<?php
declare(strict_types=1);

function post(string $key, mixed $default = ''): mixed
{
    return $_POST[$key] ?? $default;
}

function get_value(string $key, mixed $default = ''): mixed
{
    return $_GET[$key] ?? $default;
}

function is_post(): bool
{
    return ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST';
}

function set_flash(string $type, string $message): void
{
    $_SESSION['flash_message'] = [
        'type' => $type,
        'message' => $message
    ];
}

function get_flash(): ?array
{
    if (!isset($_SESSION['flash_message'])) {
        return null;
    }

    $flash = $_SESSION['flash_message'];
    unset($_SESSION['flash_message']);

    return $flash;
}

function old(string $key, mixed $default = ''): mixed
{
    return $_POST[$key] ?? $default;
}

function admin_role_label(string $role): string
{
    return match ($role) {
        'super_admin' => 'Super Admin',
        'admin' => 'Admin',
        default => 'Staff',
    };
}

function admin_status_label(int $status): string
{
    return $status === 1 ? 'Active' : 'Inactive';
}

function format_datetime(?string $datetime): string
{
    if (empty($datetime)) {
        return '-';
    }

    return date('Y-m-d h:i A', strtotime($datetime));
}


if (!function_exists('admin_csrf_token')) {
    function admin_csrf_token(string $context = 'default'): string
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        if (!isset($_SESSION['admin_csrf_tokens']) || !is_array($_SESSION['admin_csrf_tokens'])) {
            $_SESSION['admin_csrf_tokens'] = [];
        }
        $context = preg_replace('/[^a-zA-Z0-9_\-:.]/', '_', $context) ?: 'default';
        if (empty($_SESSION['admin_csrf_tokens'][$context])) {
            $_SESSION['admin_csrf_tokens'][$context] = bin2hex(random_bytes(32));
        }
        return (string) $_SESSION['admin_csrf_tokens'][$context];
    }
}

if (!function_exists('admin_csrf_input')) {
    function admin_csrf_input(string $context = 'default'): string
    {
        return '<input type="hidden" name="_csrf_context" value="' . e($context) . '">' .
               '<input type="hidden" name="_csrf_token" value="' . e(admin_csrf_token($context)) . '">';
    }
}

if (!function_exists('admin_verify_csrf')) {
    function admin_verify_csrf(string $context = 'default', ?string $token = null): bool
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        $context = preg_replace('/[^a-zA-Z0-9_\-:.]/', '_', $context) ?: 'default';
        $token = $token ?? (string)($_POST['_csrf_token'] ?? '');
        $stored = (string)($_SESSION['admin_csrf_tokens'][$context] ?? '');
        return $stored !== '' && $token !== '' && hash_equals($stored, $token);
    }
}

if (!function_exists('admin_require_post_action')) {
    function admin_require_post_action(string $context, string $fallbackUrl, string $message = 'انتهت صلاحية الطلب أو طريقة الإرسال غير صحيحة. حاول مرة أخرى.'): void
    {
        if (!is_post() || !admin_verify_csrf($context)) {
            set_flash('error', $message);
            redirect_to($fallbackUrl);
        }
    }
}

if (!function_exists('admin_post_action_form')) {
    function admin_post_action_form(string $action, string $label, string $class = '', string $context = 'default', array $fields = [], string $confirm = ''): string
    {
        $confirmAttr = $confirm !== '' ? ' onsubmit="return confirm(' . htmlspecialchars(json_encode($confirm, JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8') . ');"' : '';
        $html = '<form method="post" action="' . e($action) . '" style="display:inline"' . $confirmAttr . '>';
        $html .= admin_csrf_input($context);
        foreach ($fields as $key => $value) {
            $html .= '<input type="hidden" name="' . e((string)$key) . '" value="' . e((string)$value) . '">';
        }
        $buttonClass = trim($class) !== '' ? trim($class) : 'admin-post-action-button';
        $html .= '<button type="submit" class="' . e($buttonClass) . '">' . e($label) . '</button>';
        $html .= '</form>';
        return $html;
    }
}

?>
