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

<style>
/* CSS Responsive untuk Mobile di halaman Rekap QR Harian */
@media (max-width: 575.98px) {
    .tab-content table, 
    .tab-content thead, 
    .tab-content tbody, 
    .tab-content th, 
    .tab-content td, 
    .tab-content tr {
        display: block;
    }
    .tab-content thead {
        display: none; /* Sembunyikan header tabel */
    }
    .tab-content tr {
        border-bottom: 1px solid var(--border-color);
        padding: 12px 8px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-wrap: wrap;
        gap: 8px;
    }
    .tab-content td {
        border: none !important;
        padding: 0 !important;
    }
    .tab-content td:first-child {
        display: none; /* Sembunyikan nomor urut */
    }
    .tab-content td.fw-semibold {
        flex: 1 1 60%;
        min-width: 140px;
    }
    /* Sembunyikan NIS/Kelas yang lama pada mode mobile desktop-only */
    .tab-content td:nth-child(3), 
    .tab-content td:nth-child(4) {
        display: none;
    }
    .tab-content td:last-child {
        flex: 0 0 auto;
        display: flex;
        align-items: center;
        gap: 6px;
    }
    
    /* Tampilkan Jam Scan (Tab Hadir) dan Status Badge (Tab Keterangan) di mobile */
    #tab-hadir td:nth-child(5) {
        display: block !important;
        flex: 0 0 auto;
    }
    #tab-keterangan td:nth-child(5) {
        display: block !important;
        flex: 0 0 auto;
    }
}
</style>

<?php
// Kelompokkan baris per status untuk kemudahan tampil
$byStatus = ['hadir' => [], 'belum' => [], 'Sakit' => [], 'Izin' => [], 'Alpha' => []];
foreach ($rows as $r) {
    $k = $r['kehadiran'];
    if (!isset($byStatus[$k])) $k = 'belum';
    $byStatus[$k][] = $r;
}
?>

<div class="card shadow-sm mb-3">
    <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
        <div>
            <h5 class="mb-0"><i class="bi bi-clipboard2-pulse me-2 text-primary"></i>Rekap Absensi Harian</h5>
            <small class="text-muted">Semua siswa aktif beserta status kehadiran hari ini</small>
        </div>
        <a href="/attendance/qr-scan" class="btn btn-success btn-sm">
            <i class="bi bi-qr-code-scan me-1"></i>Buka Scanner
        </a>
        <?php if ($classroom_id && !empty($waGroupId)): ?>
        <button class="btn btn-sm btn-outline-success" onclick="sendWaGrup()" title="Kirim rekap absensi ke grup WA kelas ini">
            <i class="bi bi-whatsapp me-1"></i>Kirim ke Grup WA
        </button>
        <?php endif; ?>
    </div>
    <div class="card-body pb-2">
        <!-- Filter tanggal & kelas -->
        <form method="get" class="row g-2 align-items-end mb-3">
            <div class="col-auto">
                <label class="form-label small fw-semibold mb-1">Tanggal</label>
                <input type="date" name="date" value="<?= esc($date) ?>" class="form-control form-control-sm">
            </div>
            <div class="col-auto">
                <label class="form-label small fw-semibold mb-1">Kelas</label>
                <select name="classroom_id" class="form-select form-select-sm" style="min-width:160px">
                    <option value="">— Semua Kelas —</option>
                    <?php foreach ($classrooms as $cls): ?>
                    <option value="<?= $cls['id'] ?>"
                        <?= ($classroom_id == $cls['id']) ? 'selected' : '' ?>>
                        <?= esc($cls['grade_name'] . ' ' . $cls['classroom_name']) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-auto">
                <button type="submit" class="btn btn-primary btn-sm">
                    <i class="bi bi-search me-1"></i>Tampilkan
                </button>
            </div>
        </form>

        <!-- Kartu ringkasan -->
        <div class="row g-2 mb-3">
            <?php
            $cards = [
                ['hadir', 'success', 'bi-check-circle-fill',  'Hadir (QR)'],
                ['belum', 'warning', 'bi-question-circle-fill','Belum Diketahui'],
                ['Sakit', 'info',    'bi-thermometer-half',    'Sakit'],
                ['Izin',  'primary', 'bi-envelope-check',      'Izin'],
                ['Alpha', 'danger',  'bi-x-circle-fill',       'Alpha'],
            ];
            foreach ($cards as [$key, $color, $icon, $label]):
            ?>
            <div class="col-6 col-md">
                <div class="border rounded p-2 text-center border-<?= $color ?>-subtle bg-<?= $color ?>-subtle">
                    <i class="bi <?= $icon ?> text-<?= $color ?> fs-5"></i>
                    <div class="fw-bold fs-5 text-<?= $color ?>"><?= $summary[$key] ?? 0 ?></div>
                    <div class="small text-muted"><?= $label ?></div>
                </div>
            </div>
            <?php endforeach; ?>
            <div class="col-6 col-md">
                <div class="border rounded p-2 text-center">
                    <i class="bi bi-people-fill text-secondary fs-5"></i>
                    <div class="fw-bold fs-5"><?= count($rows) ?></div>
                    <div class="small text-muted">Total Siswa</div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Tab navigasi per status -->
<ul class="nav nav-tabs mb-0" id="statusTab" role="tablist">
    <li class="nav-item">
        <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-belum" type="button">
            <i class="bi bi-question-circle text-warning me-1"></i>
            Belum Diketahui
            <?php if ($summary['belum'] > 0): ?>
            <span class="badge bg-warning text-dark ms-1"><?= $summary['belum'] ?></span>
            <?php endif; ?>
        </button>
    </li>
    <li class="nav-item">
        <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-hadir" type="button">
            <i class="bi bi-check-circle text-success me-1"></i>
            Hadir QR
            <span class="badge bg-success ms-1"><?= $summary['hadir'] ?></span>
        </button>
    </li>
    <li class="nav-item">
        <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-keterangan" type="button">
            <i class="bi bi-pencil-square text-info me-1"></i>
            Ada Keterangan
            <span class="badge bg-secondary ms-1"><?= ($summary['Sakit'] + $summary['Izin'] + $summary['Alpha']) ?></span>
        </button>
    </li>
</ul>

<div class="tab-content border border-top-0 rounded-bottom bg-body p-3 shadow-sm">

    <!-- TAB: BELUM DIKETAHUI -->
    <div class="tab-pane fade show active" id="tab-belum">
        <?php if (empty($byStatus['belum'])): ?>
        <div class="alert alert-success mb-0">
            <i class="bi bi-check-circle me-2"></i>
            Semua siswa sudah tercatat statusnya. Tidak ada yang perlu dicek.
        </div>
        <?php else: ?>
        <div class="d-flex justify-content-between align-items-center mb-2 flex-wrap gap-2">
            <p class="text-muted small mb-0">
                <i class="bi bi-info-circle me-1"></i>
                Siswa berikut <strong>belum scan QR</strong> dan <strong>belum ada keterangan</strong> dari BK.
            </p>
            <?php if (!empty($classroom_id)): ?>
            <button class="btn btn-success btn-sm py-1" onclick="markAllPresent(<?= esc($classroom_id) ?>)">
                <i class="bi bi-check-all me-1"></i>Hadirkan Semua yang Belum Scan
            </button>
            <?php endif; ?>
        </div>
        <div class="table-responsive">
            <table class="table table-hover table-sm align-middle mb-0">
                <thead class="table-warning">
                    <tr>
                        <th style="width:36px">#</th>
                        <th>Nama Siswa</th>
                        <th>NIS</th>
                        <th>Kelas</th>
                        <th style="width:120px">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($byStatus['belum'] as $i => $r): ?>
                    <tr>
                        <td class="text-muted small"><?= $i + 1 ?></td>
                        <td class="fw-semibold">
                            <?= esc($r['full_name']) ?>
                            <div class="small text-muted d-sm-none" style="font-size: 0.75rem; font-weight: normal; margin-top: 2px;">
                                <?= esc(trim(($r['grade_name'] ?? '') . ' ' . ($r['classroom_name'] ?? '-'))) ?>
                            </div>
                        </td>
                        <td><small class="text-muted"><?= esc($r['nis']) ?></small></td>
                        <td>
                            <span class="badge bg-secondary-subtle text-secondary-emphasis border border-secondary-subtle small">
                                <?= esc(trim(($r['grade_name'] ?? '') . ' ' . ($r['classroom_name'] ?? '-'))) ?>
                            </span>
                        </td>
                        <td>
                            <div class="dropdown">
                                <button class="btn btn-outline-secondary btn-sm dropdown-toggle py-0 px-2 small" type="button" data-bs-toggle="dropdown">
                                    Set Status
                                </button>
                                <ul class="dropdown-menu dropdown-menu-end shadow-sm">
                                    <li><a class="dropdown-item small" href="#" onclick="updateStatus(<?= $r['student_id'] ?>, '<?= esc(addslashes($r['full_name'])) ?>', 'hadir')"><i class="bi bi-check-circle text-success me-2"></i>Hadir</a></li>
                                    <li><a class="dropdown-item small" href="#" onclick="updateStatus(<?= $r['student_id'] ?>, '<?= esc(addslashes($r['full_name'])) ?>', 'Sakit')"><i class="bi bi-thermometer-half text-warning me-2"></i>Sakit</a></li>
                                    <li><a class="dropdown-item small" href="#" onclick="updateStatus(<?= $r['student_id'] ?>, '<?= esc(addslashes($r['full_name'])) ?>', 'Izin')"><i class="bi bi-envelope-check text-info me-2"></i>Izin</a></li>
                                    <li><a class="dropdown-item small" href="#" onclick="updateStatus(<?= $r['student_id'] ?>, '<?= esc(addslashes($r['full_name'])) ?>', 'Alpha')"><i class="bi bi-x-circle text-danger me-2"></i>Alpha</a></li>
                                    <li><hr class="dropdown-divider"></li>
                                    <li><a class="dropdown-item small" href="#" onclick="updateStatus(<?= $r['student_id'] ?>, '<?= esc(addslashes($r['full_name'])) ?>', 'belum')"><i class="bi bi-question-circle text-muted me-2"></i>Reset</a></li>
                                </ul>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>

    <!-- TAB: HADIR QR -->
    <div class="tab-pane fade" id="tab-hadir">
        <?php if (empty($byStatus['hadir'])): ?>
        <div class="alert alert-info mb-0">
            <i class="bi bi-info-circle me-2"></i>Belum ada siswa yang scan QR hari ini.
        </div>
        <?php else: ?>
        <div class="table-responsive">
            <table class="table table-hover table-sm align-middle mb-0">
                <thead class="table-success">
                    <tr>
                        <th style="width:36px">#</th>
                        <th>Nama Siswa</th>
                        <th>NISN</th>
                        <th>Kelas</th>
                        <th>Jam Scan</th>
                        <th style="width:120px">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($byStatus['hadir'] as $i => $r): ?>
                    <tr>
                        <td class="text-muted small"><?= $i + 1 ?></td>
                        <td class="fw-semibold">
                            <?= esc($r['full_name']) ?>
                            <div class="small text-muted d-sm-none" style="font-size: 0.75rem; font-weight: normal; margin-top: 2px;">
                                <?= esc(trim(($r['grade_name'] ?? '') . ' ' . ($r['classroom_name'] ?? '-'))) ?>
                            </div>
                        </td>
                        <td><code class="small"><?= esc($r['nisn']) ?></code></td>
                        <td>
                            <span class="badge bg-success-subtle text-success-emphasis border border-success-subtle small">
                                <?= esc(trim(($r['grade_name'] ?? '') . ' ' . ($r['classroom_name'] ?? '-'))) ?>
                            </span>
                        </td>
                        <td>
                            <span class="badge bg-success">
                                <i class="bi bi-clock me-1"></i><?= esc(substr($r['scan_time'] ?? '', 0, 5)) ?>
                            </span>
                        </td>
                        <td>
                            <div class="dropdown">
                                <button class="btn btn-outline-secondary btn-sm dropdown-toggle py-0 px-2 small" type="button" data-bs-toggle="dropdown">
                                    Set Status
                                </button>
                                <ul class="dropdown-menu dropdown-menu-end shadow-sm">
                                    <li><a class="dropdown-item small" href="#" onclick="updateStatus(<?= $r['student_id'] ?>, '<?= esc(addslashes($r['full_name'])) ?>', 'hadir')"><i class="bi bi-check-circle text-success me-2"></i>Hadir</a></li>
                                    <li><a class="dropdown-item small" href="#" onclick="updateStatus(<?= $r['student_id'] ?>, '<?= esc(addslashes($r['full_name'])) ?>', 'Sakit')"><i class="bi bi-thermometer-half text-warning me-2"></i>Sakit</a></li>
                                    <li><a class="dropdown-item small" href="#" onclick="updateStatus(<?= $r['student_id'] ?>, '<?= esc(addslashes($r['full_name'])) ?>', 'Izin')"><i class="bi bi-envelope-check text-info me-2"></i>Izin</a></li>
                                    <li><a class="dropdown-item small" href="#" onclick="updateStatus(<?= $r['student_id'] ?>, '<?= esc(addslashes($r['full_name'])) ?>', 'Alpha')"><i class="bi bi-x-circle text-danger me-2"></i>Alpha</a></li>
                                    <li><hr class="dropdown-divider"></li>
                                    <li><a class="dropdown-item small" href="#" onclick="updateStatus(<?= $r['student_id'] ?>, '<?= esc(addslashes($r['full_name'])) ?>', 'belum')"><i class="bi bi-question-circle text-muted me-2"></i>Reset</a></li>
                                </ul>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>

    <!-- TAB: ADA KETERANGAN (Sakit/Izin/Alpha) -->
    <div class="tab-pane fade" id="tab-keterangan">
        <?php
        $ketList = array_merge($byStatus['Sakit'], $byStatus['Izin'], $byStatus['Alpha']);
        usort($ketList, fn($a, $b) => strcmp($a['full_name'], $b['full_name']));
        ?>
        <?php if (empty($ketList)): ?>
        <div class="alert alert-info mb-0">
            <i class="bi bi-info-circle me-2"></i>Belum ada keterangan Sakit/Izin/Alpha untuk hari ini.
        </div>
        <?php else: ?>
        <div class="table-responsive">
            <table class="table table-hover table-sm align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th style="width:36px">#</th>
                        <th>Nama Siswa</th>
                        <th>NIS</th>
                        <th>Kelas</th>
                        <th>Status</th>
                        <th style="width:120px">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($ketList as $i => $r):
                        $badgeColor = match($r['kehadiran']) {
                            'Sakit' => 'info',
                            'Izin'  => 'primary',
                            default => 'danger',
                        };
                    ?>
                    <tr>
                        <td class="text-muted small"><?= $i + 1 ?></td>
                        <td class="fw-semibold">
                            <?= esc($r['full_name']) ?>
                            <div class="small text-muted d-sm-none" style="font-size: 0.75rem; font-weight: normal; margin-top: 2px;">
                                <?= esc(trim(($r['grade_name'] ?? '') . ' ' . ($r['classroom_name'] ?? '-'))) ?>
                            </div>
                        </td>
                        <td><small class="text-muted"><?= esc($r['nis']) ?></small></td>
                        <td>
                            <span class="badge bg-secondary-subtle text-secondary-emphasis border border-secondary-subtle small">
                                <?= esc(trim(($r['grade_name'] ?? '') . ' ' . ($r['classroom_name'] ?? '-'))) ?>
                            </span>
                        </td>
                        <td>
                            <span class="badge bg-<?= $badgeColor ?>">
                                <?= esc($r['kehadiran']) ?>
                            </span>
                        </td>
                        <td>
                            <div class="dropdown">
                                <button class="btn btn-outline-secondary btn-sm dropdown-toggle py-0 px-2 small" type="button" data-bs-toggle="dropdown">
                                    Set Status
                                </button>
                                <ul class="dropdown-menu dropdown-menu-end shadow-sm">
                                    <li><a class="dropdown-item small" href="#" onclick="updateStatus(<?= $r['student_id'] ?>, '<?= esc(addslashes($r['full_name'])) ?>', 'hadir')"><i class="bi bi-check-circle text-success me-2"></i>Hadir</a></li>
                                    <li><a class="dropdown-item small" href="#" onclick="updateStatus(<?= $r['student_id'] ?>, '<?= esc(addslashes($r['full_name'])) ?>', 'Sakit')"><i class="bi bi-thermometer-half text-warning me-2"></i>Sakit</a></li>
                                    <li><a class="dropdown-item small" href="#" onclick="updateStatus(<?= $r['student_id'] ?>, '<?= esc(addslashes($r['full_name'])) ?>', 'Izin')"><i class="bi bi-envelope-check text-info me-2"></i>Izin</a></li>
                                    <li><a class="dropdown-item small" href="#" onclick="updateStatus(<?= $r['student_id'] ?>, '<?= esc(addslashes($r['full_name'])) ?>', 'Alpha')"><i class="bi bi-x-circle text-danger me-2"></i>Alpha</a></li>
                                    <li><hr class="dropdown-divider"></li>
                                    <li><a class="dropdown-item small" href="#" onclick="updateStatus(<?= $r['student_id'] ?>, '<?= esc(addslashes($r['full_name'])) ?>', 'belum')"><i class="bi bi-question-circle text-muted me-2"></i>Reset</a></li>
                                </ul>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>

</div>

<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
// Simpan tab aktif di localStorage
const tabEls = document.querySelectorAll('#statusTab button[data-bs-toggle="tab"]');
const savedTab = localStorage.getItem('qrReportTab');
if (savedTab) {
    const el = document.querySelector(`#statusTab button[data-bs-target="${savedTab}"]`);
    if (el) bootstrap.Tab.getOrCreateInstance(el).show();
}
tabEls.forEach(el => {
    el.addEventListener('shown.bs.tab', () => {
        localStorage.setItem('qrReportTab', el.dataset.bsTarget);
    });
});

function updateStatus(studentId, studentName, status) {
    let statusLabel = '';
    if (status === 'hadir') statusLabel = 'Hadir';
    else if (status === 'Sakit') statusLabel = 'Sakit';
    else if (status === 'Izin') statusLabel = 'Izin';
    else if (status === 'Alpha') statusLabel = 'Alpha';
    else if (status === 'belum') statusLabel = 'Belum Diketahui (Reset)';

    Swal.fire({
        title: 'Ubah Status Kehadiran?',
        text: `Ubah status ${studentName} menjadi ${statusLabel}?`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Ya, Ubah!',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Memproses...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            $.post('/attendance/qr-save-status', {
                student_id: studentId,
                date: '<?= esc($date) ?>',
                status: status,
                <?= csrf_token() ?>: '<?= csrf_hash() ?>'
            }, function(res) {
                if (res.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil',
                        text: res.message,
                        timer: 1200,
                        showConfirmButton: false
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire('Gagal', res.message, 'error');
                }
            }).fail(function() {
                Swal.fire('Error', 'Gagal menghubungi server.', 'error');
            });
        }
    });
}

function markAllPresent(classroomId) {
    if (!classroomId) {
        Swal.fire('Info', 'Pilih kelas terlebih dahulu untuk menghadirkan massal.', 'info');
        return;
    }
    
    if (!confirm('Hadirkan semua siswa yang belum scan di kelas ini? (Status Sakit/Izin dari BK tidak akan ditimpa)')) return;
    
    Swal.fire({
        title: 'Memproses...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    $.post('/attendance/qr-mark-present-bulk', {
        classroom_id: classroomId,
        date: '<?= esc($date) ?>',
        <?= csrf_token() ?>: '<?= csrf_hash() ?>'
    }, function(res) {
        if (res.success) {
            Swal.fire({
                icon: 'success',
                title: 'Selesai',
                text: res.message,
                timer: 1200,
                showConfirmButton: false
            }).then(() => {
                location.reload();
            });
        } else {
            Swal.fire('Gagal', res.message, 'error');
        }
    }).fail(function() {
        Swal.fire('Error', 'Gagal menghubungi server.', 'error');
    });
}
<?php if ($classroom_id && !empty($waGroupId)): ?>
function sendWaGrup() {
    const kelasName = '<?= esc($classrooms[0]['grade_name'] ?? '') . ' ' . esc($classrooms[0]['classroom_name'] ?? '') ?>';
    Swal.fire({
        title: 'Kirim Rekap ke Grup WA',
        html: `Kirim rekap absensi <strong><?= esc($date) ?></strong><br>ke grup WA kelas <strong>${kelasName}</strong>?`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: '<i class="bi bi-whatsapp me-1"></i>Ya, Kirim!',
        cancelButtonText: 'Batal',
        confirmButtonColor: '#25d366',
    }).then(result => {
        if (!result.isConfirmed) return;

        Swal.fire({ title: 'Mengirim...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });

        const params = new URLSearchParams();
        params.append('<?= csrf_token() ?>', '<?= csrf_hash() ?>');
        params.append('classroom_id', '<?= $classroom_id ?>');
        params.append('date', '<?= $date ?>');

        fetch('/attendance/send-wa-grup', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' },
            body: params,
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                Swal.fire({ title: 'Berhasil', text: data.message, icon: 'success' });
            } else {
                Swal.fire({ title: 'Gagal', text: data.message, icon: 'error' });
            }
        })
        .catch(() => Swal.fire({ title: 'Error', text: 'Gagal menghubungi server.', icon: 'error' }));
    });
}
<?php endif; ?>
</script>
<?= $this->endSection() ?>
