<?php
declare(strict_types=1);
$__template->layout('Layout.main');
$__template->section('title', 'التقارير المالية — الأنشطة الرياضية');
$__template->section('content');

$summary = $report['summary'] ?? [];
$revenueBreakdown = $report['revenue_breakdown'] ?? [];
$costBreakdown = $report['cost_breakdown'] ?? [];
$trend = $report['monthly_trend'] ?? [];
$dateFrom = $report['date_from'] ?? '';
$dateTo = $report['date_to'] ?? '';
$presets = [
    'daily'   => 'يومي',
    'weekly'  => 'أسبوعي',
    'monthly' => 'شهري',
    'yearly'  => 'سنوي (سنة مالية)',
    '3yr'     => '3 سنوات',
    '5yr'     => '5 سنوات',
    'custom'  => 'فترة مخصصة',
];
$currentPreset = $filters['period_preset'] ?? 'monthly';
?>

<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:20px;">
    <h1 style="font-size:22px;font-weight:700;color:#0D7377;">التقارير المالية — الأنشطة الرياضية</h1>
    <a href="/sa" class="btn btn-outline btn-sm">العودة للوحة التحكم</a>
</div>

<!-- Filter Card -->
<div class="card" style="margin-bottom:20px;padding:20px;border-right:4px solid #7C3AED;">
    <form method="GET" action="/sa/reports/finance" id="financeFilterForm">
        <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:12px;margin-bottom:12px;">
            <div class="form-group">
                <label class="form-label">اللعبة</label>
                <select name="discipline_id" class="form-select">
                    <option value="">كل الأنشطة</option>
                    <?php foreach ($disciplines as $d): ?>
                    <option value="<?= (int) $d['id'] ?>" <?= ($filters['discipline_id'] ?? '') == $d['id'] ? 'selected' : '' ?>><?= e($d['name_ar']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label class="form-label">الفرع</label>
                <select name="branch_id" class="form-select">
                    <option value="">كل الفروع</option>
                    <?php foreach ($branches as $b): ?>
                    <option value="<?= (int) $b['id'] ?>" <?= ($filters['branch_id'] ?? '') == $b['id'] ? 'selected' : '' ?>><?= e($b['name_ar']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group" id="customDateFrom" style="display:<?= $currentPreset === 'custom' ? 'block' : 'none' ?>;">
                <label class="form-label">من تاريخ</label>
                <input type="date" name="date_from" class="form-input" value="<?= e($filters['date_from'] ?? '') ?>">
            </div>
            <div class="form-group" id="customDateTo" style="display:<?= $currentPreset === 'custom' ? 'block' : 'none' ?>;">
                <label class="form-label">إلى تاريخ</label>
                <input type="date" name="date_to" class="form-input" value="<?= e($filters['date_to'] ?? '') ?>">
            </div>
        </div>

        <!-- Period Presets -->
        <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:12px;">
            <span style="font-size:12px;color:#6B7280;font-weight:600;">الفترة:</span>
            <?php foreach ($presets as $key => $label): ?>
            <label style="display:inline-flex;align-items:center;gap:4px;padding:6px 12px;border-radius:6px;cursor:pointer;font-size:12px;border:1px solid <?= $currentPreset === $key ? '#7C3AED' : '#E5E7EB' ?>;background:<?= $currentPreset === $key ? '#F5F3FF' : '#fff' ?>;color:<?= $currentPreset === $key ? '#7C3AED' : '#374151' ?>;">
                <input type="radio" name="period_preset" value="<?= $key ?>" <?= $currentPreset === $key ? 'checked' : '' ?> onchange="toggleCustomDates(this.value);document.getElementById('financeFilterForm').submit();" style="display:none;">
                <?= e($label) ?>
            </label>
            <?php endforeach; ?>
        </div>

        <div style="display:flex;align-items:center;gap:8px;">
            <button type="submit" class="btn btn-primary btn-sm">
                <i data-lucide="bar-chart-3" style="width:14px;height:14px;display:inline-block;vertical-align:middle;margin-left:4px;"></i> عرض التقرير
            </button>
            <span style="font-size:11px;color:#9CA3AF;">الفترة: <?= e($dateFrom) ?> — <?= e($dateTo) ?></span>
        </div>
    </form>
</div>

<!-- Summary Cards -->
<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;margin-bottom:20px;">
    <div class="card" style="padding:20px;text-align:center;border-top:3px solid #059669;">
        <div style="font-size:11px;color:#6B7280;margin-bottom:4px;">إجمالي الإيرادات</div>
        <div style="font-size:28px;font-weight:700;color:#059669;direction:ltr;"><?= number_format((float) ($summary['total_revenue'] ?? 0), 2) ?></div>
        <div style="font-size:10px;color:#9CA3AF;">ج.م</div>
    </div>
    <div class="card" style="padding:20px;text-align:center;border-top:3px solid #DC2626;">
        <div style="font-size:11px;color:#6B7280;margin-bottom:4px;">إجمالي التكاليف</div>
        <div style="font-size:28px;font-weight:700;color:#DC2626;direction:ltr;"><?= number_format((float) ($summary['total_costs'] ?? 0), 2) ?></div>
        <div style="font-size:10px;color:#9CA3AF;">ج.م</div>
    </div>
    <div class="card" style="padding:20px;text-align:center;border-top:3px solid <?= bccomp($summary['net_profit'] ?? '0', '0', 2) >= 0 ? '#2563EB' : '#DC2626' ?>;">
        <div style="font-size:11px;color:#6B7280;margin-bottom:4px;">صافي الربح</div>
        <div style="font-size:28px;font-weight:700;color:<?= bccomp($summary['net_profit'] ?? '0', '0', 2) >= 0 ? '#2563EB' : '#DC2626' ?>;direction:ltr;"><?= number_format((float) ($summary['net_profit'] ?? 0), 2) ?></div>
        <div style="font-size:10px;color:#9CA3AF;">ج.م</div>
    </div>
</div>

<!-- Export Buttons -->
<div style="display:flex;gap:8px;margin-bottom:20px;">
    <?php $exportParams = http_build_query(array_filter($filters, fn($v) => $v !== '' && $v !== null)); ?>
    <a href="/sa/reports/finance/export-csv?<?= $exportParams ?>" class="btn btn-sm btn-outline" style="color:#059669;border-color:#059669;">
        <i data-lucide="file-spreadsheet" style="width:14px;height:14px;display:inline-block;vertical-align:middle;margin-left:4px;"></i> تصدير CSV
    </a>
    <a href="/sa/reports/finance/export-pdf?<?= $exportParams ?>" class="btn btn-sm btn-outline" style="color:#DC2626;border-color:#DC2626;">
        <i data-lucide="file-text" style="width:14px;height:14px;display:inline-block;vertical-align:middle;margin-left:4px;"></i> تصدير PDF
    </a>
</div>

<!-- Revenue Breakdown -->
<div class="card" style="margin-bottom:20px;padding:20px;">
    <h2 style="font-size:15px;font-weight:600;color:#059669;margin:0 0 12px;">تفصيل الإيرادات</h2>
    <table style="width:100%;border-collapse:collapse;font-size:13px;">
        <thead>
            <tr style="border-bottom:2px solid #E5E7EB;">
                <th style="padding:8px 10px;text-align:right;color:#6B7280;">البند</th>
                <th style="padding:8px 10px;text-align:left;color:#6B7280;width:160px;">المبلغ (ج.م)</th>
                <th style="padding:8px 10px;text-align:center;color:#6B7280;width:100px;">العدد</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($revenueBreakdown as $item): ?>
            <tr style="border-bottom:1px solid #F3F4F6;">
                <td style="padding:8px 10px;"><?= e($item['label']) ?></td>
                <td style="padding:8px 10px;text-align:left;font-weight:600;color:#059669;direction:ltr;"><?= number_format((float) $item['amount'], 2) ?></td>
                <td style="padding:8px 10px;text-align:center;color:#6B7280;"><?= (int) ($item['count'] ?? 0) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Cost Breakdown -->
<div class="card" style="margin-bottom:20px;padding:20px;">
    <h2 style="font-size:15px;font-weight:600;color:#DC2626;margin:0 0 12px;">التكاليف</h2>
    <?php if (empty($costBreakdown) || bccomp($summary['total_costs'] ?? '0', '0', 2) === 0): ?>
    <p style="color:#9CA3AF;font-size:13px;">لا توجد تكاليف مسجلة في هذه الفترة.</p>
    <?php else: ?>
    <table style="width:100%;border-collapse:collapse;font-size:13px;">
        <thead>
            <tr style="border-bottom:2px solid #E5E7EB;">
                <th style="padding:8px 10px;text-align:right;color:#6B7280;">البند</th>
                <th style="padding:8px 10px;text-align:left;color:#6B7280;width:160px;">المبلغ (ج.م)</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($costBreakdown as $item): ?>
            <tr style="border-bottom:1px solid #F3F4F6;">
                <td style="padding:8px 10px;"><?= e($item['label']) ?></td>
                <td style="padding:8px 10px;text-align:left;font-weight:600;color:#DC2626;direction:ltr;"><?= number_format((float) $item['amount'], 2) ?></td>
            </tr>
            <?php if (!empty($item['detail'])): ?>
            <tr>
                <td colspan="2" style="padding:4px 10px 12px;">
                    <div style="font-size:11px;color:#6B7280;display:flex;flex-wrap:wrap;gap:6px;">
                        <?php foreach ($item['detail'] as $d): ?>
                        <span style="background:#FEF2F2;padding:2px 8px;border-radius:4px;">
                            <?= e($d['name']) ?> (<?= e($d['model']) ?>): <?= number_format((float) $d['amount'], 2) ?> ج.م
                        </span>
                        <?php endforeach; ?>
                    </div>
                </td>
            </tr>
            <?php endif; ?>
            <?php endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>
</div>

<!-- Monthly Trend -->
<?php if (!empty($trend)): ?>
<div class="card" style="padding:20px;">
    <h2 style="font-size:15px;font-weight:600;color:#374151;margin:0 0 12px;">الاتجاه الشهري</h2>
    <?php
    $maxRevenue = max(array_map(fn($t) => (float) $t['revenue'], $trend));
    $maxRevenue = $maxRevenue > 0 ? $maxRevenue : 1;
    ?>
    <div style="display:flex;align-items:end;gap:8px;height:200px;padding:10px 0;">
        <?php foreach ($trend as $t): ?>
        <?php $pct = ((float) $t['revenue'] / $maxRevenue) * 100; ?>
        <div style="flex:1;text-align:center;display:flex;flex-direction:column;justify-content:end;height:100%;">
            <div style="font-size:10px;color:#374151;font-weight:600;margin-bottom:4px;direction:ltr;"><?= number_format((float) $t['revenue'], 0) ?></div>
            <div style="background:linear-gradient(to top,#0D7377,#10B981);border-radius:4px 4px 0 0;min-height:4px;height:<?= round($pct) ?>%;transition:height 0.3s;"></div>
            <div style="font-size:9px;color:#9CA3AF;margin-top:4px;direction:ltr;"><?= e($t['month']) ?></div>
        </div>
        <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<script>
function toggleCustomDates(preset) {
    document.getElementById('customDateFrom').style.display = preset === 'custom' ? 'block' : 'none';
    document.getElementById('customDateTo').style.display = preset === 'custom' ? 'block' : 'none';
    if (preset !== 'custom') {
        document.querySelector('input[name="date_from"]').value = '';
        document.querySelector('input[name="date_to"]').value = '';
    }
}

document.addEventListener('DOMContentLoaded', function() {
    if (typeof lucide !== 'undefined') lucide.createIcons();
});
</script>

<?php $__template->endSection(); ?>
