<?php

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/helpers.php';
require_once __DIR__ . '/../../middleware/auth.php';

if (getMethod() !== 'POST') {
    jsonResponse(false, 'Method not allowed', null, 405);
}

global $pdo;
$config = require __DIR__ . '/../../config/app.php';
$user = requireAuth();
$token = getRequestToken($config);
$tokenHash = hashToken($token);

$stmt = $pdo->prepare('UPDATE user_sessions SET is_revoked = 1, updated_at = NOW() WHERE token_hash = :token_hash');
$stmt->execute(['token_hash' => $tokenHash]);

setcookie($config['auth']['session_cookie'], '', [
    'expires' => time() - 3600,
    'path' => '/',
    'secure' => isset($_SERVER['HTTPS']),
    'httponly' => true,
    'samesite' => 'Lax',
]);

$log = $pdo->prepare('INSERT INTO user_login_history (user_id, ip, device, browser, platform, user_agent, status, logout_at) VALUES (:user_id, :ip, :device, :browser, :platform, :user_agent, :status, NOW())');
$log->execute([
    'user_id' => $user['id'],
    'ip' => getClientIp(),
    'device' => 'Unknown Device',
    'browser' => 'Unknown Browser',
    'platform' => 'Unknown Platform',
    'user_agent' => getUserAgent(),
    'status' => 'logout',
]);

jsonResponse(true, 'Logout successful');
