<?php

declare(strict_types=1);

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

if (!function_exists('sa_normalize_page')) {
    function sa_normalize_page(mixed $value): int
    {
        return max(1, (int) $value);
    }
}

if (!function_exists('sa_normalize_per_page')) {
    function sa_normalize_per_page(mixed $value): int|string
    {
        $value = strtolower(trim((string) $value));
        if (!in_array($value, ['100', '200', '400', 'all'], true)) {
            return 100;
        }
        return $value === 'all' ? 'all' : (int) $value;
    }
}

if (!function_exists('sa_query_url')) {
    function sa_query_url(array $changes = [], ?string $basePath = null): string
    {
        $query = array_merge($_GET, $changes);
        foreach ($query as $key => $value) {
            if ($value === '' || $value === null) {
                unset($query[$key]);
            }
        }
        $path = $basePath ?? basename((string) ($_SERVER['PHP_SELF'] ?? ''));
        $suffix = http_build_query($query);
        return $path . ($suffix !== '' ? '?' . $suffix : '');
    }
}

if (!function_exists('sa_pagination_pages')) {
    function sa_pagination_pages(int $currentPage, int $totalPages, int $radius = 2): array
    {
        if ($totalPages <= 1) {
            return [1];
        }
        $pages = [];
        $start = max(1, $currentPage - $radius);
        $end = min($totalPages, $currentPage + $radius);
        if ($start > 1) {
            $pages[] = 1;
            if ($start > 2) {
                $pages[] = 'ellipsis';
            }
        }
        for ($page = $start; $page <= $end; $page++) {
            $pages[] = $page;
        }
        if ($end < $totalPages) {
            if ($end < $totalPages - 1) {
                $pages[] = 'ellipsis';
            }
            $pages[] = $totalPages;
        }
        return $pages;
    }
}

if (!function_exists('sa_records_range')) {
    function sa_records_range(int $total, int $currentPage, int $perPage, int $currentCount): array
    {
        if ($total === 0 || $currentCount === 0) {
            return [0, 0];
        }
        $first = (($currentPage - 1) * $perPage) + 1;
        $last = min($total, $first + $currentCount - 1);
        return [$first, $last];
    }
}

if (!function_exists('sa_render_module_hero')) {
    function sa_render_module_hero(array $config): void
    {
        $icon = $config['icon'] ?? 'fa-grid-2';
        $eyebrow = $config['eyebrow'] ?? 'GESTIÓN SUPERADMIN';
        $title = $config['title'] ?? '';
        $description = $config['description'] ?? '';
        $count = isset($config['count']) ? (int) $config['count'] : null;
        $action = $config['action'] ?? null;
        ?>
        <section class="sa-module-hero">
            <div class="sa-module-hero__content">
                <span class="sa-module-hero__icon" aria-hidden="true"><i class="fas <?= sa_e($icon) ?>"></i></span>
                <div class="sa-module-hero__copy">
                    <?php if ($eyebrow !== ''): ?><span class="sa-module-hero__eyebrow"><?= sa_e($eyebrow) ?></span><?php endif; ?>
                    <h1><?= sa_e($title) ?></h1>
                    <?php if ($description !== ''): ?><p><?= sa_e($description) ?></p><?php endif; ?>
                </div>
            </div>
            <div class="sa-module-hero__actions">
                <span class="sa-chip"><i class="fas fa-shield-halved" aria-hidden="true"></i> Gestión Superadmin</span>
                <?php if ($count !== null): ?>
                    <span class="sa-chip"><i class="fas fa-database" aria-hidden="true"></i> <?= number_format($count) ?> registro<?= $count === 1 ? '' : 's' ?></span>
                <?php endif; ?>
                <?php if (is_array($action)): ?>
                    <?php $attrs = $action['attrs'] ?? ''; ?>
                    <button type="button" class="sa-btn sa-btn--primary" <?= $attrs ?>>
                        <i class="fas <?= sa_e($action['icon'] ?? 'fa-plus') ?>" aria-hidden="true"></i>
                        <span><?= sa_e($action['label'] ?? 'Nuevo') ?></span>
                    </button>
                <?php endif; ?>
            </div>
        </section>
        <?php
    }
}

if (!function_exists('sa_render_summary_cards')) {
    function sa_render_summary_cards(array $cards): void
    {
        if ($cards === []) {
            return;
        }
        ?>
        <section class="sa-summary-grid">
            <?php foreach (array_slice($cards, 0, 4) as $card): ?>
                <article class="sa-summary-card">
                    <span class="sa-summary-card__icon <?= sa_e($card['tone'] ?? '') ?>" aria-hidden="true"><i class="fas <?= sa_e($card['icon'] ?? 'fa-chart-simple') ?>"></i></span>
                    <div>
                        <span class="sa-summary-card__label"><?= sa_e($card['label'] ?? '') ?></span>
                        <strong class="sa-summary-card__value"><?= sa_e($card['value'] ?? '0') ?></strong>
                        <?php if (!empty($card['hint'])): ?><small><?= sa_e($card['hint']) ?></small><?php endif; ?>
                    </div>
                </article>
            <?php endforeach; ?>
        </section>
        <?php
    }
}
