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

<div class="card">
    <div class="card-header">
        <div class="d-flex align-items-center gap-2">
            <i class="bi bi-calendar-check text-primary"></i>
            <span class="fw-semibold">Absensi Siswa</span>
        </div>
    </div>
    <div class="card-body">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="alert alert-info py-2 small">
                    <i class="bi bi-info-circle me-1"></i>
                    <strong>Catatan:</strong> Default siswa = <strong>HADIR</strong>. Klik tombol [S] [I] [A] untuk siswa yang tidak hadir.
                </div>
                
                <form id="formSelectClass">
                    <div class="mb-3">
                        <label class="form-label">Tanggal Absen</label>
                        <input type="date" name="date" id="date" class="form-control" 
                            value="<?= date('Y-m-d') ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Tingkat</label>
                        <select name="grade_id" id="grade_id" class="form-select" required>
                            <option value="">-- Pilih Tingkat --</option>
                            <?php foreach ($grades as $g): ?>
                            <option value="<?= $g['id'] ?>"><?= esc($g['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Kelas</label>
                        <select name="classroom_id" id="classroom_id" class="form-select" required disabled>
                            <option value="">-- Pilih Tingkat Dulu --</option>
                        </select>
                    </div>
                    <input type="hidden" name="period_id" id="period_id" value="<?= $activePeriod['id'] ?>">
                    <button type="submit" class="btn btn-primary w-100" id="btnStart">
                        <i class="bi bi-play-circle me-2"></i>Mulai Absen
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Modal Absensi -->
<div class="modal fade" id="modalAttendance" data-bs-backdrop="static" tabindex="-1">
    <div class="modal-dialog modal-lg modal-fullscreen-sm-down modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <div>
                    <h6 class="modal-title fw-semibold">
                        <i class="bi bi-person-check text-primary me-2"></i>
                        Absensi Siswa - <span id="modalClassName"></span>
                    </h6>
                    <small class="text-muted" id="modalDate"></small>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-0" id="attendanceBody">
                <div class="text-center py-5">
                    <div class="spinner-border text-primary"></div>
                    <p class="mt-2">Memuat data...</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">
                    <i class="bi bi-x-circle me-1"></i>Tutup
                </button>
                <span class="text-muted small me-auto">
                    <i class="bi bi-info-circle"></i> Klik tombol untuk mengubah status
                </span>
            </div>
        </div>
    </div>
</div>

<style>
.status-btn {
    transition: all 0.2s ease;
}
.status-btn.active-sakit {
    background-color: #ffc107;
    color: #000;
    border-color: #ffc107;
}
.status-btn.active-izin {
    background-color: #0dcaf0;
    color: #000;
    border-color: #0dcaf0;
}
.status-btn.active-alpha {
    background-color: #dc3545;
    color: #fff;
    border-color: #dc3545;
}
.status-btn.active-hadir {
    background-color: #198754;
    color: #fff;
    border-color: #198754;
}

/* Responsive Table to Cards for Mobile */
@media (max-width: 575.98px) {
    #attendanceBody table, 
    #attendanceBody thead, 
    #attendanceBody tbody, 
    #attendanceBody th, 
    #attendanceBody td, 
    #attendanceBody tr {
        display: block;
    }
    #attendanceBody thead {
        display: none; /* Sembunyikan header tabel */
    }
    #attendanceBody tr {
        border-bottom: 1px solid var(--border-color);
        padding: 12px 16px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 12px;
    }
    #attendanceBody td {
        border: none !important;
        padding: 0 !important;
    }
    #attendanceBody td:first-child {
        display: none; /* Sembunyikan nomor urut */
    }
    #attendanceBody td.align-middle:nth-child(2) {
        flex: 1 1 auto;
        text-align: left;
    }
    #attendanceBody td.align-middle:nth-child(3) {
        flex: 0 0 auto;
    }
    /* Sederhanakan tombol S I A di HP agar muat di baris sempit */
    .status-btn {
        padding: 6px 12px !important;
        font-size: 0.8rem !important;
    }
}
</style>

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

<?= $this->section('scripts') ?>
<script>
$(document).ready(function() {
    // Load kelas berdasarkan tingkat
    $('#grade_id').change(function() {
        const gradeId = $(this).val();
        const periodId = $('#period_id').val();
        const classroomSelect = $('#classroom_id');
        
        if (!gradeId) {
            classroomSelect.prop('disabled', true).html('<option value="">-- Pilih Tingkat Dulu --</option>');
            return;
        }
        
        $.ajax({
            url: '/attendance/get-classrooms',
            method: 'GET',
            data: { grade_id: gradeId, period_id: periodId },
            dataType: 'json',
            success: function(data) {
                classroomSelect.prop('disabled', false);
                let options = '<option value="">-- Pilih Kelas --</option>';
                $.each(data, function(i, cls) {
                    options += `<option value="${cls.id}">${cls.name} (${cls.grade_name})</option>`;
                });
                classroomSelect.html(options);
            }
        });
    });
    
    // Submit form
    $('#formSelectClass').submit(function(e) {
        e.preventDefault();
        
        const classroomId = $('#classroom_id').val();
        const periodId = $('#period_id').val();
        const date = $('#date').val();
        const className = $('#classroom_id option:selected').text();
        
        if (!classroomId) {
            alert('Pilih kelas terlebih dahulu!');
            return;
        }
        
        $('#modalClassName').text(className);
        $('#modalDate').text(date);
        $('#modalAttendance').modal('show');
        
        // Load siswa
        $.ajax({
            url: '/attendance/get-students',
            method: 'GET',
            data: {
                classroom_id: classroomId,
                period_id: periodId,
                date: date
            },
            dataType: 'json',
            success: function(data) {
                if (data.success && data.students.length > 0) {
                    renderAttendanceTable(data.students, classroomId, periodId, date);
                } else {
                    $('#attendanceBody').html('<div class="text-center py-5 text-muted">Tidak ada siswa di kelas ini</div>');
                }
            },
            error: function() {
                $('#attendanceBody').html('<div class="text-center py-5 text-danger">Gagal memuat data</div>');
            }
        });
    });
});

function renderAttendanceTable(students, classroomId, periodId, date) {
    let html = `
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light sticky-top">
                    <tr>
                        <th width="50">#</th>
                        <th>Nama Siswa</th>
                        <th width="250" class="text-center">Status</th>
                    </tr>
                </thead>
                <tbody>
    `;
    
    $.each(students, function(i, student) {
        const status = student.attendance_status || '';
        const hadirActive = (!status || status === '') ? 'active-hadir' : '';
        const sakitActive = (status === 'Sakit') ? 'active-sakit' : '';
        const izinActive = (status === 'Izin') ? 'active-izin' : '';
        const alphaActive = (status === 'Alpha') ? 'active-alpha' : '';
        
        html += `
            <tr>
                <td class="align-middle">${i + 1}</td>
                <td class="align-middle">
                    <strong>${escapeHtml(student.full_name)}</strong><br>
                    <small class="text-muted">NIS: ${student.nis}</small>
                </td>
                <td class="align-middle text-center">
                    <div class="btn-group" role="group">
                        <button type="button" class="btn btn-sm btn-outline-success status-btn ${hadirActive}" 
                            onclick="saveAttendance(${student.id}, ${classroomId}, ${periodId}, '${date}', 'Hadir', this)" title="Reset ke Hadir">
                            <i class="bi bi-check-circle me-1"></i>H
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-warning status-btn ${sakitActive}" 
                            onclick="saveAttendance(${student.id}, ${classroomId}, ${periodId}, '${date}', 'Sakit', this)">
                            <i class="bi bi-thermometer-high me-1"></i>S
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-info status-btn ${izinActive}" 
                            onclick="saveAttendance(${student.id}, ${classroomId}, ${periodId}, '${date}', 'Izin', this)">
                            <i class="bi bi-envelope-paper me-1"></i>I
                        </button>
                        <button type="button" class="btn btn-sm btn-outline-danger status-btn ${alphaActive}" 
                            onclick="saveAttendance(${student.id}, ${classroomId}, ${periodId}, '${date}', 'Alpha', this)">
                            <i class="bi bi-x-circle me-1"></i>A
                        </button>
                    </div>
                </td>
            </tr>
        `;
    });
    
    html += `
                </tbody>
            </table>
        </div>
    `;
    
    $('#attendanceBody').html(html);
}

function saveAttendance(studentId, classroomId, periodId, date, status, btn) {
    const buttons = $(btn).parent().find('.status-btn');
    
    $.ajax({
        url: '/attendance/save',
        method: 'POST',
        data: {
            student_id: studentId,
            classroom_id: classroomId,
            period_id: periodId,
            date: date,
            status: status, // 'Hadir' (reset), 'Sakit', 'Izin', 'Alpha'
            '<?= csrf_token() ?>': '<?= csrf_hash() ?>'
        },
        dataType: 'json',
        success: function(data) {
            if (data.success) {
                // Reset semua tombol di baris ini
                buttons.removeClass('active-hadir active-sakit active-izin active-alpha');
                
                if (data.status === 'Sakit') {
                    buttons.eq(1).addClass('active-sakit');
                } else if (data.status === 'Izin') {
                    buttons.eq(2).addClass('active-izin');
                } else if (data.status === 'Alpha') {
                    buttons.eq(3).addClass('active-alpha');
                } else {
                    // Jika null / 'Hadir'
                    buttons.eq(0).addClass('active-hadir');
                }
                
                // Feedback visual ringan
                $(btn).addClass('animate-pulse');
                setTimeout(() => $(btn).removeClass('animate-pulse'), 200);
            }
        }
    });
}

function escapeHtml(str) {
    if (!str) return '';
    return str.replace(/[&<>]/g, function(m) {
        if (m === '&') return '&amp;';
        if (m === '<') return '&lt;';
        if (m === '>') return '&gt;';
        return m;
    });
}
</script>
<?= $this->endSection() ?>