<?= $this->extend('layout/default') ?>

<?= $this->section('content') ?>
<div class="content-header">
    <div class="header-title">
        <h2>Data Kelas Perkuliahan</h2>
        <p>Kelola data kelas perkuliahan program studi</p>
    </div>
    <div class="header-actions">
        <a href="<?= base_url('kelas-perkuliahan/create') ?>" class="btn btn-success">
            <i class="fas fa-plus"></i> Tambah Kelas Baru
        </a>
        <a href="<?= base_url('kelas-perkuliahan/sync') ?>" class="btn btn-primary" onclick="return confirm('Proses sinkronisasi ini menarik SELURUH data kelas dan dosen pengajar dari SEMUA semester. Waktu tunggu mungkin cukup lama. Lanjutkan?')">
            <i class="fas fa-sync-alt"></i> Sinkronisasi PDDIKTI
        </a>
    </div>
</div>

<?php if (session()->getFlashdata('pesan')) : ?>
    <div class="alert alert-success">
        <?= session()->getFlashdata('pesan') ?>
    </div>
<?php endif; ?>
<?php if (session()->getFlashdata('error')) : ?>
    <div class="alert alert-danger">
        <?= session()->getFlashdata('error') ?>
    </div>
<?php endif; ?>

<?php
// Fungsi helper untuk memformat periode
if (!function_exists('formatPeriode')) {
    function formatPeriode($periode) {
        if (strlen($periode) == 5) {
            $tahun = substr($periode, 0, 4);
            $semester = substr($periode, 4, 1);
            $tahun_berikutnya = (int)$tahun + 1;
            
            $nama_semester = '';
            if ($semester == '1') {
                $nama_semester = 'Ganjil';
            } elseif ($semester == '2') {
                $nama_semester = 'Genap';
            } elseif ($semester == '3') {
                $nama_semester = 'Pendek';
            } else {
                $nama_semester = $semester;
            }
            
            return $tahun . '/' . $tahun_berikutnya . ' ' . $nama_semester;
        }
        return $periode;
    }
}
?>

<div class="filter-section" style="background: white; padding: 1rem; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-bottom: 1.5rem;">
    <form action="" method="GET" class="filter-form">
        <table class="table table-bordered" style="margin-bottom: 1rem;">
            <tbody>
                <tr>
                    <td style="width: 15%; background-color: #f8f9fa; vertical-align: middle;"><strong>Program Studi</strong></td>
                    <td style="width: 35%;">
                        <select name="prodi" id="prodi" class="form-control">
                            <option value="">-- Semua Program Studi --</option>
                            <?php foreach ($list_prodi as $p) : ?>
                                <option value="<?= $p['id'] ?>" <?= (isset($_GET['prodi']) && $_GET['prodi'] == $p['id']) ? 'selected' : '' ?>>
                                    <?= esc($p['nama_prodi']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td style="width: 15%; background-color: #f8f9fa; vertical-align: middle;"><strong>Periode</strong></td>
                    <td style="width: 35%;">
                        <select name="periode" id="periode" class="form-control">
                            <option value="">-- Semua Periode --</option>
                            <?php foreach ($list_periode as $pr) : ?>
                                <option value="<?= $pr['id_semester'] ?>" <?= (isset($_GET['periode']) && $_GET['periode'] == $pr['id_semester']) ? 'selected' : '' ?>>
                                    <?= esc(formatPeriode($pr['id_semester'])) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td style="background-color: #f8f9fa; vertical-align: middle;"><strong>Kurikulum</strong></td>
                    <td>
                        <select name="kurikulum" id="kurikulum" class="form-control">
                            <option value="">-- Semua Kurikulum --</option>
                            <?php foreach ($list_kurikulum as $kr) : ?>
                                <option value="<?= $kr['id'] ?>" data-prodi="<?= esc($kr['id_program_studi']) ?>" <?= (isset($_GET['kurikulum']) && $_GET['kurikulum'] == $kr['id']) ? 'selected' : '' ?>>
                                    <?= esc($kr['nama_kurikulum']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </td>
                    <td style="background-color: #f8f9fa; vertical-align: middle;"><strong>Semester</strong></td>
                    <td>
                        <select name="semester" id="semester" class="form-control">
                            <option value="">-- Semua Semester --</option>
                            <?php for($i=1; $i<=8; $i++): ?>
                                <option value="<?= $i ?>" <?= (isset($_GET['semester']) && $_GET['semester'] == $i) ? 'selected' : '' ?>><?= $i ?></option>
                            <?php endfor; ?>
                        </select>
                    </td>
                </tr>
            </tbody>
        </table>
        
        <div style="display: flex; gap: 1rem; align-items: flex-end;">
            <div class="form-group" style="flex: 1; min-width: 200px; margin-bottom: 0;">
                <label for="search" style="font-weight: bold;">Pencarian (Mata Kuliah / Nama Kelas)</label>
                <input type="text" name="search" id="search" class="form-control" placeholder="Ketik kata kunci..." value="<?= htmlspecialchars($_GET['search'] ?? '') ?>">
            </div>
            <div class="form-group" style="flex: 0 0 100px; margin-bottom: 0;">
                <label for="per_page" style="font-weight: bold;">Tampilkan</label>
                <select name="per_page" id="per_page" class="form-control">
                    <option value="10" <?= (isset($per_page) && $per_page == 10) ? 'selected' : '' ?>>10</option>
                    <option value="25" <?= (isset($per_page) && $per_page == 25) ? 'selected' : '' ?>>25</option>
                    <option value="50" <?= (isset($per_page) && $per_page == 50) ? 'selected' : '' ?>>50</option>
                    <option value="100" <?= (isset($per_page) && $per_page == 100) ? 'selected' : '' ?>>100</option>
                </select>
            </div>
            <div class="form-actions" style="margin-bottom: 0;">
                <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Filter</button>
                <a href="<?= base_url('kelas-perkuliahan') ?>" class="btn btn-secondary"><i class="fas fa-undo"></i> Reset</a>
            </div>
        </div>
    </form>
</div>

<div class="card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Semester</th>
                        <th>Mata Kuliah</th>
                        <th>Nama Kelas</th>
                        <th>Program Studi</th>
                        <th>Dosen Pengajar</th>
                        <th>Mhs</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($kelas)) : ?>
                        <tr>
                            <td colspan="7" class="text-center">Tidak ada data kelas. Silakan lakukan sinkronisasi.</td>
                        </tr>
                    <?php else : ?>
                        <?php 
                        $page = isset($_GET['page_kelas_perkuliahan']) ? $_GET['page_kelas_perkuliahan'] : 1;
                        $no = ($page - 1) * $per_page + 1;
                        foreach ($kelas as $k) : 
                        ?>
                            <tr>
                                <td><?= $no++ ?></td>
                                <td><span class="badge badge-secondary" style="background-color: #64748b; color: white; padding: 4px 8px; border-radius: 4px;"><?= esc(formatPeriode($k['id_semester'])) ?></span></td>
                                <td>
                                    <strong><?= esc($k['nama_mata_kuliah']) ?></strong><br>
                                    <small class="text-muted">SKS: <?= esc($k['sks_asli'] ?? $k['sks']) ?></small>
                                </td>
                                <td><span class="badge badge-info" style="background-color: #3b82f6; color: white; padding: 4px 8px; border-radius: 4px;"><?= esc($k['nama_kelas_kuliah']) ?></span></td>
                                <td><?= esc($k['nama_prodi'] ?? '-') ?></td>
                                <td>
                                    <div style="max-height: 80px; overflow-y: auto; font-size: 0.9em;">
                                        <?= esc($k['dosen_pengajar']) ?>
                                    </div>
                                </td>
                                <td class="py-3 px-4 border-b text-center">
                                    <div class="btn-group" role="group">
                                        <a href="<?= base_url('kelas-perkuliahan/dosen/' . $k['id_kelas_kuliah_pddikti']) ?>" class="btn btn-sm btn-info" title="Kelola Dosen Pengajar" style="color: white; background-color: #0dcaf0; border-color: #0dcaf0;">
                                            <i class="fas fa-chalkboard-teacher"></i> Dosen
                                        </a>
                                        <a href="<?= base_url('kelas-perkuliahan/peserta/' . $k['id_kelas_kuliah_pddikti']) ?>" class="btn btn-sm btn-success" title="Kelola Mahasiswa (KRS)" style="background-color: #10b981; border-color: #10b981;">
                                            <i class="fas fa-users"></i> MHS (<?= esc($k['jumlah_mahasiswa']) ?>)
                                        </a>
                                        <a href="<?= base_url('kelas-perkuliahan/edit/' . $k['id_kelas_kuliah_pddikti']) ?>" class="btn btn-sm btn-warning" title="Edit Kelas">
                                            <i class="fas fa-edit"></i> Edit
                                        </a>
                                        <a href="<?= base_url('kelas-perkuliahan/delete/' . $k['id_kelas_kuliah_pddikti']) ?>" class="btn btn-sm btn-danger" title="Hapus Kelas" onclick="return confirm('Apakah Anda yakin ingin menghapus kelas ini? Penghapusan ini akan menghapus peserta KRS dan Penugasan Dosen di dalamnya secara otomatis.');">
                                            <i class="fas fa-trash"></i> Hapus
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
                <?php if (!empty($kelas)) : ?>
                <tfoot>
                    <tr style="background-color: #f8fafc;">
                        <th colspan="2" class="text-right" style="vertical-align: middle; padding-right: 1.5rem;"><strong>Total SKS:</strong></th>
                        <th colspan="5">
                            <span class="badge badge-success" style="background-color: #10b981; color: white; padding: 6px 12px; border-radius: 4px; font-size: 14px;">
                                <?= esc($total_sks) ?> SKS
                            </span>
                        </th>
                    </tr>
                </tfoot>
                <?php endif; ?>
            </table>
        </div>
        
        <div class="pagination-container" style="padding: 1.5rem; border-top: 1px solid #e2e8f0; background: #f8fafc;">
            <?= $pager->links('kelas_perkuliahan', 'custom_pagination') ?>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const prodiSelect = document.getElementById('prodi');
    const kurikulumSelect = document.getElementById('kurikulum');
    
    // Simpan semua options asli ke dalam memori
    const allOptions = Array.from(kurikulumSelect.querySelectorAll('option'));
    const defaultOption = allOptions[0]; // Option "-- Semua Kurikulum --"

    function filterKurikulum() {
        const selectedProdi = prodiSelect.value;
        const currentSelectedKurikulum = kurikulumSelect.value;
        
        // Kosongkan select box
        kurikulumSelect.innerHTML = '';
        
        // Tambahkan opsi default
        kurikulumSelect.appendChild(defaultOption.cloneNode(true));
        
        let isCurrentValueValid = false;
        
        // Filter dan masukkan opsi yang cocok
        allOptions.forEach((option, index) => {
            if (index === 0) return; // Skip default option
            
            if (selectedProdi === "" || option.dataset.prodi === selectedProdi) {
                const newOption = option.cloneNode(true);
                kurikulumSelect.appendChild(newOption);
                
                if (newOption.value === currentSelectedKurikulum) {
                    newOption.selected = true;
                    isCurrentValueValid = true;
                }
            }
        });

        // Reset if invalid
        if (!isCurrentValueValid) {
            kurikulumSelect.value = "";
        }
    }

    // Run on initial load
    filterKurikulum();

    // Run on change
    prodiSelect.addEventListener('change', filterKurikulum);
});
</script>
<?= $this->endSection() ?>
