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

<div class="card">
    <div class="card-header d-flex align-items-center justify-content-between flex-wrap gap-2">
        <div class="d-flex align-items-center gap-2">
            <i class="bi bi-person-workspace text-primary"></i>
            <span class="fw-semibold">Setting Mengajar Guru</span>
            <span class="badge bg-secondary"><?= count($assignments) ?></span>
        </div>
        <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#modalAdd">
            <i class="bi bi-plus-circle me-1"></i>Tambah Assignment
        </button>
    </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; ?>

        <div class="table-responsive">
            <table class="table table-hover table-sm" id="dataTable">
                <thead class="table-light">
                    <tr>
                        <th width="50">#</th>
                        <th>Guru</th>
                        <th>Kelas</th>
                        <th>Mata Pelajaran</th>
                        <th>Tipe</th>
                        <th>Periode</th>
                        <th width="80">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($assignments)): ?>
                    <tr class="text-center">
                        <td colspan="7" class="text-muted py-5">
                            <i class="bi bi-inbox fs-2 d-block mb-2 opacity-25"></i>
                            <small>Belum ada data assignment</small>
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($assignments as $i => $a): ?>
                        <tr>
                            <td class="text-center"><?= $i + 1 ?></td>
                            <td>
                                <?= esc($a['teacher_name']) ?>
                                <?php if (!empty($a['nip'])): ?>
                                <br><small class="text-muted"><?= teacher_id_label($a['status_kepegawaian'] ?? null) ?>: <?= esc(teacher_id_display($a)) ?></small>
                                <?php endif; ?>
                            </td>
                            <td><?= esc($a['classroom_name']) ?> (<?= esc($a['grade_name']) ?>)</td>
                            <td>
                                <?php if ($a['assignment_type'] == 'bk'): ?>
                                    <span class="badge bg-info">BK (Bimbingan Konseling)</span>
                                <?php else: ?>
                                    <?= esc($a['subject_name'] ?? '-') ?>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($a['assignment_type'] == 'bk'): ?>
                                    <span class="badge bg-success">Guru BK</span>
                                <?php else: ?>
                                    <span class="badge bg-primary">Guru Mapel</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <small><?= esc($a['semester']) ?> - <?= esc($a['year_name']) ?></small>
                            </td>
                            <td>
                                <a href="/assignment/delete/<?= $a['id'] ?>" 
                                    class="btn btn-sm btn-outline-danger"
                                    onclick="return confirm('Hapus assignment ini?')">
                                    <i class="bi bi-trash"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modal Add Assignment -->
<div class="modal fade" id="modalAdd" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="/assignment/store" method="post">
                <?= csrf_field() ?>
                <div class="modal-header">
                    <h6 class="modal-title fw-semibold">
                        <i class="bi bi-plus-circle me-2 text-primary"></i>Tambah Assignment
                    </h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-info py-2 small mb-3">
                        <i class="bi bi-building me-1"></i>
                        Jenjang Sekolah: <strong><?= esc($school_type) ?></strong><br>
                        <i class="bi bi-book me-1"></i>
                        Mata pelajaran yang tampil hanya untuk jenjang <strong><?= esc($school_type) ?></strong> (dan mapel umum)
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Pilih Guru <span class="text-danger">*</span></label>
                        <select name="teacher_id" class="form-select" required>
                            <option value="">-- Pilih Guru --</option>
                            <?php foreach ($teachers as $t): ?>
                            <option value="<?= $t['id'] ?>"><?= esc($t['name']) ?> (<?= esc($t['nip'] ?? '-') ?>)</option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Pilih Kelas <span class="text-danger">*</span></label>
                        <select name="classroom_id" class="form-select" required>
                            <option value="">-- Pilih Kelas --</option>
                            <?php foreach ($classrooms as $c): ?>
                            <option value="<?= $c['id'] ?>"><?= esc($c['grade_name']) ?> - <?= esc($c['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Periode Akademik <span class="text-danger">*</span></label>
                        <select name="academic_period_id" class="form-select" required>
                            <option value="">-- Pilih Periode --</option>
                            <?php foreach ($periods as $p): ?>
                            <option value="<?= $p['id'] ?>" <?= ($activePeriod && $activePeriod['id'] == $p['id']) ? 'selected' : '' ?>>
                                <?= esc($p['year_name']) ?> - <?= esc($p['semester']) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Tipe Assignment <span class="text-danger">*</span></label>
                        <select name="assignment_type" id="assignmentType" class="form-select" required onchange="toggleSubject()">
                            <option value="">-- Pilih Tipe --</option>
                            <option value="bk">Guru BK (Bimbingan Konseling)</option>
                            <option value="subject_teacher">Guru Mata Pelajaran</option>
                        </select>
                    </div>
                    <div class="mb-3" id="subjectField" style="display:none">
                        <label class="form-label">Mata Pelajaran <span class="text-danger">*</span></label>
                        <select name="subject_id" class="form-select">
                            <option value="">-- Pilih Mata Pelajaran --</option>
                            <?php foreach ($subjects as $s): ?>
                            <option value="<?= $s['id'] ?>"><?= esc($s['name']) ?> 
                                <?php if ($s['level'] != 'ALL'): ?>
                                (<?= esc($s['level']) ?>)
                                <?php endif; ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="form-text text-muted small">
                            <i class="bi bi-info-circle"></i> 
                            Hanya menampilkan mapel untuk jenjang <?= esc($school_type) ?> + mapel umum (Semua)
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary btn-sm">Simpan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function toggleSubject() {
    const type = document.getElementById('assignmentType').value;
    const subjectField = document.getElementById('subjectField');
    if (type === 'subject_teacher') {
        subjectField.style.display = 'block';
        document.querySelector('select[name="subject_id"]').required = true;
    } else {
        subjectField.style.display = 'none';
        document.querySelector('select[name="subject_id"]').required = false;
    }
}
</script>

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

<?= $this->section('scripts') ?>
<script>
$(document).ready(function() {
    // Hancurkan instance DataTable jika sudah ada
    if ($.fn.DataTable.isDataTable('#dataTable')) {
        $('#dataTable').DataTable().destroy();
    }
    
    // Inisialisasi DataTable dengan language inline (tanpa CORS)
    $('#dataTable').DataTable({
        language: {
            "decimal": ",",
            "emptyTable": "Tidak ada data assignment",
            "info": "Menampilkan _START_ sampai _END_ dari _TOTAL_ data",
            "infoEmpty": "Menampilkan 0 sampai 0 dari 0 data",
            "infoFiltered": "(difilter dari _MAX_ total data)",
            "infoPostFix": "",
            "thousands": ".",
            "lengthMenu": "Tampilkan _MENU_ data",
            "loadingRecords": "Memuat...",
            "processing": "Memproses...",
            "search": "Cari:",
            "zeroRecords": "Tidak ditemukan data yang cocok",
            "paginate": {
                "first": "Pertama",
                "last": "Terakhir",
                "next": "›",
                "previous": "‹"
            },
            "aria": {
                "sortAscending": ": aktifkan untuk mengurutkan kolom ascending",
                "sortDescending": ": aktifkan untuk mengurutkan kolom descending"
            }
        },
        pageLength: 25,
        order: [[0, 'asc']],
        columnDefs: [
            { orderable: false, targets: [6] } // Kolom Aksi tidak bisa di-sort
        ]
    });
});
</script>
<?= $this->endSection() ?>