<div class="container mt-4">
    <div class="card modern-card shadow-sm border-0 rounded-4">
        <div class="card-body p-4">

            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="mb-0">Data Kelas</h5>
                <div>
                    <?php if(check_permission('kelas', 'can_create')): ?>
                    <button class="btn btn-success btn-add" style="margin-right: 5px;">
                        <i class="bi bi-plus-circle me-1"></i> Tambah Kelas
                    </button>
                    <?php endif; ?>
                </div>
            </div>

            <div class="table-responsive">
                <table id="tableKelas" class="table modern-table align-middle w-100">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Nama Kelas</th>
                            <th>Gedung</th>
                            <th>Wali Kelas</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>

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

<!-- MODAL TAMBAH / EDIT KELAS -->
<div class="modal fade" id="modalKelas">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content rounded-4">
            <div class="modal-header bg-success text-white rounded-top-4">
                <h5 class="modal-title">Tambah Kelas</h5>
                <button class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="inputId">
                <label class="fw-semibold mt-2">Nama Kelas</label>
                <input type="text" class="form-control" id="inputNama" placeholder="Masukkan nama kelas">

                <label class="fw-semibold mt-2">Gedung</label>
                <input type="text" class="form-control" id="inputGedung" placeholder="Masukkan nama gedung">

                <label class="fw-semibold mt-2">Nama Wali Kelas</label>
                <input type="text" class="form-control" id="inputWaliKelas" placeholder="Masukkan nama wali kelas">
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                <button class="btn btn-success" id="btnSimpanKelas">Simpan</button>
            </div>
        </div>
    </div>
</div>

<!-- MODAL DETAIL KELAS -->
<div class="modal fade" id="modalDetailKelas">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content rounded-4 shadow">
            <div class="modal-header bg-primary text-white rounded-top-4">
                <h5 class="modal-title">Detail Kelas</h5>
                <button class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <div class="d-flex flex-column gap-2">
                    <div class="p-3 border rounded-3 bg-light">
                        <span class="text-success fw-bold">Nama Kelas:</span>
                        <div id="detailNamaKelas" class="fw-semibold"></div>
                    </div>
                    <div class="p-3 border rounded-3 bg-light">
                        <span class="text-success fw-bold">Gedung:</span>
                        <div id="detailGedung"></div>
                    </div>
                    <div class="p-3 border rounded-3 bg-light">
                        <span class="text-success fw-bold">Nama Wali Kelas:</span>
                        <div id="detailWaliKelas"></div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-primary" data-bs-dismiss="modal">Tutup</button>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function(){

    let table = $('#tableKelas').DataTable({
        dom: '<"dataTables_top d-flex justify-content-between mb-3"l f>rtip',
        processing: true,
        serverSide: true,
        responsive: false,
        autoWidth: false,
        order: [],
        ajax: {
            url: "<?= base_url('kelas/get_data'); ?>", // Sesuaikan dengan controller Kelas
            type: "POST"
        },
        columns: [
            { data: 0, orderable: false },
            { data: 1 },
            { data: 2 },
            { data: 3 },
            { data: 4, orderable: false } // Kolom Aksi
        ],
        language: {
            processing: `<div class="d-flex justify-content-center"><div class="spinner-border text-success"></div></div>`
        }
    });

    $('.dataTables_filter input').attr('placeholder', 'Search...').css({
        'min-width': '300px',
        'padding': '6px 12px',
        'border-radius': '6px',
        'border': '1px solid #ced4da',
        'font-size': '0.9rem',
        'box-sizing': 'border-box'
    });

    table.on('draw', function () {
        $('#tableKelas tbody tr').each(function() {
            $(this).find('td').each(function(index) {
                let header = $('#tableKelas thead th').eq(index).text().trim();
                $(this).attr('data-label', header + ' : ');
            });
        });
    });

    // OPEN MODAL TAMBAH
    $(document).on('click', '.btn-add', function(){
        $('#inputId, #inputNama, #inputGedung, #inputWaliKelas').val('');
        $('#modalKelas .modal-title').text('Tambah Kelas');
        $('#btnSimpanKelas').text('Simpan').data('action','add').removeData('id');
        $('#modalKelas').modal('show');
    });

    // SAVE / UPDATE KELAS
    $('#btnSimpanKelas').click(function(){
        let action = $(this).data('action');
        let id     = $('#inputId').val() || ''; // Ambil dari hidden input
        let formData = {
            id: id,
            nama: $('#inputNama').val(),
            gedung: $('#inputGedung').val(),
            nama_wali_kelas: $('#inputWaliKelas').val()
        };

        let url = action === 'add' ? "<?= base_url('kelas/save'); ?>" : "<?= base_url('kelas/update'); ?>";

        $.ajax({
            url: url,
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function(res){
                if(res.status){
                    $('#modalKelas').modal('hide');
                    table.ajax.reload(null,false);
                    Swal.fire('Sukses', res.message || 'Berhasil!', 'success');
                } else {
                    Swal.fire('Gagal', res.message || 'Gagal!', 'error');
                }
            },
            error: function(){
                Swal.fire('Error', 'Terjadi kesalahan server.', 'error');
            }
        });
    });

    // DETAIL KELAS
    $(document).on('click', '.btn-detail', function(){
        let id = $(this).data('id');
        $.ajax({
            url: "<?= base_url('kelas/detail'); ?>/" + id, // Sesuaikan dengan controller Kelas
            type: "GET",
            dataType: "json",
            success: function(res){
                $('#detailNamaKelas').text(res.nama);
                $('#detailGedung').text(res.gedung);
                $('#detailWaliKelas').text(res.nama_wali_kelas);
                $('#modalDetailKelas').modal('show');
            },
            error: function(){
                Swal.fire('Error','Gagal memuat detail.','error');
            }
        });
    });

    // EDIT KELAS
    $(document).on('click', '.btn-edit', function(){
        let id = $(this).data('id');
        $.ajax({
            url: "<?= base_url('kelas/detail'); ?>/" + id, // Sesuaikan dengan controller Kelas
            type: "GET",
            dataType: "json",
            success: function(res){
                $('#inputId').val(res.id); // Set ID ke hidden input
                $('#inputNama').val(res.nama);
                $('#inputGedung').val(res.gedung);
                $('#inputWaliKelas').val(res.nama_wali_kelas);

                $('#modalKelas .modal-title').text('Edit Kelas');
                $('#btnSimpanKelas').text('Update').data('action','edit'); // ID sudah ada di hidden input
                $('#modalKelas').modal('show');
            },
            error: function(){
                Swal.fire('Error','Gagal memuat data edit.','error');
            }
        });
    });

    // DELETE KELAS
    $(document).on('click', '.btn-delete', function(){
        let id = $(this).data('id');
        Swal.fire({
            title: 'Yakin ingin hapus?',
            text: "Data tidak dapat dikembalikan!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Ya, hapus',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if(result.isConfirmed){
                $.ajax({
                    url: "<?= base_url('kelas/delete'); ?>/" + id, // Sesuaikan dengan controller Kelas
                    type: "GET",
                    dataType: "json",
                    success: function(res){
                        if(res.status){
                            table.ajax.reload(null,false);
                            Swal.fire('Terhapus!', res.message || 'Berhasil dihapus!', 'success');
                        } else {
                            Swal.fire('Gagal', res.message || 'Gagal menghapus!', 'error');
                        }
                    },
                    error: function(){
                        Swal.fire('Error','Terjadi kesalahan saat menghapus.','error');
                    }
                });
            }
        });
    });

});
</script>