<?php
require_once "config/config.php";

$secure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';

session_start();

// -------------------- Remember-Token löschen --------------------
if (!empty($_COOKIE['remember'])) {

    $token = (string)$_COOKIE['remember'];
    $tokenHash = hash('sha256', $token);

    try {
        $del = $pdo->prepare("DELETE FROM remember_tokens WHERE token_hash = :th");
        $del->execute([':th' => $tokenHash]);
    } catch (Throwable $e) {
        // fail silently
    }

    // Remember-Cookie löschen
    setcookie('remember', '', [
        'expires'  => time() - 3600,
        'path'     => '/',
        'secure'   => $secure,
        'httponly' => true,
        'samesite' => 'Lax',
    ]);
}

// -------------------- Session löschen --------------------
$_SESSION = array();

if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(
        session_name(),
        '',
        time() - 42000,
        $params["path"],
        $params["domain"],
        $params["secure"],
        $params["httponly"]
    );
}

session_destroy();

// Weiterleiten zum Login
header("location: index.php");
exit;
