<?php

declare(strict_types=1);

/**
 * Result Helper - Core utility functions for Result Management
 */

if (!function_exists('jsonResponse')) {
    function jsonResponse(bool $success, string $message, array $data = [], int $statusCode = 200): never {
        http_response_code($statusCode);
        header('Content-Type: application/json; charset=UTF-8');
        echo json_encode([
            'success' => $success,
            'message' => $message,
            'data'    => $data
        ], JSON_UNESCAPED_UNICODE | JSON_HEX_TAG);
        exit;
    }
}

if (!function_exists('csrfField')) {
    function csrfField(): string {
        if (session_status() === PHP_SESSION_NONE) session_start();
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }
        $token = htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8');
        return '<input type="hidden" name="csrf_token" value="' . $token . '">';
    }
}

if (!function_exists('verifyCsrfToken')) {
    function verifyCsrfToken(): void {
        if (session_status() === PHP_SESSION_NONE) session_start();
        $token = $_POST['csrf_token'] ?? '';
        if (empty($token) || !hash_equals($_SESSION['csrf_token'] ?? '', $token)) {
            jsonResponse(false, 'Security breach: Invalid CSRF token.', [], 403);
        }
    }
}

if (!function_exists('requirePostRequest')) {
    function requirePostRequest(): void {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            jsonResponse(false, 'Invalid request method.', [], 405);
        }
    }
}

if (!function_exists('validateId')) {
    function validateId(mixed $id): int {
        $val = filter_var($id, FILTER_VALIDATE_INT);
        return ($val !== false && $val > 0) ? $val : 0;
    }
}