<?php

declare(strict_types=1);

// ── Customer Tier / Badge ─────────────────────────────────────────────────────

function customer_tier(int $deliveredOrders): array
{
    return match (true) {
        $deliveredOrders >= 30 => ['label' => 'Platinum', 'icon' => '💎', 'class' => 'badge-platinum'],
        $deliveredOrders >= 15 => ['label' => 'Gold',     'icon' => '🥇', 'class' => 'badge-gold'],
        $deliveredOrders >= 5  => ['label' => 'Silver',   'icon' => '🥈', 'class' => 'badge-silver'],
        $deliveredOrders >= 1  => ['label' => 'Bronze',   'icon' => '🥉', 'class' => 'badge-bronze'],
        default                => ['label' => 'New',      'icon' => '🆕', 'class' => 'badge-new'],
    };
}

// ── Output / Escaping ─────────────────────────────────────────────────────────

function e(mixed $value): string
{
    return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function nl2br_e(string $value): string
{
    return nl2br(e($value));
}

// ── CSRF field helper (use in every form) ─────────────────────────────────────

function csrf_field(): string
{
    $token = \Core\Request::generateCsrfToken();
    return '<input type="hidden" name="' . CSRF_TOKEN_NAME . '" value="' . $token . '">';
}

function csrf_token(): string
{
    return \Core\Request::generateCsrfToken();
}

// ── URL helpers ───────────────────────────────────────────────────────────────

function base_url(): string
{
    // Auto-detect https so assets load correctly on SSL hosts
    $isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        || ($_SERVER['SERVER_PORT'] ?? '') === '443'
        || ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https';

    return ($isHttps ? 'https' : 'http') . '://'
        . ($_SERVER['HTTP_HOST'] ?? parse_url(APP_URL, PHP_URL_HOST))
        . rtrim(parse_url(APP_URL, PHP_URL_PATH) ?? '', '/');
}

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

function asset(string $path): string
{
    $rel  = ltrim($path, '/');
    $file = dirname(__DIR__, 2) . '/public/assets/' . $rel;
    $ver  = file_exists($file) ? filemtime($file) : APP_VERSION;
    return base_url() . '/assets/' . $rel . '?v=' . $ver;
}

function upload_url(string $path): string
{
    return base_url() . '/uploads/' . ltrim($path, '/');
}

// ── Flash alerts ──────────────────────────────────────────────────────────────

function flash_alert(): string
{
    $types = ['success', 'error', 'warning', 'info'];
    $html  = '';

    foreach ($types as $type) {
        $msg = \Core\Session::getFlash($type);
        if ($msg) {
            $bsType = $type === 'error' ? 'danger' : $type;
            $icon   = match ($type) {
                'success' => 'check-circle-fill',
                'error'   => 'x-circle-fill',
                'warning' => 'exclamation-triangle-fill',
                default   => 'info-circle-fill',
            };
            $html .= <<<HTML
            <div class="alert alert-{$bsType} alert-dismissible d-flex align-items-center fade show" role="alert">
                <i class="bi bi-{$icon} me-2 fs-5"></i>
                <div>{$msg}</div>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            HTML;
        }
    }

    return $html;
}

// ── Slug ──────────────────────────────────────────────────────────────────────

function slugify(string $text): string
{
    $text = mb_strtolower(trim($text));
    $text = preg_replace('/[^\w\s-]/u', '', $text);
    $text = preg_replace('/[\s_-]+/', '-', $text);
    return trim($text, '-');
}

// ── Dates ─────────────────────────────────────────────────────────────────────

function format_date(string $date, string $format = 'd M Y'): string
{
    return date($format, strtotime($date));
}

function format_datetime(string $date): string
{
    return date('d M Y, h:i A', strtotime($date));
}

function time_ago(string $date): string
{
    $diff = time() - strtotime($date);
    return match (true) {
        $diff < 60     => 'just now',
        $diff < 3600   => (int)($diff / 60) . ' min ago',
        $diff < 86400  => (int)($diff / 3600) . ' hr ago',
        default        => format_date($date),
    };
}

// ── Numbers ───────────────────────────────────────────────────────────────────

function money(float $amount): string
{
    static $symbol = null;
    if ($symbol === null) {
        $symbol = \Core\Database::getInstance()->fetchValue(
            "SELECT value FROM settings WHERE key_name = 'currency_symbol'"
        ) ?? 'Rs.';
    }
    return $symbol . ' ' . number_format($amount, 2);
}

// ── Order status badge ────────────────────────────────────────────────────────

function order_status_badge(string $status): string
{
    [$color, $label] = match ($status) {
        'pending'    => ['warning',   'Pending'],
        'confirmed'  => ['primary',   'Confirmed'],
        'cooking'    => ['info',      'Cooking'],
        'ready'      => ['secondary', 'Ready'],
        'picked_up'  => ['dark',      'Picked Up'],
        'on_the_way' => ['purple',    'On the Way'],
        'delivered'  => ['success',   'Delivered'],
        'cancelled'  => ['danger',    'Cancelled'],
        default      => ['light',     ucfirst($status)],
    };

    return "<span class=\"badge bg-{$color} status-badge\">{$label}</span>";
}

// ── Pagination ────────────────────────────────────────────────────────────────

function paginate(int $total, int $page, int $perPage, string $baseUrl): string
{
    $totalPages = (int) ceil($total / $perPage);
    if ($totalPages <= 1) return '';

    $html = '<nav><ul class="pagination pagination-sm mb-0">';

    $html .= sprintf(
        '<li class="page-item %s"><a class="page-link" href="%s?page=%d">‹ Prev</a></li>',
        $page <= 1 ? 'disabled' : '',
        $baseUrl,
        max(1, $page - 1)
    );

    $start = max(1, $page - 2);
    $end   = min($totalPages, $page + 2);

    if ($start > 1) {
        $html .= '<li class="page-item disabled"><span class="page-link">…</span></li>';
    }

    for ($i = $start; $i <= $end; $i++) {
        $html .= sprintf(
            '<li class="page-item %s"><a class="page-link" href="%s?page=%d">%d</a></li>',
            $i === $page ? 'active' : '',
            $baseUrl,
            $i,
            $i
        );
    }

    if ($end < $totalPages) {
        $html .= '<li class="page-item disabled"><span class="page-link">…</span></li>';
    }

    $html .= sprintf(
        '<li class="page-item %s"><a class="page-link" href="%s?page=%d">Next ›</a></li>',
        $page >= $totalPages ? 'disabled' : '',
        $baseUrl,
        min($totalPages, $page + 1)
    );

    $html .= '</ul></nav>';
    return $html;
}

// ── String ────────────────────────────────────────────────────────────────────

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

// ── Image placeholder ─────────────────────────────────────────────────────────

function img_placeholder(int $w = 80, int $h = 80): string
{
    return "https://placehold.co/{$w}x{$h}/f1f3f5/adb5bd?text=IMG";
}
