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

<div class="row mb-4">
    <div class="col-md-6">
        <div class="card">
            <div class="card-body py-2 px-3">
                <div class="d-flex align-items-center gap-3">
                    <label class="form-label mb-0 fw-semibold text-nowrap">Periode Akademik:</label>
                    <select id="select_period_id" class="form-select form-select-sm">
                        <?php foreach ($periods as $p): ?>
                        <option value="<?= $p['id'] ?>" <?= ($selectedPeriod['id'] == $p['id']) ? 'selected' : '' ?>>
                            <?= esc($p['year_name']) ?> - <?= esc($p['semester']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <div class="d-flex align-items-center justify-content-between">
            <div class="d-flex align-items-center gap-2">
                <i class="bi bi-person-badge text-primary fs-5"></i>
                <span class="fw-semibold">Konfigurasi Wali Kelas</span>
            </div>
            <span class="badge bg-secondary">Periode: <?= esc($selectedPeriod['year_name']) ?> - <?= esc($selectedPeriod['semester']) ?></span>
        </div>
    </div>
    <div class="card-body">
        <?php if (session()->getFlashdata('success')): ?>
        <div class="alert alert-success alert-dismissible fade show py-2 small" role="alert">
            <i class="bi bi-check-circle me-1"></i><?= session()->getFlashdata('success') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <?php if (session()->getFlashdata('error')): ?>
        <div class="alert alert-danger alert-dismissible fade show py-2 small" role="alert">
            <i class="bi bi-exclamation-circle me-1"></i><?= session()->getFlashdata('error') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>

        <form action="/homeroom-assignment/save" method="post" id="formHomeroom">
            <?= csrf_field() ?>
            <input type="hidden" name="academic_period_id" value="<?= $selectedPeriod['id'] ?>">

            <div class="table-responsive">
                <table class="table table-hover table-bordered table-sm align-middle" id="tableHomeroom">
                    <thead class="table-light">
                        <tr>
                            <th width="50" class="text-center">#</th>
                            <th width="120">Tingkat</th>
                            <th>Nama Kelas</th>
                            <th width="450">Wali Kelas</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($classrooms)): ?>
                        <tr>
                            <td colspan="4" class="text-center text-muted py-4">Belum ada data kelas.</td>
                        </tr>
                        <?php else: ?>
                            <?php $no = 1; foreach ($classrooms as $c): ?>
                            <tr>
                                <td class="text-center"><?= $no++ ?></td>
                                <td>
                                    <span class="badge bg-light text-dark border"><?= esc($c['grade_name']) ?></span>
                                </td>
                                <td><strong><?= esc($c['name']) ?></strong></td>
                                <td>
                                    <select name="wali_kelas[<?= $c['id'] ?>]" class="form-select form-select-sm select-teacher-wali">
                                        <option value="">-- Tanpa Wali Kelas --</option>
                                        <?php foreach ($teachers as $t): ?>
                                            <?php 
                                                $selected = isset($assignedMap[$c['id']]) && $assignedMap[$c['id']] == $t['id'] ? 'selected' : '';
                                            ?>
                                            <option value="<?= $t['id'] ?>" <?= $selected ?>>
                                                <?= esc($t['name']) ?> (<?= esc(teacher_id_display($t)) ?>)
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <div class="mt-3 d-flex justify-content-end">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-save me-2"></i>Simpan Konfigurasi Wali Kelas
                </button>
            </div>
        </form>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<!-- Load Select2 CDN -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
$(document).ready(function() {
    // Inisialisasi Select2
    $('.select-teacher-wali').select2({
        theme: 'bootstrap-5',
        placeholder: "-- Pilih Wali Kelas --",
        allowClear: true,
        width: '100%'
    });

    // Pindah periode
    $('#select_period_id').change(function() {
        const periodId = $(this).val();
        window.location.href = '/homeroom-assignment?period_id=' + periodId;
    });

    // Peringatan jika satu guru dipilih di lebih dari satu kelas
    $('#formHomeroom').submit(function(e) {
        let selectedTeachers = {};
        let duplicateFound = false;
        let duplicateName = "";

        $('.select-teacher-wali').each(function() {
            const val = $(this).val();
            if (val) {
                if (selectedTeachers[val]) {
                    duplicateFound = true;
                    duplicateName = $(this).find('option:selected').text().trim();
                    return false; // break loop
                }
                selectedTeachers[val] = true;
            }
        });

        if (duplicateFound) {
            if (!confirm(`Peringatan: Guru "${duplicateName}" dipilih sebagai Wali Kelas di lebih dari satu kelas. Apakah Anda ingin tetap melanjutkan?`)) {
                e.preventDefault();
                return false;
            }
        }
    });
});
</script>
<?= $this->endSection() ?>
