<?php
namespace App\Core;
final class Security {
    public static function generateCSRF() {
        if (session_status() === PHP_SESSION_NONE) session_start();
        if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(32));
        return $_SESSION['csrf'];
    }
    public static function checkCSRF() {
        if (session_status() === PHP_SESSION_NONE) session_start();
        if (empty($_POST['csrf']) || !hash_equals($_SESSION['csrf'] ?? '', $_POST['csrf'])) {
            http_response_code(403); die('CSRF Invalido');
        }
        return true;
    }

    public static function checkCSRFJson()
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

        $csrfToken = '';
        if (isset($_SERVER['HTTP_X_CSRF_TOKEN'])) {
            $csrfToken = $_SERVER['HTTP_X_CSRF_TOKEN'];
        } else {
            $json = file_get_contents('php://input');
            $data = json_decode($json, true);
            if (isset($data['csrf'])) {
                $csrfToken = $data['csrf'];
            }
        }

        if (empty($csrfToken) || !hash_equals($_SESSION['csrf'] ?? '', $csrfToken)) {
            http_response_code(403);
            // Return a JSON error message to be consistent with the API
            header('Content-Type: application/json');
            die(json_encode(['error' => 'CSRF Invalido']));
        }

        return true;
    }
}