<?php
session_start();
require_once '../config/database.php';

// Delete remember me token from database if exists
if (isset($_COOKIE['remember_token'])) {
    $conn = getDBConnection();
    $token = $_COOKIE['remember_token'];

    // Validate token format
    if (preg_match('/^[a-f0-9]{64}$/i', $token)) {
        $hashed_token = hash('sha256', $token);

        // Delete token from database
        $stmt = $conn->prepare("DELETE FROM remember_tokens WHERE token_hash = ?");
        $stmt->bind_param("s", $hashed_token);
        $stmt->execute();
        $stmt->close();
    }

    // Delete cookie
    setcookie('remember_token', '', [
        'expires' => time() - 3600,
        'path' => '/',
        'domain' => '',
        'secure' => isset($_SERVER['HTTPS']),
        'httponly' => true,
        'samesite' => 'Strict'
    ]);

    $conn->close();
}

session_unset();
session_destroy();
header('Location: ../index.php?error=logout');
exit();
?>
