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

<div class="row justify-content-center">
    <div class="col-12 col-xl-10">
        <div class="card border-0 shadow-sm rounded-4 overflow-hidden mb-4">
            <div class="card-header bg-primary bg-gradient py-3 px-4 d-flex align-items-center gap-2">
                <i class="bi bi-printer-fill text-white fs-4"></i>
                <div>
                    <h5 class="card-title text-white fw-bold mb-0">Hub Cetak Administrasi Kelas</h5>
                    <p class="text-white text-opacity-75 small mb-0">Cetak berbagai kebutuhan administrasi dan presensi kelas secara mandiri atau massal</p>
                </div>
            </div>
            <div class="card-body p-4">
                
                <?php if ($activePeriod): ?>
                <div class="alert alert-info border-0 bg-info bg-opacity-10 d-flex align-items-center gap-2 py-2.5 px-3 mb-4 rounded-3 text-info">
                    <i class="bi bi-calendar-check-fill fs-5"></i>
                    <div>
                        Periode Aktif saat ini: <strong class="text-dark"><?= esc($activePeriod['year_name']) ?> — Sem. <?= esc($activePeriod['semester']) ?></strong>
                    </div>
                </div>
                <?php else: ?>
                <div class="alert alert-danger border-0 bg-danger bg-opacity-10 d-flex align-items-center gap-2 py-2.5 px-3 mb-4 rounded-3 text-danger">
                    <i class="bi bi-exclamation-triangle-fill fs-5"></i>
                    <div>
                        Belum ada periode akademik aktif! Silakan aktifkan periode akademik terlebih dahulu.
                    </div>
                </div>
                <?php endif; ?>

                <!-- SELEKSI KELAS UTAMA -->
                <div class="row g-3 mb-4 p-3 bg-light rounded-3 border">
                    <div class="col-md-6">
                        <label class="form-label fw-semibold text-secondary">Tingkat Kelas</label>
                        <select id="filterGrade" class="form-select border-0 shadow-sm py-2">
                            <option value="">-- Pilih Tingkat --</option>
                            <?php foreach ($grades as $grade): ?>
                            <option value="<?= $grade['id'] ?>"><?= esc($grade['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label fw-semibold text-secondary">Kelas <span class="text-danger">*</span></label>
                        <select id="filterClassroom" class="form-select border-0 shadow-sm py-2" disabled>
                            <option value="">-- Pilih Tingkat Dulu --</option>
                        </select>
                    </div>
                </div>

                <!-- PILIHAN TIPE DOKUMEN (TABS) -->
                <div class="mb-4">
                    <label class="form-label fw-bold text-dark mb-2 fs-6">Pilih Jenis Dokumen:</label>
                    <ul class="nav nav-pills nav-fill bg-light p-1 rounded-3 border" id="documentTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active py-2.5 d-flex align-items-center justify-content-center gap-2" id="tab-bulanan" data-bs-toggle="pill" data-bs-target="#panel-bulanan" type="button" role="tab" aria-selected="true">
                                <i class="bi bi-calendar-check fs-5"></i> Presensi Bulanan
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link py-2.5 d-flex align-items-center justify-content-center gap-2" id="tab-guru" data-bs-toggle="pill" data-bs-target="#panel-guru" type="button" role="tab" aria-selected="false">
                                <i class="bi bi-person-workspace fs-5"></i> Presensi Guru
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link py-2.5 d-flex align-items-center justify-content-center gap-2" id="tab-nilai" data-bs-toggle="pill" data-bs-target="#panel-nilai" type="button" role="tab" aria-selected="false">
                                <i class="bi bi-journal-text fs-5"></i> Daftar Nilai
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link py-2.5 d-flex align-items-center justify-content-center gap-2" id="tab-portrait" data-bs-toggle="pill" data-bs-target="#panel-portrait" type="button" role="tab" aria-selected="false">
                                <i class="bi bi-file-earmark-text fs-5"></i> Hadir Portrait
                            </button>
                        </li>
                    </ul>
                </div>

                <!-- PANEL PENGATURAN DINAMIS -->
                <div class="tab-content border rounded-3 p-4 bg-white shadow-xs" id="documentPanels">
                    
                    <!-- TAB 1: PRESENSI BULANAN -->
                    <div class="tab-pane fade show active" id="panel-bulanan" role="tabpanel" aria-labelledby="tab-bulanan">
                        <h6 class="fw-bold text-primary mb-3">Pengaturan Presensi Bulanan Kelas (Landscape F4)</h6>
                        <p class="text-muted small">Mencetak rekap presensi kelas format mendatar dengan arsiran otomatis pada kolom hari Minggu.</p>
                        <div class="row g-3 mt-1">
                            <div class="col-md-6">
                                <label class="form-label fw-semibold text-secondary">Bulan</label>
                                <select id="bulananMonth" class="form-select border-grey">
                                    <?php foreach ($months as $num => $name): ?>
                                    <option value="<?= $num ?>" <?= $num == date('n') ? 'selected' : '' ?>>
                                        <?= $name ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-semibold text-secondary">Tahun</label>
                                <select id="bulananYear" class="form-select border-grey">
                                    <?php
                                    $currentYear = (int) date('Y');
                                    for ($y = $currentYear - 1; $y <= $currentYear + 1; $y++): ?>
                                    <option value="<?= $y ?>" <?= $y == $currentYear ? 'selected' : '' ?>><?= $y ?></option>
                                    <?php endfor; ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- TAB 2: PRESENSI GURU -->
                    <div class="tab-pane fade" id="panel-guru" role="tabpanel" aria-labelledby="tab-guru">
                        <h6 class="fw-bold text-primary mb-3">Pengaturan Presensi Pertemuan Guru (Landscape F4)</h6>
                        <p class="text-muted small">Format mendatar berisi kolom pertemuan 1-20 untuk guru pengampu mencatat kehadiran per tatap muka.</p>
                        
                        <div class="form-check form-switch mb-3 mt-2 bg-light p-2.5 rounded border-start border-primary border-3 ps-5">
                            <input class="form-check-input" type="checkbox" id="guruUniversal" checked>
                            <label class="form-check-label fw-semibold text-dark" for="guruUniversal">
                                Universal untuk Fotokopi (Kosongkan Nama Mapel & Guru)
                            </label>
                            <div class="text-muted small">Sangat disarankan: Cukup cetak 1 per kelas lalu fotokopi sebanyak jumlah mapel untuk menghemat waktu dan kertas.</div>
                        </div>

                        <div id="guruSpecPanel" class="row g-3 d-none">
                            <div class="col-md-6">
                                <label class="form-label fw-semibold text-secondary">Mata Pelajaran</label>
                                <select id="guruSubject" class="form-select">
                                    <option value="">-- Pilih Mata Pelajaran --</option>
                                    <?php foreach ($subjects as $subject): ?>
                                    <option value="<?= $subject['id'] ?>"><?= esc($subject['name']) ?> (<?= esc($subject['code']) ?>)</option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-semibold text-secondary">Nama Guru Pengampu</label>
                                <select id="guruTeacher" class="form-select">
                                    <option value="">-- Pilih Guru --</option>
                                    <?php foreach ($teachers as $teacher): ?>
                                    <option value="<?= $teacher['id'] ?>"><?= esc($teacher['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- TAB 3: DAFTAR NILAI -->
                    <div class="tab-pane fade" id="panel-nilai" role="tabpanel" aria-labelledby="tab-nilai">
                        <h6 class="fw-bold text-primary mb-3">Pengaturan Daftar Nilai Guru (Landscape F4)</h6>
                        <p class="text-muted small">Format mendatar untuk rekap nilai fisik guru, mencakup kolom Asesmen Sumatif Harian (ASH 1-8), ASTS, ASAS, dan Rerata.</p>
                        
                        <div class="form-check form-switch mb-3 mt-2 bg-light p-2.5 rounded border-start border-primary border-3 ps-5">
                            <input class="form-check-input" type="checkbox" id="nilaiUniversal" checked>
                            <label class="form-check-label fw-semibold text-dark" for="nilaiUniversal">
                                Universal untuk Fotokopi (Kosongkan Nama Mapel & Guru)
                            </label>
                            <div class="text-muted small">Sangat disarankan: Cukup cetak 1 per kelas lalu fotokopi sebanyak jumlah mapel untuk menghemat waktu dan kertas.</div>
                        </div>

                        <div id="nilaiSpecPanel" class="row g-3 d-none">
                            <div class="col-md-6">
                                <label class="form-label fw-semibold text-secondary">Mata Pelajaran</label>
                                <select id="nilaiSubject" class="form-select">
                                    <option value="">-- Pilih Mata Pelajaran --</option>
                                    <?php foreach ($subjects as $subject): ?>
                                    <option value="<?= $subject['id'] ?>"><?= esc($subject['name']) ?> (<?= esc($subject['code']) ?>)</option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-semibold text-secondary">Nama Guru Pengampu</label>
                                <select id="nilaiTeacher" class="form-select">
                                    <option value="">-- Pilih Guru --</option>
                                    <?php foreach ($teachers as $teacher): ?>
                                    <option value="<?= $teacher['id'] ?>"><?= esc($teacher['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- TAB 4: HADIR PORTRAIT -->
                    <div class="tab-pane fade" id="panel-portrait" role="tabpanel" aria-labelledby="tab-portrait">
                        <h6 class="fw-bold text-primary mb-3">Pengaturan Daftar Hadir Kegiatan (Portrait A4)</h6>
                        <p class="text-muted small">Cetak lembar kehadiran tegak (Portrait) pada kertas A4 dengan kolom tanda tangan zigzag. Judul dan tanggal tanda tangan kustom.</p>
                        
                        <div class="row g-3 mt-1">
                            <div class="col-12">
                                <label class="form-label fw-semibold text-secondary">Judul Kegiatan / Daftar Hadir <span class="text-danger">*</span></label>
                                <input type="text" id="portTitle" class="form-control" value="Daftar Hadir Masa Ta'aruf Siswa Madrasah" placeholder="Misal: Daftar Hadir Ujian Madrasah, Daftar Hadir Pertemuan Wali Murid">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-semibold text-secondary">Subjudul / Instansi</label>
                                <input type="text" id="portSubtitle" class="form-control" value="<?= esc($school['school_name'] ?? 'MTsN 1 Wonogiri') ?> Tahun Ajaran <?= esc($activePeriod['year_name'] ?? '') ?>" placeholder="Misal: MTsN 1 Wonogiri Tahun Ajaran 2026/2027">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-semibold text-secondary">Tanggal Tanda Tangan (Dinamis)</label>
                                <input type="text" id="portDate" class="form-control" value="<?= esc($school['city'] ?? 'Wonogiri') ?>, ..... .................... <?= date('Y') ?>" placeholder="Contoh: Wonogiri, 15 Juli 2026">
                            </div>
                        </div>
                    </div>

                </div>

                <!-- BUTTON CETAK -->
                <div class="mt-4 pt-3 border-top d-flex align-items-center justify-content-between">
                    <div>
                        <span class="text-muted small text-start d-block">
                            <i class="bi bi-info-circle me-1"></i>
                            Kertas disarankan: <strong>Folio/F4</strong> untuk Landscape, <strong>A4</strong> untuk Portrait.
                        </span>
                    </div>
                    <button class="btn btn-primary px-5 py-2 fw-semibold shadow-sm rounded-3" id="btnPreview">
                        <i class="bi bi-printer-fill me-2"></i>Preview & Cetak
                    </button>
                </div>

            </div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
const allClassrooms = [
    <?php foreach ($classrooms as $c): ?>
    { id: '<?= $c['id'] ?>', gradeId: '<?= $c['grade_id'] ?>', name: '<?= esc($c['name']) ?>' },
    <?php endforeach; ?>
];

// Switch layout input Mapel/Guru di Tab 2
$('#guruUniversal').on('change', function() {
    if (this.checked) {
        $('#guruSpecPanel').addClass('d-none');
    } else {
        $('#guruSpecPanel').removeClass('d-none');
    }
});

// Switch layout input Mapel/Guru di Tab 3
$('#nilaiUniversal').on('change', function() {
    if (this.checked) {
        $('#nilaiSpecPanel').addClass('d-none');
    } else {
        $('#nilaiSpecPanel').removeClass('d-none');
    }
});

// Penanganan Dropdown Kelas dinamis berdasarkan tingkat
$('#filterGrade').on('change', function() {
    const gradeId = this.value;
    const sel = document.getElementById('filterClassroom');
    sel.innerHTML = '<option value="">-- Pilih Kelas --</option>';
    if (gradeId) {
        sel.appendChild(new Option('-- Semua Kelas --', 'all'));
    }
    allClassrooms
        .filter(c => !gradeId || c.gradeId === gradeId)
        .forEach(c => sel.appendChild(new Option(c.name, c.id)));
    sel.disabled = !gradeId;
});

// Tombol Preview & Cetak
$('#btnPreview').on('click', function() {
    const gradeId = $('#filterGrade').val();
    const classroomId = $('#filterClassroom').val();

    if (!gradeId) {
        Swal.fire('Perhatian', 'Pilih tingkat kelas terlebih dahulu!', 'warning');
        return;
    }
    if (!classroomId) {
        Swal.fire('Perhatian', 'Pilih kelas terlebih dahulu!', 'warning');
        return;
    }

    // Tentukan Tab yang aktif
    const activeTab = $('#documentTabs button.active').attr('id');
    let type = 'bulanan';
    let query = `?classroom_id=${classroomId}&grade_id=${gradeId}`;

    if (activeTab === 'tab-bulanan') {
        type = 'bulanan';
        const m = $('#bulananMonth').val();
        const y = $('#bulananYear').val();
        query += `&type=bulanan&month=${m}&year=${y}`;
    } else if (activeTab === 'tab-guru') {
        type = 'guru';
        query += `&type=guru`;
        const isUniversal = $('#guruUniversal').is(':checked');
        if (!isUniversal) {
            const subject = $('#guruSubject').val();
            const teacher = $('#guruTeacher').val();
            if (subject) query += `&subject_id=${subject}`;
            if (teacher) query += `&teacher_id=${teacher}`;
        }
    } else if (activeTab === 'tab-nilai') {
        type = 'nilai';
        query += `&type=nilai`;
        const isUniversal = $('#nilaiUniversal').is(':checked');
        if (!isUniversal) {
            const subject = $('#nilaiSubject').val();
            const teacher = $('#nilaiTeacher').val();
            if (subject) query += `&subject_id=${subject}`;
            if (teacher) query += `&teacher_id=${teacher}`;
        }
    } else if (activeTab === 'tab-portrait') {
        type = 'portrait';
        const title = encodeURIComponent($('#portTitle').val());
        const subtitle = encodeURIComponent($('#portSubtitle').val());
        const customDate = encodeURIComponent($('#portDate').val());
        query += `&type=portrait&activity_title=${title}&activity_subtitle=${subtitle}&custom_date=${customDate}`;
    }

    const url = `/attendance-sheet/print${query}`;
    window.open(url, '_blank');
});
</script>
<?= $this->endSection() ?>