<?php
declare(strict_types=1);

/**
 * /public_html/test_erp/api/auth/csrf_token.php
 * Session-bound CSRF token endpoint — TEST environment
 */

require_once __DIR__ . '/../../config/session.php';

header('Content-Type: application/json; charset=UTF-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

if (
    empty($_SESSION['csrf_token'])
    || !is_string($_SESSION['csrf_token'])
    || strlen($_SESSION['csrf_token']) < 64
) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$token = $_SESSION['csrf_token'];

header('X-CSRF-Token: ' . $token);

echo json_encode([
    'status'  => 200,
    'success' => true,
    'message' => 'CSRF token',
    'data'    => [
        'csrf_token' => $token,
    ],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
