<?php
// متغيرات متاحة: $summary, $prevSummary, $dailyChart, $byProduct, $byShipper, $byWilaya, $topOrders, $period, $dateFrom, $dateTo
$currency = __('finance.currency','DZD');

// دالة المقارنة مع الفترة السابقة
function changePercent($current, $prev): string {
    if ($prev == 0) return '';
    $pct = round((($current - $prev) / $prev) * 100, 1);
    $color = $pct >= 0 ? 'text-success' : 'text-danger';
    $icon  = $pct >= 0 ? 'bi-arrow-up-short' : 'bi-arrow-down-short';
    return "<span class=\"$color small\"><i class=\"bi $icon\"></i>{$pct}%</span>";
}

function fmtMoney(float $v): string {
    return number_format($v, 0, '.', ',');
}

function financeWilayaCode($code): string {
    $raw = trim((string)$code);
    if ($raw === '') {
        return '';
    }
    if (ctype_digit($raw)) {
        return str_pad((string)((int)$raw), 2, '0', STR_PAD_LEFT);
    }
    if (preg_match('/(\d{1,2})/', $raw, $m)) {
        return str_pad((string)((int)$m[1]), 2, '0', STR_PAD_LEFT);
    }
    return '';
}

$dzStatesPath = ROOT_PATH . '/storage/data/states_dz.json';
$dzStatesPayload = file_exists($dzStatesPath) ? json_decode((string)file_get_contents($dzStatesPath), true) : [];
$dzStates = is_array($dzStatesPayload['states'] ?? null) ? $dzStatesPayload['states'] : [];

$wilayaStatsByCode = [];
foreach ($byWilaya as $row) {
    $code = financeWilayaCode($row['wilaya_code'] ?? '');
    if ($code === '') {
        continue;
    }

    $wilayaStatsByCode[$code] = [
        'orders_count' => (int)($row['orders_count'] ?? 0),
        'revenue' => (float)($row['revenue'] ?? 0),
        'label' => (string)($row['city_name'] ?? ''),
    ];
}

$wilayaMapData = [];
foreach ($dzStates as $state) {
    $code = financeWilayaCode($state['code'] ?? $state['id'] ?? '');
    if ($code === '') {
        continue;
    }

    $stats = $wilayaStatsByCode[$code] ?? null;
    $wilayaMapData[] = [
        'code' => $code,
        'name' => (string)($state['name'] ?? ''),
        'ar_name' => (string)($state['ar_name'] ?? ''),
        'label' => (string)($state['ar_name'] ?? $state['name'] ?? (__('finance.wilaya_prefix', 'Wilaya ') . $code)),
        'orders_count' => (int)($stats['orders_count'] ?? 0),
        'revenue' => (float)($stats['revenue'] ?? 0),
    ];
}

if (empty($wilayaMapData) && !empty($byWilaya)) {
    foreach ($byWilaya as $row) {
        $code = financeWilayaCode($row['wilaya_code'] ?? '');
        if ($code === '') {
            continue;
        }
        $wilayaMapData[] = [
            'code' => $code,
            'name' => (string)($row['city_name'] ?? ''),
            'ar_name' => (string)($row['city_name'] ?? ''),
            'label' => (string)($row['city_name'] ?: (__('finance.wilaya_prefix', 'Wilaya ') . $code)),
            'orders_count' => (int)($row['orders_count'] ?? 0),
            'revenue' => (float)($row['revenue'] ?? 0),
        ];
    }
}

usort($wilayaMapData, static function (array $a, array $b): int {
    return $b['orders_count'] <=> $a['orders_count'];
});

$financeMapSvgMarkup = '';
$financeMapAvailableCodes = [];
$financeMapSvgPath = ROOT_PATH . '/storage/data/algeria_wilayas_blank_2020.svg';

if (file_exists($financeMapSvgPath)) {
    $rawSvg = (string)file_get_contents($financeMapSvgPath);

    if ($rawSvg !== '' && class_exists(\DOMDocument::class)) {
        $svgDom = new DOMDocument();
        $svgDom->preserveWhiteSpace = false;

        if (@$svgDom->loadXML($rawSvg)) {
            $xpath = new DOMXPath($svgDom);
            $xpath->registerNamespace('svg', 'http://www.w3.org/2000/svg');
            $layer = $xpath->query('//*[@id="layer4"]')->item(0);

            if ($layer instanceof DOMElement) {
                $mapDom = new DOMDocument('1.0', 'UTF-8');
                $mapDom->formatOutput = false;
                $svg = $mapDom->createElementNS('http://www.w3.org/2000/svg', 'svg');
                $svg->setAttribute('id', 'algeriaFinanceMap');
                $svg->setAttribute('class', 'finance-map-svg finance-province-map');
                $svg->setAttribute('viewBox', '0 0 508 500');
                $svg->setAttribute('aria-label', (string)__('finance.algeria_map', 'Algeria Orders Map'));
                $mapDom->appendChild($svg);

                foreach ($xpath->query('.//svg:path', $layer) as $pathNode) {
                    if (!$pathNode instanceof DOMElement) {
                        continue;
                    }

                    $rawId = trim((string)$pathNode->getAttribute('id'));
                    if (!preg_match('/^(\d{2})\s+(.+)$/u', $rawId, $matches)) {
                        continue;
                    }

                    $code = $matches[1];
                    $name = trim($matches[2]);

                    $clone = $mapDom->importNode($pathNode, true);
                    if (!$clone instanceof DOMElement) {
                        continue;
                    }

                    $clone->setAttribute('class', 'finance-map-region');
                    $clone->setAttribute('data-wilaya-code', $code);
                    $clone->setAttribute('data-wilaya-name', $name);
                    $clone->removeAttribute('style');
                    $svg->appendChild($clone);
                    $financeMapAvailableCodes[] = $code;
                }

                $financeMapSvgMarkup = $mapDom->saveXML($svg) ?: '';
                $financeMapAvailableCodes = array_values(array_unique($financeMapAvailableCodes));
            }
        }
    }

    if ($financeMapSvgMarkup === '' && $rawSvg !== '') {
        if (preg_match('/<g[^>]*id=\"layer4\"[^>]*>(.*?)<\/g>/si', $rawSvg, $layerMatch)) {
            $layerMarkup = $layerMatch[1];
            $pathsMarkup = '';

            if (preg_match_all('/<path\b([^>]*)>/si', $layerMarkup, $pathMatches)) {
                foreach ($pathMatches[1] as $attrs) {
                    if (!preg_match('/\bid=\"(\d{2})\s+([^\"]+)\"/u', $attrs, $idMatch)) {
                        continue;
                    }
                    if (!preg_match('/\bd=\"([^\"]+)\"/u', $attrs, $dMatch)) {
                        continue;
                    }

                    $code = $idMatch[1];
                    $name = trim($idMatch[2]);
                    $d = $dMatch[1];
                    $pathsMarkup .= '<path class="finance-map-region" data-wilaya-code="' . htmlspecialchars($code, ENT_QUOTES, 'UTF-8') . '" data-wilaya-name="' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '" d="' . htmlspecialchars($d, ENT_QUOTES, 'UTF-8') . '"></path>';
                    $financeMapAvailableCodes[] = $code;
                }
            }

            if ($pathsMarkup !== '') {
                $financeMapSvgMarkup = '<svg id="algeriaFinanceMap" class="finance-map-svg finance-province-map" viewBox="0 0 508 500" aria-label="' . htmlspecialchars((string)__('finance.algeria_map', 'Algeria Orders Map'), ENT_QUOTES, 'UTF-8') . '">' . $pathsMarkup . '</svg>';
                $financeMapAvailableCodes = array_values(array_unique($financeMapAvailableCodes));
            }
        }
    }
}

$wilayaLeaders = array_values(array_filter(
    $wilayaMapData,
    static fn(array $item): bool => $item['orders_count'] > 0 && (empty($financeMapAvailableCodes) || in_array($item['code'], $financeMapAvailableCodes, true))
));
$wilayaLeaders = array_slice($wilayaLeaders, 0, 6);

$defaultSelectedWilaya = $wilayaLeaders[0] ?? null;
if (!$defaultSelectedWilaya) {
    foreach ($wilayaMapData as $item) {
        if (empty($financeMapAvailableCodes) || in_array($item['code'], $financeMapAvailableCodes, true)) {
            $defaultSelectedWilaya = $item;
            break;
        }
    }
}
?>

<style>
.finance-map-card {
    overflow: hidden;
}

.finance-map-shell {
    display: grid;
    grid-template-columns: minmax(0, 1.7fr) minmax(320px, 0.9fr);
    gap: 1.25rem;
}

.finance-map-stage {
    position: relative;
    min-height: 680px;
    border-radius: 24px;
    padding: 1.25rem;
    background:
        radial-gradient(circle at 15% 20%, rgba(13, 110, 253, 0.16), transparent 30%),
        radial-gradient(circle at 80% 18%, rgba(13, 202, 240, 0.14), transparent 28%),
        linear-gradient(180deg, #ffffff 0%, #f5f9ff 100%);
    border: 1px solid rgba(13, 110, 253, 0.08);
}

.finance-map-stage::before {
    content: "";
    position: absolute;
    inset: 18px;
    border-radius: 20px;
    background-image:
        linear-gradient(rgba(13, 110, 253, 0.045) 1px, transparent 1px),
        linear-gradient(90deg, rgba(13, 110, 253, 0.045) 1px, transparent 1px);
    background-size: 32px 32px;
    pointer-events: none;
}

.finance-map-svg {
    position: relative;
    z-index: 1;
    width: 100%;
    height: auto;
    max-height: 760px;
}

.finance-map-svg .finance-map-region {
    fill: #edf4ff;
    stroke: rgba(255, 255, 255, 0.96);
    stroke-width: 1.25;
    vector-effect: non-scaling-stroke;
    cursor: pointer;
    transition: fill .18s ease, opacity .18s ease, transform .18s ease, filter .18s ease;
}

.finance-map-svg .finance-map-region:hover {
    filter: brightness(1.03);
}

.finance-map-svg .finance-map-region.is-selected {
    stroke: #0f172a;
    stroke-width: 1.8;
    filter: drop-shadow(0 14px 22px rgba(37, 99, 235, 0.22));
}

.finance-map-svg.is-dimmed .finance-map-region {
    opacity: .44;
}

.finance-map-svg.is-dimmed .finance-map-region.is-selected,
.finance-map-svg.is-dimmed .finance-map-region:hover {
    opacity: 1;
}

.finance-map-tooltip {
    position: absolute;
    z-index: 3;
    min-width: 200px;
    max-width: 250px;
    padding: .8rem .9rem;
    border-radius: 16px;
    background: rgba(15, 23, 42, 0.95);
    color: #fff;
    box-shadow: 0 20px 35px rgba(15, 23, 42, 0.22);
    opacity: 0;
    transform: translateY(8px);
    pointer-events: none;
    transition: opacity .16s ease, transform .16s ease;
}

.finance-map-tooltip.is-visible {
    opacity: 1;
    transform: translateY(0);
}

.finance-map-tooltip .finance-map-tooltip-title {
    font-weight: 700;
    margin-bottom: .2rem;
}

.finance-map-tooltip .finance-map-tooltip-meta {
    font-size: .83rem;
    color: rgba(255,255,255,.78);
}

.finance-map-legend {
    position: absolute;
    right: 1.35rem;
    bottom: 1.35rem;
    z-index: 2;
    display: inline-flex;
    align-items: center;
    gap: .75rem;
    padding: .7rem .9rem;
    border-radius: 999px;
    background: rgba(255, 255, 255, 0.92);
    border: 1px solid rgba(13, 110, 253, 0.08);
    backdrop-filter: blur(12px);
    box-shadow: 0 12px 30px rgba(15, 23, 42, 0.08);
    font-size: .82rem;
    color: #475569;
}

.finance-map-legend-gradient {
    width: 148px;
    height: 10px;
    border-radius: 999px;
    background: linear-gradient(90deg, #dbeafe 0%, #60a5fa 40%, #2563eb 100%);
}

.finance-map-sidebar {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.finance-map-hero {
    padding: 1.15rem 1.15rem 1rem;
    border-radius: 22px;
    color: #fff;
    background: linear-gradient(145deg, #0f172a 0%, #1d4ed8 62%, #38bdf8 100%);
    box-shadow: 0 18px 38px rgba(29, 78, 216, 0.22);
}

.finance-map-hero .badge {
    background: rgba(255,255,255,.14);
    border: 1px solid rgba(255,255,255,.18);
    color: #fff;
}

.finance-map-selected-name {
    font-size: 1.6rem;
    font-weight: 800;
    line-height: 1.15;
    margin: .55rem 0 .35rem;
}

.finance-map-selected-subtitle {
    color: rgba(255,255,255,.78);
    font-size: .92rem;
}

.finance-map-metric-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: .75rem;
}

.finance-map-metric {
    padding: .95rem 1rem;
    border-radius: 18px;
    background: #fff;
    border: 1px solid rgba(15, 23, 42, 0.06);
    box-shadow: 0 10px 24px rgba(15, 23, 42, 0.06);
}

.finance-map-metric-label {
    color: #64748b;
    font-size: .83rem;
    margin-bottom: .35rem;
}

.finance-map-metric-value {
    color: #0f172a;
    font-size: 1.35rem;
    font-weight: 800;
}

.finance-map-toplist {
    background: #fff;
    border: 1px solid rgba(15, 23, 42, 0.06);
    border-radius: 22px;
    box-shadow: 0 10px 24px rgba(15, 23, 42, 0.06);
    overflow: hidden;
}

.finance-map-toplist-header {
    padding: 1rem 1.1rem;
    border-bottom: 1px solid rgba(15, 23, 42, 0.06);
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.finance-map-toplist-body {
    padding: .45rem;
}

.finance-map-top-item {
    width: 100%;
    border: 0;
    background: transparent;
    border-radius: 18px;
    padding: .75rem .85rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: .75rem;
    text-align: inherit;
    transition: background .16s ease, transform .16s ease;
}

.finance-map-top-item:hover,
.finance-map-top-item.is-selected {
    background: rgba(37, 99, 235, 0.08);
}

.finance-map-top-item.is-selected {
    box-shadow: inset 0 0 0 1px rgba(37, 99, 235, 0.16);
}

.finance-map-top-item-rank {
    width: 34px;
    height: 34px;
    flex: 0 0 34px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 999px;
    background: #eff6ff;
    color: #1d4ed8;
    font-weight: 800;
}

.finance-map-top-item-name {
    font-weight: 700;
    color: #0f172a;
}

.finance-map-top-item-meta {
    font-size: .82rem;
    color: #64748b;
}

.finance-map-empty {
    text-align: center;
    color: #64748b;
    padding: 1.25rem;
}

.finance-wilaya-row.is-selected {
    background: rgba(13, 110, 253, 0.08);
}

@media (max-width: 1199.98px) {
    .finance-map-shell {
        grid-template-columns: 1fr;
    }

    .finance-map-stage {
        min-height: 540px;
    }
}

@media (max-width: 767.98px) {
    .finance-map-stage {
        min-height: 440px;
        padding: .85rem;
    }

    .finance-map-legend {
        position: static;
        margin-top: .8rem;
        width: 100%;
        justify-content: center;
        border-radius: 18px;
    }

    .finance-map-selected-name {
        font-size: 1.35rem;
    }
}
</style>

<div class="content-wrapper">
<section class="content pt-3">
<div class="container-fluid pb-5">

    <!-- ===== HEADER ===== -->
    <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
        <div>
            <h3 class="mb-1 fw-bold">
                <i class="bi bi-graph-up-arrow me-2 text-primary"></i>
                <?= __('finance.title','الإحصائيات المالية') ?>
            </h3>
            <p class="text-muted mb-0 small">
                <?= __('finance.subtitle','Detailed analysis of revenue, costs and net profit') ?>
            </p>
        </div>

        <!-- PERIOD FILTER -->
        <form method="GET" action="/admin/finance" class="d-flex flex-wrap gap-2 align-items-center">
            <div class="btn-group btn-group-sm" role="group">
                <?php foreach (['7'=>__('finance.period.7','7 days'),'30'=>__('finance.period.30','30 days'),'90'=>__('finance.period.90','90 days'),'365'=>__('finance.period.year','Year')] as $val=>$lbl): ?>
                    <a href="/admin/finance?period=<?= $val ?>"
                       class="btn <?= $period == $val && !request_has_custom_range() ? 'btn-primary' : 'btn-outline-secondary' ?>">
                        <?= $lbl ?>
                    </a>
                <?php endforeach; ?>
            </div>

            <div class="d-flex gap-1 align-items-center">
                <input type="date" name="start" class="form-control form-control-sm"
                       value="<?= htmlspecialchars($_GET['start'] ?? '') ?>"
                       style="max-width:140px">
                <span class="text-muted">→</span>
                <input type="date" name="end" class="form-control form-control-sm"
                       value="<?= htmlspecialchars($_GET['end'] ?? '') ?>"
                       style="max-width:140px">
                <button type="submit" class="btn btn-sm btn-outline-primary">
                    <i class="bi bi-funnel"></i>
                </button>
            </div>
        </form>
    </div>

    <!-- ===== KPI CARDS ===== -->
    <div class="row g-3 mb-4">

        <!-- إجمالي المداخيل -->
        <div class="col-6 col-xl-3">
            <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #0d6efd !important">
                <div class="card-body px-4 py-3">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div class="rounded-circle d-flex align-items-center justify-content-center bg-primary-subtle"
                             style="width:42px;height:42px">
                            <i class="bi bi-wallet2 fs-5 text-primary"></i>
                        </div>
                        <?= changePercent($summary['revenue_total'], $prevSummary['revenue_total']) ?>
                    </div>
                    <div class="fs-4 fw-bold"><?= fmtMoney($summary['revenue_total']) ?> <small class="fs-6 text-muted"><?= $currency ?></small></div>
                    <div class="text-muted small mt-1"><?= __('finance.kpi.total_revenue','Total Revenue') ?></div>
                    <div class="text-muted smaller mt-1">
                        <span class="me-2"><?= __('finance.products','Products') ?>: <?= fmtMoney($summary['revenue_products']) ?></span>
                        <span><?= __('finance.shipping','Shipping') ?>: <?= fmtMoney($summary['revenue_shipping']) ?></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- تكلفة الشحن -->
        <div class="col-6 col-xl-3">
            <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #dc3545 !important">
                <div class="card-body px-4 py-3">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div class="rounded-circle d-flex align-items-center justify-content-center bg-danger-subtle"
                             style="width:42px;height:42px">
                            <i class="bi bi-truck fs-5 text-danger"></i>
                        </div>
                    </div>
                    <div class="fs-4 fw-bold"><?= fmtMoney($summary['shipping_cost']) ?> <small class="fs-6 text-muted"><?= $currency ?></small></div>
                    <div class="text-muted small mt-1"><?= __('finance.kpi.shipping_cost','Actual Shipping Cost') ?></div>
                    <div class="mt-1">
                        <?php $margin = $summary['shipping_margin']; ?>
                        <span class="badge <?= $margin >= 0 ? 'bg-success-subtle text-success' : 'bg-danger-subtle text-danger' ?> border <?= $margin >= 0 ? 'border-success-subtle' : 'border-danger-subtle' ?>">
                            <?= __('finance.shipping_margin','Shipping Margin') ?>: <?= ($margin >= 0 ? '+' : '') . fmtMoney($margin) ?> <?= $currency ?>
                        </span>
                    </div>
                </div>
            </div>
        </div>

        <!-- المرتجعات -->
        <div class="col-6 col-xl-3">
            <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #ffc107 !important">
                <div class="card-body px-4 py-3">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div class="rounded-circle d-flex align-items-center justify-content-center bg-warning-subtle"
                             style="width:42px;height:42px">
                            <i class="bi bi-arrow-return-left fs-5 text-warning"></i>
                        </div>
                    </div>
                    <div class="fs-4 fw-bold"><?= fmtMoney($summary['returns_value']) ?> <small class="fs-6 text-muted"><?= $currency ?></small></div>
                    <div class="text-muted small mt-1"><?= __('finance.kpi.returns','Returns Loss') ?></div>
                    <div class="text-muted smaller mt-1"><?= $summary['returns_count'] ?> <?= __('finance.returns_unit','returns') ?></div>
                </div>
            </div>
        </div>

        <!-- صافي الربح -->
        <div class="col-6 col-xl-3">
            <?php $profit = $summary['net_profit']; $profitPositive = $profit >= 0; ?>
            <div class="card border-0 shadow-sm h-100" style="border-top:3px solid <?= $profitPositive ? '#198754' : '#dc3545' ?> !important">
                <div class="card-body px-4 py-3">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div class="rounded-circle d-flex align-items-center justify-content-center"
                             style="width:42px;height:42px;background:rgba(<?= $profitPositive ? '25,135,84' : '220,53,69' ?>,.12)">
                            <i class="bi <?= $profitPositive ? 'bi-graph-up-arrow' : 'bi-graph-down-arrow' ?> fs-5 <?= $profitPositive ? 'text-success' : 'text-danger' ?>"></i>
                        </div>
                    </div>
                    <div class="fs-3 fw-bold <?= $profitPositive ? 'text-success' : 'text-danger' ?>">
                        <?= ($profitPositive ? '+' : '') . fmtMoney($profit) ?> <small class="fs-6"><?= $currency ?></small>
                    </div>
                    <div class="text-muted small mt-1"><?= __('finance.kpi.net_profit','Net Profit') ?></div>
                    <div class="text-muted smaller mt-1"><?= __('finance.avg_order','Avg. Order') ?>: <?= fmtMoney($summary['avg_order_value']) ?> <?= $currency ?></div>
                </div>
            </div>
        </div>

    </div>

    <!-- ===== ORDER STATS ROW ===== -->
    <div class="row g-3 mb-4">

        <div class="col-md-8">
            <!-- DAILY CHART -->
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-white border-bottom d-flex justify-content-between align-items-center py-3">
                    <h6 class="mb-0 fw-semibold">
                        <i class="bi bi-bar-chart-line me-2 text-primary"></i>
                        <?= __('finance.chart.daily','Daily Revenue') ?>
                    </h6>
                    <div class="d-flex gap-3 small text-muted">
                        <span><span class="badge bg-primary opacity-75 rounded-1 me-1"> </span><?= __('finance.products_revenue','Product Revenue') ?></span>
                        <span><span class="badge bg-info opacity-75 rounded-1 me-1"> </span><?= __('finance.shipping_revenue','Shipping Revenue') ?></span>
                    </div>
                </div>
                <div class="card-body">
                    <canvas id="dailyChart" height="120"></canvas>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <!-- ORDER STATUS BREAKDOWN -->
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-white border-bottom py-3">
                    <h6 class="mb-0 fw-semibold">
                        <i class="bi bi-pie-chart me-2 text-warning"></i>
                        <?= __('finance.orders_breakdown','Orders Breakdown') ?>
                    </h6>
                </div>
                <div class="card-body">
                    <canvas id="statusChart" height="160"></canvas>
                    <div class="mt-3">
                        <?php
                        $total = max(1, $summary['total_orders']);
                        $statItems = [
                            ['label'=>__('orders.confirmed','Confirmed'), 'count'=>$summary['confirmed_count'], 'color'=>'success'],
                            ['label'=>__('orders.rejected','Rejected'),  'count'=>$summary['rejected_count'],  'color'=>'danger'],
                            ['label'=>__('orders.pending','Pending'),    'count'=>$summary['pending_count'],   'color'=>'warning'],
                        ];
                        foreach ($statItems as $si): ?>
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="small">
                                <span class="badge bg-<?= $si['color'] ?> me-1 rounded-1"> </span>
                                <?= $si['label'] ?>
                            </span>
                            <span class="fw-semibold small"><?= $si['count'] ?> <span class="text-muted">(<?= round($si['count']/$total*100,1) ?>%)</span></span>
                        </div>
                        <?php endforeach; ?>
                        <hr class="my-2">
                        <div class="d-flex justify-content-between small fw-bold">
                            <span><?= __('finance.confirm_rate','Confirm Rate') ?></span>
                            <span class="text-<?= $summary['confirm_rate'] >= 50 ? 'success' : 'warning' ?>"><?= $summary['confirm_rate'] ?>%</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>

    <!-- ===== ALGERIA MAP ===== -->
    <div class="row g-3 mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm finance-map-card">
                <div class="card-header bg-white border-bottom py-3 d-flex flex-wrap justify-content-between align-items-center gap-2">
                    <div>
                        <h6 class="mb-1 fw-semibold">
                            <i class="bi bi-map me-2 text-primary"></i>
                            <?= __('finance.algeria_map', 'Algeria Orders Map') ?>
                        </h6>
                        <div class="text-muted small"><?= __('finance.algeria_map_subtitle', 'Click any wilaya to inspect orders and revenue instantly') ?></div>
                    </div>
                    <span class="badge rounded-pill text-bg-light border">
                        <?= count($wilayaLeaders) ?> <?= __('finance.top_wilayas', 'Top Wilayas') ?>
                    </span>
                </div>
                <div class="card-body p-3 p-xl-4">
                    <div class="finance-map-shell">
                        <div class="finance-map-stage">
                            <?php if ($financeMapSvgMarkup !== ''): ?>
                                <?= $financeMapSvgMarkup ?>
                            <?php else: ?>
                                <div class="finance-map-empty py-5"><?= __('finance.no_data', 'No data') ?></div>
                            <?php endif; ?>
                            <div id="financeMapTooltip" class="finance-map-tooltip"></div>
                            <div class="finance-map-legend">
                                <span><?= __('finance.map_legend_low', 'Lower activity') ?></span>
                                <span class="finance-map-legend-gradient"></span>
                                <span><?= __('finance.map_legend_high', 'Higher activity') ?></span>
                            </div>
                        </div>

                        <div class="finance-map-sidebar">
                            <div class="finance-map-hero">
                                <span class="badge rounded-pill"><?= __('finance.selected_wilaya', 'Selected Wilaya') ?></span>
                                <div id="financeSelectedWilayaName" class="finance-map-selected-name"><?= htmlspecialchars($defaultSelectedWilaya['label'] ?? __('finance.tap_wilaya', 'Tap a wilaya to start')) ?></div>
                                <div id="financeSelectedWilayaMeta" class="finance-map-selected-subtitle">
                                    <?= htmlspecialchars($defaultSelectedWilaya['name'] ?? __('finance.tap_wilaya', 'Tap a wilaya to start')) ?>
                                </div>
                            </div>

                            <div class="finance-map-metric-grid">
                                <div class="finance-map-metric">
                                    <div class="finance-map-metric-label"><?= __('finance.orders_count', 'Orders Count') ?></div>
                                    <div id="financeSelectedOrders" class="finance-map-metric-value"><?= (int)($defaultSelectedWilaya['orders_count'] ?? 0) ?></div>
                                </div>
                                <div class="finance-map-metric">
                                    <div class="finance-map-metric-label"><?= __('finance.order_share', 'Order Share') ?></div>
                                    <div id="financeSelectedShare" class="finance-map-metric-value">0%</div>
                                </div>
                                <div class="finance-map-metric">
                                    <div class="finance-map-metric-label"><?= __('finance.revenue', 'Revenue') ?></div>
                                    <div id="financeSelectedRevenue" class="finance-map-metric-value"><?= fmtMoney((float)($defaultSelectedWilaya['revenue'] ?? 0)) ?></div>
                                </div>
                                <div class="finance-map-metric">
                                    <div class="finance-map-metric-label"><?= __('finance.wilaya', 'Wilaya') ?></div>
                                    <div id="financeSelectedCode" class="finance-map-metric-value"><?= htmlspecialchars($defaultSelectedWilaya['code'] ?? '--') ?></div>
                                </div>
                            </div>

                            <div class="finance-map-toplist">
                                <div class="finance-map-toplist-header">
                                    <div class="fw-semibold"><?= __('finance.top_wilayas', 'Top Wilayas') ?></div>
                                    <div class="small text-muted"><?= __('finance.orders', 'Orders') ?></div>
                                </div>
                                <div id="financeTopWilayas" class="finance-map-toplist-body">
                                    <?php if (empty($wilayaLeaders)): ?>
                                        <div class="finance-map-empty"><?= __('finance.no_orders_yet', 'No orders yet') ?></div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ===== TABLES ROW ===== -->
    <div class="row g-3 mb-4">

        <!-- BY PRODUCT -->
        <div class="col-lg-6">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-white border-bottom py-3">
                    <h6 class="mb-0 fw-semibold">
                        <i class="bi bi-box-seam me-2 text-primary"></i>
                        <?= __('finance.by_product','Performance by Product') ?>
                    </h6>
                </div>
                <div class="card-body p-0">
                    <table class="table table-hover table-sm align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th class="ps-3"><?= __('finance.product','Product') ?></th>
                                <th class="text-center"><?= __('finance.orders','Orders') ?></th>
                                <th class="text-end pe-3"><?= __('finance.revenue','Revenue') ?></th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if (empty($byProduct)): ?>
                            <tr><td colspan="3" class="text-center text-muted py-3"><?= __('finance.no_data','No data') ?></td></tr>
                        <?php else: ?>
                            <?php
                            $maxRev = max(array_column($byProduct,'revenue') ?: [1]);
                            foreach ($byProduct as $row):
                                $pct = $maxRev > 0 ? round(($row['revenue']/$maxRev)*100) : 0;
                            ?>
                            <tr>
                                <td class="ps-3">
                                    <div class="small fw-semibold"><?= htmlspecialchars($row['title'] ?? 'منتج محذوف') ?></div>
                                    <div class="progress mt-1" style="height:3px">
                                        <div class="progress-bar bg-primary" style="width:<?= $pct ?>%"></div>
                                    </div>
                                </td>
                                <td class="text-center small"><?= (int)$row['orders_count'] ?></td>
                                <td class="text-end pe-3 small fw-semibold"><?= fmtMoney($row['revenue']) ?> <?= $currency ?></td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- BY WILAYA -->
        <div class="col-lg-6">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-white border-bottom py-3">
                    <h6 class="mb-0 fw-semibold">
                        <i class="bi bi-geo-alt me-2 text-info"></i>
                        <?= __('finance.by_wilaya','Performance by Wilaya') ?>
                    </h6>
                </div>
                <div class="card-body p-0">
                    <table class="table table-hover table-sm align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th class="ps-3"><?= __('finance.wilaya','Wilaya') ?></th>
                                <th class="text-center"><?= __('finance.orders','طلبات') ?></th>
                                <th class="text-end pe-3"><?= __('finance.revenue','مداخيل') ?></th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if (empty($byWilaya)): ?>
                            <tr><td colspan="3" class="text-center text-muted py-3"><?= __('finance.no_data','No data') ?></td></tr>
                        <?php else: ?>
                            <?php
                            $maxW = max(array_column($byWilaya,'orders_count') ?: [1]);
                            foreach ($byWilaya as $row):
                                $wilayaCode = financeWilayaCode($row['wilaya_code'] ?? '');
                                $pct = $maxW > 0 ? round(($row['orders_count']/$maxW)*100) : 0;
                            ?>
                            <tr class="finance-wilaya-row" data-wilaya-code="<?= htmlspecialchars($wilayaCode) ?>">
                                <td class="ps-3">
                                    <div class="small fw-semibold">
                                        <?= htmlspecialchars($row['city_name'] ?: (__('finance.wilaya_prefix','Wilaya ').$row['wilaya_code'])) ?>
                                    </div>
                                    <div class="progress mt-1" style="height:3px">
                                        <div class="progress-bar bg-info" style="width:<?= $pct ?>%"></div>
                                    </div>
                                </td>
                                <td class="text-center small"><?= (int)$row['orders_count'] ?></td>
                                <td class="text-end pe-3 small fw-semibold"><?= fmtMoney($row['revenue']) ?> <?= $currency ?></td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    </div>

    <!-- ===== SHIPPERS + TOP ORDERS ===== -->
    <div class="row g-3">

        <!-- BY SHIPPER -->
        <div class="col-lg-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-white border-bottom py-3">
                    <h6 class="mb-0 fw-semibold">
                        <i class="bi bi-truck me-2 text-danger"></i>
                        <?= __('finance.by_shipper','By Shipping Company') ?>
                    </h6>
                </div>
                <div class="card-body">
                    <?php if (empty($byShipper)): ?>
                        <p class="text-muted text-center py-3"><?= __('finance.no_data','No data') ?></p>
                    <?php else: ?>
                        <?php
                        $shipperColors = ['ecotrack'=>'primary','zr_express'=>'warning','yalidine'=>'success','maystro'=>'info','dhd'=>'secondary'];
                        $totalShip = max(1, array_sum(array_column($byShipper,'orders_count')));
                        foreach ($byShipper as $sh):
                            $prov  = strtolower($sh['provider'] ?? 'unknown');
                            $color = $shipperColors[$prov] ?? 'secondary';
                            $pct   = round($sh['orders_count']/$totalShip*100);
                        ?>
                        <div class="mb-3">
                            <div class="d-flex justify-content-between mb-1">
                                <span class="badge bg-<?= $color ?> px-2"><?= strtoupper($prov) ?></span>
                                <span class="small fw-semibold"><?= (int)$sh['orders_count'] ?> <?= __('finance.orders_unit','orders') ?> (<?= $pct ?>%)</span>
                            </div>
                            <div class="progress" style="height:8px">
                                <div class="progress-bar bg-<?= $color ?>" style="width:<?= $pct ?>%"></div>
                            </div>
                            <div class="text-muted smaller mt-1">
                                <?= __('finance.shipping_revenue','Shipping Revenue') ?>: <?= fmtMoney($sh['shipping_revenue']) ?> <?= $currency ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- TOP ORDERS -->
        <div class="col-lg-8">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-white border-bottom py-3">
                    <h6 class="mb-0 fw-semibold">
                        <i class="bi bi-star me-2 text-warning"></i>
                        <?= __('finance.top_orders','Top Orders by Value') ?>
                    </h6>
                </div>
                <div class="card-body p-0">
                    <table class="table table-hover table-sm align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th class="ps-3">#</th>
                                <th><?= __('finance.customer','Customer') ?></th>
                                <th class="text-center"><?= __('finance.shipper','Shipper') ?></th>
                                <th class="text-end"><?= __('finance.product_total','المنتج') ?></th>
                                <th class="text-end pe-3"><?= __('finance.order_total','Total') ?></th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if (empty($topOrders)): ?>
                            <tr><td colspan="5" class="text-center text-muted py-3"><?= __('finance.no_data','No data') ?></td></tr>
                        <?php else: ?>
                            <?php foreach ($topOrders as $ord): ?>
                            <tr>
                                <td class="ps-3">
                                    <a href="/admin/orders/view/<?= (int)$ord['id'] ?>" class="fw-bold text-decoration-none">
                                        #<?= (int)$ord['id'] ?>
                                    </a>
                                </td>
                                <td>
                                    <div class="small fw-semibold"><?= htmlspecialchars($ord['full_name']) ?></div>
                                    <div class="text-muted smaller"><?= date('d/m/Y', strtotime($ord['created_at'])) ?></div>
                                </td>
                                <td class="text-center">
                                    <?php $prov = strtolower($ord['provider'] ?? ''); ?>
                                    <?php if ($prov): ?>
                                        <span class="badge bg-<?= $shipperColors[$prov] ?? 'secondary' ?> px-2 small">
                                            <?= strtoupper($prov) ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-end small"><?= fmtMoney($ord['product_total']) ?> <?= $currency ?></td>
                                <td class="text-end pe-3 fw-bold"><?= fmtMoney($ord['total']) ?> <?= $currency ?></td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

    </div>

</div>
</section>
</div>

<?php
// إعداد بيانات الرسوم البيانية
$chartLabels   = array_column($dailyChart, 'day');
$chartRevenue  = array_map(fn($r) => (float)$r['revenue'], $dailyChart);
$chartShipping = array_map(fn($r) => (float)$r['shipping_revenue'], $dailyChart);
$chartOrders   = array_map(fn($r) => (int)$r['orders_count'], $dailyChart);
$wilayaMapJson = json_encode(array_values($wilayaMapData), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$defaultSelectedCode = (string)($defaultSelectedWilaya['code'] ?? '');
?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
// Daily Chart
new Chart(document.getElementById('dailyChart'), {
    type: 'bar',
    data: {
        labels: <?= json_encode($chartLabels) ?>,
        datasets: [
            {
                label: '<?= __('finance.products_revenue','Product Revenue') ?>',
                data: <?= json_encode($chartRevenue) ?>,
                backgroundColor: 'rgba(13,110,253,0.7)',
                borderRadius: 4,
                order: 1
            },
            {
                label: '<?= __('finance.shipping_revenue','Shipping Revenue') ?>',
                data: <?= json_encode($chartShipping) ?>,
                backgroundColor: 'rgba(13,202,240,0.6)',
                borderRadius: 4,
                order: 2
            },
            {
                label: '<?= __('finance.orders_count','Orders Count') ?>',
                data: <?= json_encode($chartOrders) ?>,
                type: 'line',
                borderColor: '#198754',
                backgroundColor: 'rgba(25,135,84,0.1)',
                fill: true,
                tension: 0.3,
                pointRadius: 3,
                yAxisID: 'y2',
                order: 0
            }
        ]
    },
    options: {
        responsive: true,
        interaction: { mode: 'index', intersect: false },
        plugins: { legend: { display: false } },
        scales: {
            x: { grid: { display: false }, ticks: { maxRotation: 45 } },
            y: {
                position: 'right',
                ticks: { callback: v => v.toLocaleString() + ' <?= __('finance.currency','DZD') ?>' },
                grid: { color: 'rgba(0,0,0,.05)' }
            },
            y2: {
                position: 'left',
                grid: { display: false },
                ticks: { callback: v => v + ' <?= __('finance.orders_unit','orders') ?>' }
            }
        }
    }
});

// Status Doughnut
new Chart(document.getElementById('statusChart'), {
    type: 'doughnut',
    data: {
        labels: ['<?= __('orders.confirmed','Confirmed') ?>', '<?= __('orders.rejected','Rejected') ?>', '<?= __('orders.pending','Pending') ?>'],
        datasets: [{
            data: [<?= $summary['confirmed_count'] ?>, <?= $summary['rejected_count'] ?>, <?= $summary['pending_count'] ?>],
            backgroundColor: ['#198754','#dc3545','#ffc107'],
            borderWidth: 2,
            borderColor: '#fff'
        }]
    },
    options: {
        cutout: '70%',
        plugins: { legend: { display: false } }
    }
});

const financeWilayaData = <?= $wilayaMapJson ?: '[]' ?>;
const financeDefaultWilayaCode = <?= json_encode($defaultSelectedCode, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const financeOrdersTotal = <?= (int)array_sum(array_map(static fn(array $item): int => (int)$item['orders_count'], $wilayaMapData)) ?>;
const financeCurrencyLabel = <?= json_encode(__('finance.currency', 'DZD'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const financeMapStrings = {
    orders: <?= json_encode(__('finance.orders', 'Orders'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
    revenue: <?= json_encode(__('finance.revenue', 'Revenue'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
    noOrders: <?= json_encode(__('finance.no_orders_yet', 'No orders yet'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
    orderShare: <?= json_encode(__('finance.order_share', 'Order Share'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
    tapWilaya: <?= json_encode(__('finance.tap_wilaya', 'Tap a wilaya to start'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>,
};

const financeMapRoot = document.getElementById('algeriaFinanceMap');
const financeTooltip = document.getElementById('financeMapTooltip');
const financeSelectedName = document.getElementById('financeSelectedWilayaName');
const financeSelectedMeta = document.getElementById('financeSelectedWilayaMeta');
const financeSelectedOrders = document.getElementById('financeSelectedOrders');
const financeSelectedShare = document.getElementById('financeSelectedShare');
const financeSelectedRevenue = document.getElementById('financeSelectedRevenue');
const financeSelectedCode = document.getElementById('financeSelectedCode');
const financeTopWilayas = document.getElementById('financeTopWilayas');
const financeWilayaRows = Array.from(document.querySelectorAll('.finance-wilaya-row'));
const financeWilayaRowMap = new Map(financeWilayaRows.map((row) => [row.dataset.wilayaCode, row]));
const financeMaxOrders = Math.max(1, ...financeWilayaData.map((item) => Number(item.orders_count || 0)));
const financeWilayaDataMap = new Map(financeWilayaData.map((item) => [item.code, item]));
const financeMapRegions = Array.from(document.querySelectorAll('.finance-map-region'));
let financeSelectedCodeValue = financeDefaultWilayaCode;

function financeInterpolateColor(value) {
    const ratio = Math.max(0, Math.min(1, value / financeMaxOrders));
    const start = { r: 219, g: 234, b: 254 };
    const end = { r: 37, g: 99, b: 235 };
    const r = Math.round(start.r + (end.r - start.r) * ratio);
    const g = Math.round(start.g + (end.g - start.g) * ratio);
    const b = Math.round(start.b + (end.b - start.b) * ratio);
    return `rgb(${r}, ${g}, ${b})`;
}

function financeMarkerRadius(value) {
    if (value <= 0) {
        return 8;
    }
    const ratio = Math.max(0, Math.min(1, value / financeMaxOrders));
    return 10 + Math.round(ratio * 12);
}

function financeMoney(value) {
    return Number(value || 0).toLocaleString() + ' ' + financeCurrencyLabel;
}

function financeShare(value) {
    if (!financeOrdersTotal) {
        return '0%';
    }
    return ((Number(value || 0) / financeOrdersTotal) * 100).toFixed(1) + '%';
}

function financeTooltipHtml(item) {
    return `
        <div class="finance-map-tooltip-title">${item.label}</div>
        <div class="finance-map-tooltip-meta">${item.name || item.label}</div>
        <div class="mt-2 small">${financeMapStrings.orders}: <strong>${Number(item.orders_count || 0).toLocaleString()}</strong></div>
        <div class="small">${financeMapStrings.revenue}: <strong>${financeMoney(item.revenue || 0)}</strong></div>
    `;
}

function financeShowTooltip(event, item) {
    if (!financeTooltip || !financeMapRoot) {
        return;
    }
    const bounds = financeMapRoot.getBoundingClientRect();
    const pointX = event.clientX - bounds.left;
    const pointY = event.clientY - bounds.top;
    financeTooltip.innerHTML = financeTooltipHtml(item);
    financeTooltip.style.left = `${Math.min(Math.max(pointX + 16, 12), bounds.width - 220)}px`;
    financeTooltip.style.top = `${Math.min(Math.max(pointY - 14, 12), bounds.height - 120)}px`;
    financeTooltip.classList.add('is-visible');
}

function financeHideTooltip() {
    financeTooltip?.classList.remove('is-visible');
}

function financeHighlightRow(code) {
    financeWilayaRows.forEach((row) => row.classList.toggle('is-selected', row.dataset.wilayaCode === code));
}

function financePaintMap(selectedCode = '') {
    if (!financeMapRoot) {
        return;
    }

    const hasSelection = selectedCode !== '';
    financeMapRoot.classList.toggle('is-dimmed', hasSelection);

    financeMapRegions.forEach((region) => {
        const code = region.dataset.wilayaCode || '';
        const item = financeWilayaDataMap.get(code);
        const orders = Number(item?.orders_count || 0);
        region.style.fill = orders > 0 ? financeInterpolateColor(orders) : '#edf4ff';
        region.classList.toggle('is-selected', code === selectedCode);
        region.style.opacity = hasSelection && code !== selectedCode ? '0.38' : '1';
    });
}

function financeRenderTopWilayas(selectedCode) {
    if (!financeTopWilayas) {
        return;
    }

    const topItems = financeWilayaData
        .filter((item) => Number(item.orders_count || 0) > 0)
        .sort((a, b) => Number(b.orders_count || 0) - Number(a.orders_count || 0))
        .slice(0, 6);

    if (!topItems.length) {
        financeTopWilayas.innerHTML = `<div class="finance-map-empty">${financeMapStrings.noOrders}</div>`;
        return;
    }

    financeTopWilayas.innerHTML = topItems.map((item, index) => `
        <button type="button" class="finance-map-top-item ${item.code === selectedCode ? 'is-selected' : ''}" data-wilaya-code="${item.code}">
            <div class="d-flex align-items-center gap-3">
                <span class="finance-map-top-item-rank">${index + 1}</span>
                <div>
                    <div class="finance-map-top-item-name">${item.label}</div>
                    <div class="finance-map-top-item-meta">${item.name || item.label}</div>
                </div>
            </div>
            <div class="text-end">
                <div class="fw-bold">${Number(item.orders_count || 0).toLocaleString()}</div>
                <div class="finance-map-top-item-meta">${financeShare(item.orders_count || 0)}</div>
            </div>
        </button>
    `).join('');

    financeTopWilayas.querySelectorAll('[data-wilaya-code]').forEach((button) => {
        button.addEventListener('click', () => financeSelectWilaya(button.dataset.wilayaCode));
    });
}

function financeSelectWilaya(code) {
    const item = financeWilayaDataMap.get(code);
    if (!item) {
        return;
    }

    financeSelectedCodeValue = code;
    financeSelectedName.textContent = item.label || financeMapStrings.tapWilaya;
    financeSelectedMeta.textContent = item.name || item.label || '';
    financeSelectedOrders.textContent = Number(item.orders_count || 0).toLocaleString();
    financeSelectedShare.textContent = financeShare(item.orders_count || 0);
    financeSelectedRevenue.textContent = financeMoney(item.revenue || 0);
    financeSelectedCode.textContent = item.code || '--';

    financeHighlightRow(code);
    financeRenderTopWilayas(code);
    financePaintMap(code);
}

function financeBindMap() {
    if (!financeMapRoot || !financeMapRegions.length) {
        return;
    }

    financeMapRegions.forEach((region) => {
        const code = region.dataset.wilayaCode || '';
        const item = financeWilayaDataMap.get(code);
        if (!item) {
            return;
        }

        region.addEventListener('mouseenter', (event) => financeShowTooltip(event, item));
        region.addEventListener('mousemove', (event) => financeShowTooltip(event, item));
        region.addEventListener('mouseleave', financeHideTooltip);
        region.addEventListener('click', () => financeSelectWilaya(code));
    });

    financePaintMap(financeSelectedCodeValue);

    if (financeSelectedCodeValue) {
        financeSelectWilaya(financeSelectedCodeValue);
    } else {
        financeRenderTopWilayas('');
    }
}

financeWilayaRows.forEach((row) => {
    row.style.cursor = 'pointer';
    row.addEventListener('click', () => {
        if (row.dataset.wilayaCode) {
            financeSelectWilaya(row.dataset.wilayaCode);
        }
    });
    row.addEventListener('mouseenter', () => {
        if (financeMapRoot && row.dataset.wilayaCode) {
            financePaintMap(row.dataset.wilayaCode);
        }
    });
    row.addEventListener('mouseleave', () => {
        if (financeSelectedCodeValue) {
            financePaintMap(financeSelectedCodeValue);
        }
    });
});

if (financeMapRoot) {
    financeMapRoot.addEventListener('mouseleave', () => {
        if (financeSelectedCodeValue) {
            financePaintMap(financeSelectedCodeValue);
        }
        financeHideTooltip();
    });
}

if (financeSelectedRevenue && financeDefaultWilayaCode) {
    const initialItem = financeWilayaDataMap.get(financeDefaultWilayaCode);
    if (initialItem) {
        financeSelectedRevenue.textContent = financeMoney(initialItem.revenue || 0);
    }
}

financeBindMap();
</script>

<?php
function request_has_custom_range(): bool {
    return !empty($_GET['start']) && !empty($_GET['end']);
}
?>
