<?php

require_once __DIR__ . '/../config.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ----------------------
// DELETE REMEMBER ME TOKEN
// ----------------------
if (!empty($_COOKIE['ts_admin_remember'])) {
    $parts = explode(':', $_COOKIE['ts_admin_remember']);

    if (count($parts) === 2) {
        [$selector] = $parts;

        if (ctype_xdigit($selector) && strlen($selector) === 24) {
            try {
                $stmt = $pdo->prepare("
                    DELETE FROM admin_remember_tokens
                    WHERE selector = ?
                ");

                $stmt->execute([
                    $selector
                ]);
            } catch (Exception $e) {
                // Do not block logout if token cleanup fails.
            }
        }
    }
}

// ----------------------
// CLEAR REMEMBER ME COOKIE
// ----------------------
setcookie('ts_admin_remember', '', [
    'expires' => time() - 3600,
    'path' => '/admin',
    'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
    'httponly' => true,
    'samesite' => 'Lax'
]);

// ----------------------
// CLEAR SESSION
// ----------------------
$_SESSION = [];

if (ini_get('session.use_cookies')) {
    $params = session_get_cookie_params();

    setcookie(session_name(), '', [
        'expires' => time() - 3600,
        'path' => $params['path'],
        'domain' => $params['domain'],
        'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
        'httponly' => true,
        'samesite' => 'Lax'
    ]);
}

session_destroy();

header('Location: /admin/login.php');
exit;