<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>الاشتراكات الشهرية<?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<?php if (can('sa.subscription.generate')): ?>
<form method="POST" action="/sa/subscriptions/generate" style="display:inline-flex;gap:8px;align-items:center;">
    <?= csrf_field() ?>
    <input type="month" name="year_month" value="<?= e($filters['month'] ?? date('Y-m')) ?>" class="form-input" style="width:160px;">
    <button type="submit" class="btn btn-primary" onclick="return confirm('هل تريد توليد الاشتراكات لهذا الشهر؟');">
        <i data-lucide="refresh-cw" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> توليد الاشتراكات
    </button>
</form>
<button type="button" id="previewBtn" class="btn btn-outline" style="margin-right:8px;">
    <i data-lucide="eye" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> معاينة الشهر القادم
</button>
<?php endif; ?>
<?php $__template->endSection(); ?>

<?php $__template->section('content'); ?>

<!-- Monthly Stats Summary -->
<?php if (!empty($stats) && (int) ($stats['total'] ?? 0) > 0): ?>
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:12px;margin-bottom:20px;">
    <div class="card" style="padding:16px;text-align:center;">
        <div style="font-size:24px;font-weight:700;color:#1A1A2E;"><?= (int) $stats['total'] ?></div>
        <div style="font-size:12px;color:#6B7280;margin-top:4px;">إجمالي الاشتراكات</div>
        <div style="font-size:11px;color:#9CA3AF;margin-top:2px;"><?= e($statsMonth ?? '') ?></div>
    </div>
    <div class="card" style="padding:16px;text-align:center;border-right:3px solid #059669;">
        <div style="font-size:24px;font-weight:700;color:#059669;"><?= (int) ($stats['paid'] ?? 0) ?></div>
        <div style="font-size:12px;color:#6B7280;margin-top:4px;">مدفوع</div>
        <div style="font-size:11px;color:#059669;margin-top:2px;"><?= money((float) ($stats['collected'] ?? 0)) ?></div>
    </div>
    <div class="card" style="padding:16px;text-align:center;border-right:3px solid #F59E0B;">
        <div style="font-size:24px;font-weight:700;color:#F59E0B;"><?= (int) ($stats['unpaid'] ?? 0) ?></div>
        <div style="font-size:12px;color:#6B7280;margin-top:4px;">لم يدفع</div>
        <div style="font-size:11px;color:#F59E0B;margin-top:2px;"><?= money((float) ($stats['pending_amount'] ?? 0)) ?></div>
    </div>
    <div class="card" style="padding:16px;text-align:center;border-right:3px solid #DC2626;">
        <div style="font-size:24px;font-weight:700;color:#DC2626;"><?= (int) ($stats['overdue'] ?? 0) ?></div>
        <div style="font-size:12px;color:#6B7280;margin-top:4px;">متأخر</div>
    </div>
    <?php if ((int) ($stats['exempt'] ?? 0) > 0): ?>
    <div class="card" style="padding:16px;text-align:center;border-right:3px solid #7C3AED;">
        <div style="font-size:24px;font-weight:700;color:#7C3AED;"><?= (int) $stats['exempt'] ?></div>
        <div style="font-size:12px;color:#6B7280;margin-top:4px;">معفى</div>
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- Filters -->
<div class="card" style="margin-bottom:20px;padding:15px;">
    <form method="GET" action="/sa/subscriptions" style="display:flex;gap:10px;align-items:end;flex-wrap:wrap;">
        <div style="min-width:180px;">
            <label class="form-label" style="font-size:12px;">بحث (اسم/رقم قومي)</label>
            <input type="text" name="q" value="<?= e($filters['q'] ?? '') ?>" placeholder="ابحث باسم اللاعب..." class="form-input">
        </div>
        <div style="min-width:160px;">
            <label class="form-label" style="font-size:12px;">الشهر</label>
            <input type="month" name="month" value="<?= e($filters['month'] ?? '') ?>" class="form-input">
        </div>
        <div style="min-width:150px;">
            <label class="form-label" style="font-size:12px;">النشاط الرياضي</label>
            <select name="discipline_id" class="form-select" id="subFilterDiscipline">
                <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 style="min-width:180px;">
            <label class="form-label" style="font-size:12px;">المجموعة</label>
            <select name="group_id" class="form-select"
                    data-searchable="true"
                    data-cascade-from="discipline_id"
                    data-cascade-url="/api/sa/groups/search?active_only=1&discipline_id={value}"
                    data-placeholder="-- الكل --">
                <option value="">-- الكل --</option>
                <?php foreach ($groups as $g): ?>
                <option value="<?= (int) $g['id'] ?>" <?= ($filters['group_id'] ?? '') === (string) $g['id'] ? 'selected' : '' ?>><?= e($g['name_ar']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div style="min-width:150px;">
            <label class="form-label" style="font-size:12px;">حالة الدفع</label>
            <select name="payment_status" class="form-select">
                <option value="">-- الكل --</option>
                <?php foreach ($statusOptions as $key => $label): ?>
                <option value="<?= e($key) ?>" <?= ($filters['payment_status'] ?? '') === $key ? 'selected' : '' ?>><?= e($label) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <button type="submit" class="btn btn-outline"><i data-lucide="search" style="width:16px;height:16px;vertical-align:middle;"></i> بحث</button>
        <a href="/sa/subscriptions" class="btn btn-sm btn-outline" style="color:#6B7280;">مسح</a>
    </form>
</div>

<!-- Subscriptions Table -->
<div class="card">
    <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>الرقم</th>
                    <th>اللاعب</th>
                    <th>المجموعة</th>
                    <th>الفترة</th>
                    <th>المبلغ</th>
                    <th>الحالة</th>
                    <th>إجراءات</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($subscriptions)): ?>
                <?php foreach ($subscriptions as $sub): ?>
                <tr>
                    <td><code style="font-size:11px;background:#F3F4F6;padding:2px 6px;border-radius:4px;"><?= e($sub['subscription_number'] ?? '') ?></code></td>
                    <td><?= e($sub['player_name'] ?? '—') ?></td>
                    <td><?= e($sub['group_name'] ?? '—') ?></td>
                    <td style="font-size:12px;"><?= e($sub['period_start'] ?? '') ?> - <?= e($sub['period_end'] ?? '') ?></td>
                    <td style="font-weight:600;"><?= money((float) ($sub['final_amount'] ?? 0)) ?></td>
                    <td>
                        <?php
                        $statusColors = [
                            'unpaid' => 'background:#FEF3C7;color:#92400E;',
                            'paid' => 'background:#ECFDF5;color:#059669;',
                            'partial' => 'background:#DBEAFE;color:#1D4ED8;',
                            'exempt' => 'background:#F3E8FF;color:#7C3AED;',
                            'overdue' => 'background:#FEE2E2;color:#DC2626;',
                        ];
                        $statusStyle = $statusColors[$sub['payment_status'] ?? ''] ?? 'background:#F3F4F6;color:#374151;';
                        ?>
                        <span style="<?= $statusStyle ?>padding:3px 10px;border-radius:10px;font-size:12px;font-weight:600;">
                            <?= e($statusOptions[$sub['payment_status'] ?? ''] ?? $sub['payment_status'] ?? '') ?>
                        </span>
                    </td>
                    <td>
                        <a href="/sa/subscriptions/<?= (int) $sub['id'] ?>" class="btn btn-sm btn-outline" style="font-size:12px;padding:4px 10px;">
                            <i data-lucide="eye" style="width:13px;height:13px;vertical-align:middle;"></i> عرض
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php else: ?>
                <tr>
                    <td colspan="7" style="text-align:center;padding:40px;color:#6B7280;">
                        <i data-lucide="credit-card" style="width:36px;height:36px;color:#D1D5DB;display:block;margin:0 auto 10px;"></i>
                        لا توجد اشتراكات
                    </td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if (isset($pagination) && ($pagination['last_page'] ?? 1) > 1): ?>
    <div style="padding:15px;">
        <?php $__template->include('Shared.Components.pagination', ['pagination' => $pagination, 'baseUrl' => '/sa/subscriptions?' . http_build_query(array_filter($filters))]); ?>
    </div>
    <?php endif; ?>
</div>

<div id="previewModal" style="position:fixed;inset:0;background:rgba(0,0,0,.4);z-index:1000;display:none;align-items:center;justify-content:center;">
    <div style="background:#fff;border-radius:12px;padding:24px;width:700px;max-width:90vw;max-height:85vh;overflow-y:auto;box-shadow:0 20px 60px rgba(0,0,0,.2);">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
            <h3 style="margin:0;font-size:18px;">معاينة اشتراكات الشهر القادم</h3>
            <button id="previewClose" style="background:none;border:none;cursor:pointer;font-size:20px;color:#6B7280;">✕</button>
        </div>
        <div id="previewContent" style="font-size:13px;">جاري التحميل...</div>
    </div>
</div>

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

    var previewBtn = document.getElementById('previewBtn');
    var previewModal = document.getElementById('previewModal');
    var previewClose = document.getElementById('previewClose');
    var previewContent = document.getElementById('previewContent');

    if (previewBtn) {
        previewBtn.addEventListener('click', function() {
            previewModal.style.display = 'flex';
            previewContent.innerHTML = '<p style="text-align:center;color:#6B7280;">جاري التحميل...</p>';
            var nextMonth = new Date();
            nextMonth.setMonth(nextMonth.getMonth() + 1);
            var month = nextMonth.getFullYear() + '-' + String(nextMonth.getMonth() + 1).padStart(2, '0');

            fetch('/api/sa/subscriptions/preview?month=' + month)
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    if (!data.success) { previewContent.innerHTML = '<p style="color:#DC2626;">' + (data.error || 'خطأ') + '</p>'; return; }
                    var html = '<div style="display:flex;gap:16px;margin-bottom:12px;flex-wrap:wrap;">';
                    html += '<span style="background:#D1FAE5;padding:4px 12px;border-radius:6px;font-size:12px;font-weight:600;color:#065F46;">' + data.count + ' اشتراك</span>';
                    html += '<span style="background:#EFF6FF;padding:4px 12px;border-radius:6px;font-size:12px;font-weight:600;color:#1D4ED8;">الإجمالي: ' + data.total_amount.toFixed(2) + ' ج.م</span>';
                    if (data.exceptions.length) html += '<span style="background:#FEF3C7;padding:4px 12px;border-radius:6px;font-size:12px;font-weight:600;color:#92400E;">' + data.exceptions.length + ' استثناء</span>';
                    html += '</div>';

                    if (data.items.length) {
                        html += '<table style="width:100%;border-collapse:collapse;font-size:12px;"><thead><tr style="background:#F9FAFB;">';
                        html += '<th style="padding:8px;text-align:right;">اللاعب</th><th style="padding:8px;text-align:right;">المجموعة</th><th style="padding:8px;text-align:right;">المبلغ</th><th style="padding:8px;text-align:center;">تأجيل</th>';
                        html += '</tr></thead><tbody>';
                        data.items.forEach(function(item) {
                            html += '<tr style="border-top:1px solid #F3F4F6;">';
                            html += '<td style="padding:8px;">' + esc(item.player_name) + (item.prorated ? ' <span style="color:#F59E0B;font-size:10px;">نصف</span>' : '') + '</td>';
                            html += '<td style="padding:8px;">' + esc(item.group_name) + '</td>';
                            html += '<td style="padding:8px;direction:ltr;text-align:right;">' + item.amount.toFixed(2) + '</td>';
                            html += '<td style="padding:8px;text-align:center;"><button class="pause-btn" data-player="' + item.player_id + '" data-group="' + item.group_id + '" data-month="' + data.month + '" style="background:#FEF3C7;border:1px solid #F59E0B;border-radius:4px;padding:2px 8px;font-size:11px;cursor:pointer;">تأجيل</button></td>';
                            html += '</tr>';
                        });
                        html += '</tbody></table>';
                    }

                    if (data.exceptions.length) {
                        html += '<h4 style="margin:16px 0 8px;font-size:13px;color:#92400E;">الاستثناءات:</h4><ul style="margin:0;padding:0 16px;">';
                        data.exceptions.forEach(function(ex) {
                            html += '<li style="font-size:12px;color:#6B7280;">' + esc(ex.player_name) + ' — ' + esc(ex.group_name) + ': ' + esc(ex.reason) + '</li>';
                        });
                        html += '</ul>';
                    }

                    previewContent.innerHTML = html;

                    previewContent.querySelectorAll('.pause-btn').forEach(function(btn) {
                        btn.addEventListener('click', function() {
                            var self = this;
                            fetch('/api/sa/subscriptions/pause', {
                                method: 'POST',
                                headers: {'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest'},
                                body: JSON.stringify({player_id: parseInt(self.dataset.player), group_id: parseInt(self.dataset.group), month: self.dataset.month})
                            })
                            .then(function(r) { return r.json(); })
                            .then(function(res) {
                                if (res.success) {
                                    self.textContent = 'تم التأجيل ✓';
                                    self.disabled = true;
                                    self.style.background = '#D1FAE5';
                                    self.style.borderColor = '#059669';
                                    self.style.color = '#065F46';
                                }
                            });
                        });
                    });
                });
        });
    }

    if (previewClose) previewClose.addEventListener('click', function() { previewModal.style.display = 'none'; });
    previewModal.addEventListener('click', function(e) { if (e.target === previewModal) previewModal.style.display = 'none'; });

    function esc(s) { var d = document.createElement('div'); d.textContent = s || ''; return d.innerHTML; }
});
</script>
<?php $__template->endSection(); ?>
