<?php

function e(?string $string): string
{
    return htmlspecialchars($string ?? '', ENT_QUOTES, 'UTF-8');
}

function csrf_field(): string
{
    return CSRF::field();
}

function csrf_token(): string
{
    return CSRF::token();
}

/**
 * BUG 2 FIX: Cache old data on first access so multiple calls work
 */
function old(string $field, string $default = ''): string
{
    static $oldData = null;
    if ($oldData === null) {
        $oldData = Session::getFlash('old');
        if ($oldData === null) {
            // Check if it's still in the flash array (not yet consumed)
            $oldData = $_SESSION['_flash']['old'] ?? [];
            unset($_SESSION['_flash']['old']);
        }
        if (!is_array($oldData)) {
            $oldData = [];
        }
    }
    return e($oldData[$field] ?? $default);
}

function session_flash(string $key)
{
    return Session::getFlash($key);
}

function auth_user(?string $field = null)
{
    return Auth::user($field);
}

function auth_can(string $permission): bool
{
    return Gate::can($permission);
}

function auth_id(): ?int
{
    return Auth::id();
}

function url(string $path = ''): string
{
    return '/' . ltrim($path, '/');
}

function module_asset(string $module, string $path): string
{
    return '/modules/' . $module . '/' . ltrim($path, '/');
}

function format_date(?string $date, ?string $format = null): string
{
    if (!$date) return '';
    $format = $format ?? Config::get('date_format', 'Y-m-d');
    $ts = strtotime($date);
    return $ts ? date($format, $ts) : '';
}

function format_datetime(?string $dt): string
{
    if (!$dt) return '';
    $format = Config::get('datetime_format', 'Y-m-d H:i:s');
    $ts = strtotime($dt);
    return $ts ? date($format, $ts) : '';
}

function format_money($amount, ?string $symbol = null): string
{
    $symbol = $symbol ?? Config::get('default_currency', 'EGP');
    return number_format((float)$amount, 2) . ' ' . $symbol;
}

function format_number($n, int $decimals = 2): string
{
    return number_format((float)$n, $decimals);
}

function money($amount): string
{
    return format_money($amount);
}

function time_ago(?string $datetime): string
{
    if (!$datetime) return '';
    $ts = strtotime($datetime);
    if (!$ts) return '';
    $diff = time() - $ts;
    if ($diff < 0) return 'just now';
    if ($diff < 60) return 'just now';
    if ($diff < 3600) return floor($diff / 60) . 'm ago';
    if ($diff < 86400) return floor($diff / 3600) . 'h ago';
    if ($diff < 2592000) return floor($diff / 86400) . 'd ago';
    return format_date($datetime);
}

function str_limit(string $string, int $limit = 100, string $end = '...'): string
{
    if (mb_strlen($string) <= $limit) return $string;
    return mb_substr($string, 0, $limit) . $end;
}

function is_rtl(): bool
{
    return Lang::isRtl();
}

function current_lang(): string
{
    return Lang::current();
}

function lang(string $key, array $replacements = []): string
{
    return Lang::get($key, $replacements);
}

function dd($var): void
{
    echo '<pre>';
    var_dump($var);
    echo '</pre>';
    die;
}

function status_badge(string $status): string
{
    $map = [
        'active' => 'success', 'pending' => 'warning', 'draft' => 'secondary',
        'suspended' => 'danger', 'frozen' => 'info', 'terminated' => 'dark',
        'expired' => 'secondary', 'cancelled' => 'danger', 'completed' => 'success',
        'approved' => 'success', 'rejected' => 'danger', 'overdue' => 'danger',
        'paid' => 'success', 'partially_paid' => 'warning', 'issued' => 'primary',
        'pending_approval' => 'warning', 'under_review' => 'info',
        'open' => 'primary', 'closed' => 'secondary', 'resolved' => 'success',
        'submitted' => 'info', 'in_progress' => 'primary', 'escalated' => 'danger',
        'deceased' => 'dark', 'transferred' => 'info', 'void' => 'dark',
        'written_off' => 'dark', 'defaulted' => 'danger', 'bounced' => 'danger',
        'waitlisted' => 'info', 'enrolled' => 'primary',
    ];
    $class = $map[$status] ?? 'secondary';
    $label = ucfirst(str_replace('_', ' ', $status));
    return '<span class="badge bg-' . $class . '">' . e($label) . '</span>';
}

function active_class(string $path): string
{
    $uri = $_GET['_url'] ?? '';
    $uri = '/' . ltrim($uri, '/');
    return str_starts_with($uri, $path) ? 'active' : '';
}

function selected($value, $current): string
{
    return ((string)$value === (string)$current) ? 'selected' : '';
}

function checked($value, $current): string
{
    return ((string)$value === (string)$current) ? 'checked' : '';
}

/**
 * Render flash alerts — safe to call from any layout.
 * Returns array of ['type' => '...', 'message' => '...']
 */
function get_flash_alerts(): array
{
    static $consumed = false;
    static $cached = [];

    if (!$consumed) {
        $consumed = true;
        $cached = Session::getFlash('alerts') ?? [];
        $error = Session::getFlash('error');
        $success = Session::getFlash('success');
        $warning = Session::getFlash('warning');
        $info = Session::getFlash('info');
        if ($error)   $cached[] = ['type' => 'danger', 'message' => $error];
        if ($success)  $cached[] = ['type' => 'success', 'message' => $success];
        if ($warning)  $cached[] = ['type' => 'warning', 'message' => $warning];
        if ($info)     $cached[] = ['type' => 'info', 'message' => $info];
    }
    return $cached;
}