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

<?php
$period = $activePeriod ?? [];
$semester = $period['semester'] ?? '—';
$tahun = $period['academic_year_name'] ?? '—';
?>

<div class="card shadow-sm border-0 rounded-3">
    <div class="card-header bg-white py-3 border-0 d-flex align-items-center justify-content-between">
        <div>
            <h5 class="card-title fw-bold mb-0"><i class="bi bi-journal-plus me-2 text-primary"></i>Tambah Jurnal</h5>
            <p class="text-muted small mb-0">Isi jurnal setelah selesai mengajar. Data tersimpan otomatis untuk presensi.</p>
        </div>
        <a href="/guru/journal" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-arrow-left me-1"></i>Kembali
        </a>
    </div>
    <div class="card-body p-4">
        <form id="journalForm">
            <?= csrf_field() ?>

            <div class="row g-3">

                <!-- Tanggal -->
                <div class="col-12 col-md-4">
                    <label class="form-label fw-semibold">Tanggal</label>
                    <input type="date" name="meeting_date" class="form-control border-0 bg-light shadow-none py-2"
                           value="<?= date('Y-m-d') ?>" required>
                </div>

                <!-- Kelas -->
                <div class="col-12 col-md-4">
                    <label class="form-label fw-semibold">Kelas</label>
                    <select name="classroom_id" id="classroomSelect" class="form-select border-0 bg-light shadow-none py-2" required>
                        <option value="">-- Pilih Kelas --</option>
                        <?php foreach ($classrooms as $c): ?>
                        <option value="<?= $c['id'] ?>"><?= esc($c['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Mapel -->
                <div class="col-12 col-md-4">
                    <label class="form-label fw-semibold">Mata Pelajaran</label>
                    <select name="school_subject_id" id="subjectSelect" class="form-select border-0 bg-light shadow-none py-2" required>
                        <option value="">-- Pilih Mapel --</option>
                        <?php foreach ($subjects as $s): ?>
                        <option value="<?= $s['id'] ?>"><?= esc($s['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Jam ke- (rentang) -->
                <div class="col-12 col-md-3">
                    <label class="form-label fw-semibold">Jam ke-</label>
                    <div class="d-flex align-items-center gap-2">
                        <select name="start_period" class="form-select border-0 bg-light shadow-none py-2" style="width:80px;" required>
                            <?php for ($i = 1; $i <= 10; $i++): ?>
                            <option value="<?= $i ?>"><?= $i ?></option>
                            <?php endfor; ?>
                        </select>
                        <span class="text-muted">s/d</span>
                        <select name="end_period" class="form-select border-0 bg-light shadow-none py-2" style="width:80px;" required>
                            <?php for ($i = 1; $i <= 10; $i++): ?>
                            <option value="<?= $i ?>" <?= $i === 2 ? 'selected' : '' ?>><?= $i ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>
                </div>

                <!-- Materi -->
                <div class="col-12">
                    <label class="form-label fw-semibold">Materi Pokok</label>
                    <textarea name="topic" class="form-control border-0 bg-light shadow-none" rows="2"
                              placeholder="Misal: Bilangan berpangkat dan sifat-sifatnya"></textarea>
                </div>

                <!-- Catatan -->
                <div class="col-12">
                    <label class="form-label fw-semibold">Catatan / Kendala <span class="text-muted">(opsional)</span></label>
                    <textarea name="notes" class="form-control border-0 bg-light shadow-none" rows="2"
                              placeholder="Misal: Ada 2 siswa belum paham, listrik mati 10 menit"></textarea>
                </div>

            </div>

            <!-- PRESENSI -->
            <hr class="my-4">
            <h6 class="fw-bold mb-3"><i class="bi bi-people me-2 text-primary"></i>Siswa Tidak Hadir</h6>
            <p class="text-muted small mb-3">
                Centang siswa yang <strong>tidak hadir</strong> dan pilih statusnya.
                Siswa yang tidak dicentang otomatis dianggap <strong>Hadir</strong>.
            </p>

            <div class="mb-3">
                <input type="text" id="studentSearchInput" class="form-control border-0 bg-light shadow-none"
                       placeholder="Cari nama siswa..." style="max-width:300px;">
            </div>

            <div id="studentListContainer" class="p-3 bg-light rounded-3" style="max-height:400px;overflow-y:auto;">
                <p class="text-muted small mb-0">Pilih kelas terlebih dahulu untuk memuat daftar siswa.</p>
            </div>

            <!-- Tombol -->
            <div class="d-flex gap-2 mt-4">
                <button type="submit" class="btn btn-primary px-4" id="btnSubmit">
                    <i class="bi bi-check-lg me-1"></i>Simpan Jurnal
                </button>
                <a href="/guru/journal" class="btn btn-outline-secondary">Batal</a>
            </div>

        </form>
        <div id="formReport" class="mt-3"></div>
    </div>
</div>

<script>
// ── LOAD SISWA KETIKA KELAS DIPILIH ─────────────────────────
let allStudents = [];

document.getElementById('classroomSelect').addEventListener('change', function() {
    const classId = this.value;
    const container = document.getElementById('studentListContainer');

    if (classId) {
        // Load siswa
        const periodId = <?= (int)($activePeriod["id"] ?? 0) ?>;
        if (periodId) {
            fetch('/guru/journal/students?classroom_id=' + classId + '&academic_period_id=' + periodId)
                .then(r => r.json())
                .then(data => {
                    allStudents = data.students || [];
                    renderStudentList(allStudents);
                })
                .catch(() => {
                    container.innerHTML = '<p class="text-muted small mb-0">Gagal memuat data siswa.</p>';
                });
        }
    } else {
        container.innerHTML = '<p class="text-muted small mb-0">Pilih kelas terlebih dahulu.</p>';
    }
});

// ── RENDER SISWA ─────────────────────────────────────────────
function renderStudentList(students) {
    const container = document.getElementById('studentListContainer');
    if (students.length === 0) {
        container.innerHTML = '<p class="text-muted small mb-0">Tidak ada siswa di kelas ini.</p>';
        return;
    }

    container.innerHTML = students.map(s => `
        <div class="student-row d-flex align-items-center justify-content-between py-1 px-2 rounded-2 ${s._sick ? 'bg-warning bg-opacity-10' : ''}">
            <div class="d-flex align-items-center gap-2">
                <span class="small fw-medium">${s.full_name}</span>
            </div>
            <div class="d-flex align-items-center gap-1">
                <div class="form-check form-check-inline m-0">
                    <input class="form-check-input" type="radio" name="absent_${s.student_id}"
                           id="abs_hadir_${s.student_id}" value="" checked
                           onchange="toggleAbsent(${s.student_id}, '')">
                    <label class="form-check-label small" for="abs_hadir_${s.student_id}">Hadir</label>
                </div>
                <div class="form-check form-check-inline m-0">
                    <input class="form-check-input" type="radio" name="absent_${s.student_id}"
                           id="abs_s_${s.student_id}" value="Sakit"
                           onchange="toggleAbsent(${s.student_id}, 'Sakit')">
                    <label class="form-check-label small text-warning" for="abs_s_${s.student_id}">S</label>
                </div>
                <div class="form-check form-check-inline m-0">
                    <input class="form-check-input" type="radio" name="absent_${s.student_id}"
                           id="abs_i_${s.student_id}" value="Izin"
                           onchange="toggleAbsent(${s.student_id}, 'Izin')">
                    <label class="form-check-label small text-info" for="abs_i_${s.student_id}">I</label>
                </div>
                <div class="form-check form-check-inline m-0">
                    <input class="form-check-input" type="radio" name="absent_${s.student_id}"
                           id="abs_a_${s.student_id}" value="Alpha"
                           onchange="toggleAbsent(${s.student_id}, 'Alpha')">
                    <label class="form-check-label small text-danger" for="abs_a_${s.student_id}">A</label>
                </div>
            </div>
        </div>
    `).join('');
}

function toggleAbsent(studentId, status) {
    const row = document.querySelector(`.student-row`); // contextual highlight
}

// ── SEARCH SISWA ─────────────────────────────────────────────
document.getElementById('studentSearchInput').addEventListener('input', function() {
    const q = this.value.toLowerCase().trim();
    if (q === '') {
        renderStudentList(allStudents);
        return;
    }
    const filtered = allStudents.filter(s =>
        s.full_name.toLowerCase().includes(q)
    );
    renderStudentList(filtered);
});

// ── SUBMIT ───────────────────────────────────────────────────
document.getElementById('journalForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const btn = document.getElementById('btnSubmit');
    const report = document.getElementById('formReport');

    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Menyimpan...';
    report.innerHTML = '';

    // Kumpulkan absensi
    const absentees = [];
    allStudents.forEach(s => {
        const selected = document.querySelector(`input[name="absent_${s.student_id}"]:checked`);
        if (selected && selected.value !== '') {
            absentees.push({
                student_id: s.student_id,
                status: selected.value
            });
        }
    });

    const formData = new FormData(this);
    formData.append('absentees', JSON.stringify(absentees));

    fetch('/guru/journal/store', {
        method: 'POST',
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            report.innerHTML = `<div class="alert alert-success py-2 small">✅ ${data.message}</div>`;
            setTimeout(() => window.location.href = '/guru/journal', 1500);
        } else {
            report.innerHTML = `<div class="alert alert-danger py-2 small">❌ ${data.message}</div>`;
            btn.disabled = false;
            btn.innerHTML = '<i class="bi bi-check-lg me-1"></i>Simpan Jurnal';
        }
    })
    .catch(() => {
        report.innerHTML = `<div class="alert alert-danger py-2 small">❌ Gagal terhubung ke server.</div>`;
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-check-lg me-1"></i>Simpan Jurnal';
    });
});
</script>

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