<?php
/**
 * Reusable time period filter bar.
 *
 * @var string $period     Current selected period (day|week|month|year|3year|5year|custom)
 * @var string $from       Custom start date (Y-m-d)
 * @var string $to         Custom end date (Y-m-d)
 * @var string $baseUrl    Base URL for navigation links
 * @var bool   $export     If true, hide the export button
 */
$currentPeriod = $period ?? 'month';
$currentFrom = $from ?? '';
$currentTo = $to ?? '';
$baseUrl = $baseUrl ?? '';
$export = $export ?? false;
?>
<div class="card" style="padding:12px 20px;margin-bottom:20px;display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
    <?php
    $periods = [
        'day'    => 'اليوم',
        'week'   => 'الأسبوع',
        'month'  => 'الشهر',
        'year'   => 'السنة',
        '3year'  => '3 سنوات',
        '5year'  => '5 سنوات',
        'custom' => 'مخصص',
    ];
    foreach ($periods as $key => $label): ?>
    <a href="<?= e($baseUrl) ?>?period=<?= $key ?><?= $key === 'custom' && $currentFrom ? '&from=' . e($currentFrom) . '&to=' . e($currentTo) : '' ?>"
       class="btn <?= $currentPeriod === $key ? 'btn-primary' : 'btn-outline' ?>"
       style="padding:6px 14px;font-size:13px;"
       <?= $key === 'custom' ? 'id="custom-period-btn"' : '' ?>>
        <?= $label ?>
    </a>
    <?php endforeach; ?>

    <div id="custom-range" style="display:<?= $currentPeriod === 'custom' ? 'flex' : 'none' ?>;gap:8px;align-items:center;margin-right:10px;">
        <input type="date" id="filter-from" value="<?= e($currentFrom) ?>" class="form-input" style="width:150px;padding:5px;">
        <span>—</span>
        <input type="date" id="filter-to" value="<?= e($currentTo) ?>" class="form-input" style="width:150px;padding:5px;">
        <button onclick="applyCustomRange()" class="btn btn-primary" style="padding:5px 12px;font-size:12px;">تطبيق</button>
    </div>

    <?php if (!$export): ?>
    <a href="<?= e($baseUrl) ?>/export?level=club&period=<?= e($currentPeriod) ?>&from=<?= e($currentFrom) ?>&to=<?= e($currentTo) ?>" class="btn btn-outline" style="margin-right:auto;padding:6px 14px;font-size:13px;">
        <i data-lucide="download" style="width:14px;height:14px;display:inline;vertical-align:middle;"></i>
        تصدير PDF
    </a>
    <?php endif; ?>
</div>
<script>
function applyCustomRange() {
    var from = document.getElementById('filter-from').value;
    var to = document.getElementById('filter-to').value;
    if (!from || !to) { alert('يرجى تحديد تاريخ البداية والنهاية'); return; }
    window.location.href = '<?= e($baseUrl) ?>?period=custom&from=' + from + '&to=' + to;
}
(function() {
    var btn = document.getElementById('custom-period-btn');
    if (btn) {
        btn.addEventListener('click', function(e) {
            if ('<?= $currentPeriod ?>' !== 'custom') {
                e.preventDefault();
                document.getElementById('custom-range').style.display = 'flex';
            }
        });
    }
})();
</script>
