<?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();
$input = getJsonInput();

$targetSessionId = (int)($input['session_id'] ?? 0);
if ($targetSessionId <= 0) {
    jsonResponse(false, 'session_id is required', null, 422);
}

$find = $pdo->prepare('SELECT id, user_id FROM user_sessions WHERE id = :id LIMIT 1');
$find->execute(['id' => $targetSessionId]);
$session = $find->fetch();

if (!$session || (int)$session['user_id'] !== (int)$user['id']) {
    jsonResponse(false, 'Session not found', null, 404);
}

$revoke = $pdo->prepare('UPDATE user_sessions SET is_revoked = 1, updated_at = NOW() WHERE id = :id');
$revoke->execute(['id' => $targetSessionId]);

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

jsonResponse(true, 'Session revoked successfully', [
    'session_id' => $targetSessionId,
    'is_current' => ($targetSessionId === (int)$user['session_id']),
]);
