<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<?= $this->include('guru/tahfidz/_subnav') ?>

<!-- Filter -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-body py-2">
        <form class="row g-2 align-items-end" method="GET">
            <input type="hidden" name="program_id" value="<?= $selectedProgram['id'] ?>">
            <div class="col-auto">
                <label class="form-label fw-semibold small mb-1">Kelas</label>
                <select name="classroom_id" class="form-select form-select-sm">
                    <option value="">-- Semua Kelas --</option>
                    <?php foreach ($classrooms as $cid => $cname): ?>
                    <option value="<?= $cid ?>" <?= $selectedClassId == $cid ? 'selected' : '' ?>>
                        <?= esc($cname) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-auto">
                <label class="form-label fw-semibold small mb-1">Dari</label>
                <input type="date" name="start_date" class="form-control form-control-sm" value="<?= $startDate ?>">
            </div>
            <div class="col-auto">
                <label class="form-label fw-semibold small mb-1">Sampai</label>
                <input type="date" name="end_date" class="form-control form-control-sm" value="<?= $endDate ?>">
            </div>
            <div class="col-auto">
                <button class="btn btn-sm btn-success"><i class="bi bi-filter me-1"></i>Filter</button>
            </div>
        </form>
    </div>
</div>

<div class="row g-3">
    <!-- Rekap Setoran -->
    <div class="col-lg-7">
        <div class="card border-0 shadow-sm mb-3">
            <div class="card-header bg-success bg-opacity-10 border-0 py-3 d-flex align-items-center justify-content-between flex-wrap gap-2">
                <div class="fw-bold text-success">
                    <i class="bi bi-journal-check me-2"></i>Rekap Setoran
                    <small class="text-muted fw-normal ms-2"><?= date('d/m/Y', strtotime($startDate)) ?> – <?= date('d/m/Y', strtotime($endDate)) ?></small>
                </div>
                <div class="d-flex align-items-center gap-2">
                    <?php if ($waConfigured): ?>
                        <button type="button" id="btnWaGrup" class="btn btn-xs btn-success fw-semibold" style="font-size:0.75rem; padding: 3px 8px; border-radius: 6px;">
                            <i class="bi bi-whatsapp me-1"></i> Kirim ke Grup
                        </button>
                        <button type="button" id="btnWaOrtu" class="btn btn-xs btn-outline-success fw-semibold" style="font-size:0.75rem; padding: 3px 8px; border-radius: 6px;">
                            <i class="bi bi-whatsapp me-1"></i> Kirim ke Ortu
                        </button>
                    <?php else: ?>
                        <button type="button" class="btn btn-xs btn-secondary fw-semibold" style="font-size:0.75rem; padding: 3px 8px; border-radius: 6px;" disabled title="WhatsApp Gateway Belum Aktif">
                            <i class="bi bi-whatsapp me-1"></i> Kirim WA
                        </button>
                    <?php endif; ?>
                    <span class="badge bg-success"><?= count($rekapSetoran) ?> siswa</span>
                </div>
            </div>
            <div class="table-responsive">
                <?php if (empty($rekapSetoran)): ?>
                <div class="text-center text-muted py-5">
                    <i class="bi bi-inbox fs-1 d-block mb-2 opacity-25"></i>
                    Tidak ada data setoran di rentang ini
                </div>
                <?php else: ?>
                <table class="table table-sm table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Nama</th>
                            <th class="text-center">Setoran</th>
                            <th class="text-center">Rata Nilai</th>
                            <th class="text-center">Total Ayat</th>
                            <th>Terakhir</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($rekapSetoran as $r): ?>
                        <tr>
                            <td>
                                <div class="fw-semibold small"><?= esc($r['full_name']) ?></div>
                                <div class="text-muted" style="font-size:0.72rem;"><?= esc($r['nis']) ?></div>
                            </td>
                            <td class="text-center">
                                <span class="badge bg-primary bg-opacity-15 text-primary fw-bold"><?= $r['total_setoran'] ?>x</span>
                            </td>
                            <td class="text-center">
                                <?php
                                $avg = (float) $r['rata_nilai'];
                                $cls = match(true) { $avg>=95=>'success', $avg>=85=>'primary', $avg>=75=>'info', $avg>=60=>'warning', default=>'danger' };
                                ?>
                                <span class="badge bg-<?= $cls ?>"><?= $r['rata_nilai'] ?></span>
                            </td>
                            <td class="text-center small text-muted"><?= $r['total_ayat_disetorkan'] ?></td>
                            <td class="small text-muted"><?= $r['last_setoran'] ? date('d/m', strtotime($r['last_setoran'])) : '—' ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>
        </div>

        <!-- Rekap Hafalan -->
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-light border-0 py-3">
                <div class="fw-bold"><i class="bi bi-trophy me-2 text-warning"></i>Rekap Hafalan (Total Surah)</div>
            </div>
            <div class="table-responsive">
                <?php if (empty($rekapHafalan)): ?>
                <div class="text-center text-muted py-4"><small>Belum ada data hafalan.</small></div>
                <?php else: ?>
                <table class="table table-sm table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>No</th>
                            <th>Nama</th>
                            <th class="text-center">Surah Hafal</th>
                            <th>
                                <div class="d-flex align-items-center" style="min-width:100px;">Progress</div>
                            </th>
                            <th class="text-center" style="width: 90px;">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($rekapHafalan as $i => $r): ?>
                        <tr>
                            <td class="text-muted small"><?= $i + 1 ?></td>
                            <td>
                                <div class="fw-semibold small"><?= esc($r['full_name']) ?></div>
                                <div class="text-muted" style="font-size:0.72rem;"><?= esc($r['nis']) ?></div>
                            </td>
                            <td class="text-center">
                                <span class="fw-bold text-success"><?= $r['total_hafal'] ?></span>
                                <span class="text-muted small"> / 114</span>
                            </td>
                            <td>
                                <div class="progress" style="height:8px; min-width:80px;">
                                    <?php $pct = $r['total_hafal'] ? round(($r['total_hafal'] / 114) * 100) : 0; ?>
                                    <div class="progress-bar bg-success" style="width:<?= $pct ?>%"></div>
                                </div>
                                <small class="text-muted"><?= $pct ?>%</small>
                            </td>
                            <td class="text-center">
                                <a href="/guru/tahfidz/report-setup?program_id=<?= $selectedProgram['id'] ?>&student_id=<?= $r['id'] ?>" class="btn btn-xs btn-outline-success fw-semibold" style="font-size: 0.72rem; padding: 2px 6px; border-radius: 5px;">
                                    <i class="bi bi-printer me-1"></i>Rapor
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Alert: Belum Setor -->
    <div class="col-lg-5">
        <div class="card border-0 shadow-sm border-start border-danger border-3">
            <div class="card-header bg-danger bg-opacity-10 border-0 py-3 d-flex align-items-center justify-content-between">
                <div class="fw-bold text-danger">
                    <i class="bi bi-exclamation-triangle me-2"></i>Belum Setor 7 Hari
                </div>
                <span class="badge bg-danger"><?= count($blumSetor) ?></span>
            </div>
            <div class="card-body p-0">
                <?php if (empty($blumSetor)): ?>
                <div class="text-center text-muted py-5">
                    <i class="bi bi-check-circle text-success fs-1 d-block mb-2"></i>
                    Semua siswa sudah setor minggu ini 🎉
                </div>
                <?php else: ?>
                <ul class="list-group list-group-flush">
                    <?php foreach ($blumSetor as $bs): ?>
                    <li class="list-group-item px-3 py-2">
                        <div class="d-flex align-items-center gap-2">
                            <div class="rounded-circle bg-danger bg-opacity-15 d-flex align-items-center justify-content-center flex-shrink-0"
                                 style="width:36px; height:36px; font-size:0.85rem; font-weight:700; color:#dc3545;">
                                <?= strtoupper(substr($bs['full_name'], 0, 1)) ?>
                            </div>
                            <div>
                                <div class="fw-semibold small"><?= esc($bs['full_name']) ?></div>
                                <div class="text-muted" style="font-size:0.72rem;">
                                    <?= esc($bs['nis']) ?> —
                                    <?php if ($bs['last_setoran']): ?>
                                        Terakhir: <?= date('d/m/Y', strtotime($bs['last_setoran'])) ?>
                                    <?php else: ?>
                                        <span class="text-danger">Belum pernah setor</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <a href="/guru/tahfidz/setoran/<?= $selectedProgram['id'] ?>?student_id=<?= $bs['id'] ?>"
                               class="btn btn-sm btn-outline-success ms-auto" title="Input Setoran">
                                <i class="bi bi-plus"></i>
                            </a>
                        </div>
                    </li>
                    <?php endforeach; ?>
                </ul>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const CSRF_NAME = '<?= csrf_token() ?>';
    const CSRF_TOKEN = '<?= csrf_hash() ?>';

    const btnWaGrup = document.getElementById('btnWaGrup');
    const btnWaOrtu = document.getElementById('btnWaOrtu');

    if (btnWaGrup) {
        btnWaGrup.addEventListener('click', async function () {
            const groupId = '<?= esc($waGroupId) ?>';
            if (!groupId) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Group ID WA Kosong',
                    text: 'Silakan isi WhatsApp Group ID di pengaturan program tahfidz terlebih dahulu (Menu Admin).',
                    confirmButtonColor: '#198754'
                });
                return;
            }

            const { value: accept } = await Swal.fire({
                title: 'Kirim Rekap ke Grup?',
                text: `Apakah Anda yakin ingin mengirim rekap setoran periode ini ke grup WA?`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#198754',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Ya, Kirim!',
                cancelButtonText: 'Batal'
            });

            if (!accept) return;

            btnWaGrup.disabled = true;
            btnWaGrup.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Mengirim...';

            const fd = new FormData();
            fd.append(CSRF_NAME, CSRF_TOKEN);
            fd.append('program_id', '<?= $selectedProgram['id'] ?>');
            fd.append('group_id', groupId);
            fd.append('start_date', '<?= $startDate ?>');
            fd.append('end_date', '<?= $endDate ?>');

            try {
                const res = await fetch('/guru/tahfidz/wa-group', { method: 'POST', body: fd });
                const data = await res.json();
                if (data.success) {
                    Swal.fire({ icon: 'success', title: 'Berhasil', text: data.message, confirmButtonColor: '#198754' });
                } else {
                    Swal.fire({ icon: 'error', title: 'Gagal', text: data.message, confirmButtonColor: '#dc3545' });
                }
            } catch (err) {
                Swal.fire({ icon: 'error', title: 'Error', text: 'Terjadi kesalahan sistem.', confirmButtonColor: '#dc3545' });
            } finally {
                btnWaGrup.disabled = false;
                btnWaGrup.innerHTML = '<i class="bi bi-whatsapp me-1"></i> Kirim ke Grup';
            }
        });
    }

    if (btnWaOrtu) {
        btnWaOrtu.addEventListener('click', async function () {
            const { value: accept } = await Swal.fire({
                title: 'Kirim ke Ortu?',
                text: 'Sistem akan mengirimkan pesan laporan harian/mingguan ke masing-masing no. WA Ayah (father_phone) yang terdaftar. Lanjutkan?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#198754',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Ya, Kirim!',
                cancelButtonText: 'Batal'
            });

            if (!accept) return;

            btnWaOrtu.disabled = true;
            btnWaOrtu.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> Mengirim...';

            const fd = new FormData();
            fd.append(CSRF_NAME, CSRF_TOKEN);
            fd.append('program_id', '<?= $selectedProgram['id'] ?>');
            fd.append('start_date', '<?= $startDate ?>');
            fd.append('end_date', '<?= $endDate ?>');

            try {
                const res = await fetch('/guru/tahfidz/wa-ortu', { method: 'POST', body: fd });
                const data = await res.json();
                if (data.success) {
                    Swal.fire({ icon: 'success', title: 'Berhasil', text: data.message, confirmButtonColor: '#198754' });
                } else {
                    Swal.fire({ icon: 'error', title: 'Gagal', text: data.message, confirmButtonColor: '#dc3545' });
                }
            } catch (err) {
                Swal.fire({ icon: 'error', title: 'Error', text: 'Terjadi kesalahan sistem.', confirmButtonColor: '#dc3545' });
            } finally {
                btnWaOrtu.disabled = false;
                btnWaOrtu.innerHTML = '<i class="bi bi-whatsapp me-1"></i> Kirim ke Ortu';
            }
        });
    }
});
</script>

<?= $this->endSection() ?>
