<?php
session_start();
require_once(__DIR__ . "/../inc/config.inc.php");
require_once(__DIR__ . "/../inc/functions.inc.php");

// 1) Token in DB löschen (nur dieses Gerät)
if (!empty($_COOKIE['identifier'])) {
    $identifier = (string)$_COOKIE['identifier'];

    $stmt = $pdo->prepare("DELETE FROM securitytokens WHERE identifier = :i AND user_type = 'admin'");
    $stmt->execute([':i' => $identifier]);
}

// 2) Session sauber leeren
$_SESSION = [];
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 3600, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
}
session_destroy();

// 3) Remember-me Cookies löschen (mit gleichen Optionen wie gesetzt)
$isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        || ((int)($_SERVER['SERVER_PORT'] ?? 0) === 443);

$cookieOpts = [
    'expires'  => time() - 3600,
    'path'     => '/',
    'secure'   => $isHttps,
    'httponly' => true,
    'samesite' => 'Lax',
];

setcookie('identifier', '', $cookieOpts);
setcookie('securitytoken', '', $cookieOpts);

include("templates/header.inc.php");
?>
<div class="container main-container">
Der Logout war erfolgreich. <a href="login.php">Zurück zum Login</a>.
</div>
<?php include("templates/footer.inc.php"); ?>
