<?php
require_once '../config.php';
require_once '../middleware.php';

header('Content-Type: application/json');

// Get request method
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    // Get the encrypted payload
    $encrypted_payload = file_get_contents('php://input');
    if (empty($encrypted_payload)) {
        sendResponse(400, 'Empty request body');
    }

    // Decrypt the payload
    $data = decryptRequestPayload($encrypted_payload);
    if (!$data) {
        sendResponse(400, 'Invalid request body');
    }

    $device_id = $_SERVER['HTTP_DEVICE_ID'] ?? '';
    $session_token = $_SERVER['HTTP_SESSION_TOKEN'] ?? '';

    validateInput($data, ['user_id']);
    $user_id = $data['user_id'];

    authenticateSession($user_id, $device_id, $session_token);
    rateLimit($user_id);

    $conn = getDbConnection();

    $stmt = $conn->prepare("DELETE FROM session_tokens WHERE user_id = ? AND device_id = ?");
    $stmt->bind_param("is", $user_id, $device_id);
    $stmt->execute();

    sendResponse(200, 'Logout successful');

    $stmt->close();
    $conn->close();
} else {
    sendResponse(405, 'Method Not Allowed');
}
?>