<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/constants.php';
require_once __DIR__ . '/../core/Response.php';

session_name(SESSION_NAME);
session_start();

/**
 * Apply only to state-changing methods
 */
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

if (!in_array($method, ['POST', 'PUT', 'PATCH', 'DELETE'], true)) {
    return;
}

/**
 * Require CSRF token
 */
$token = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';

if ($token === '' || empty($_SESSION['csrf_token'])) {
    Response::error('CSRF token missing', 403);
}

/**
 * Timing-safe comparison
 */
if (!hash_equals($_SESSION['csrf_token'], $token)) {
    Response::error('Invalid CSRF token', 403);
}
