<?php
/**
 * Response helpers.
 */

declare(strict_types=1);

/**
 * Send a JSON response and exit.
 *
 * @param string|int $status   'success' | 'error' | 1 | 0 | custom string
 * @param string     $message  Human-readable message
 * @param array|null $data     Optional payload
 * @param int        $httpCode HTTP status code (default 200)
 */
function jsonResponse(string|int $status, string $message = '', ?array $data = null, int $httpCode = 200): void
{
    http_response_code($httpCode);
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');

    $payload = ['status' => $status, 'message' => $message];
    if ($data !== null) $payload['data'] = $data;

    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function jsonSuccess(string $message = 'OK', ?array $data = null): void
{
    jsonResponse('success', $message, $data, 200);
}

function jsonError(string $message = 'Error', int $httpCode = 400, ?array $data = null): void
{
    jsonResponse('error', $message, $data, $httpCode);
}

function redirect(string $url, int $code = 302): void
{
    header("Location: {$url}", true, $code);
    exit;
}

/** Escape for safe HTML output */
function e(?string $s): string
{
    return htmlspecialchars((string)$s, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
