<?= $this->extend('Admin/Layout/app_layout'); ?>
<?= $this->section('css'); ?>
<style>

</style>
<?= $this->endSection(); ?>
<?= $this->section('content'); ?>

<div class="layout-px-spacing">

    <div class="middle-content container-xxl p-0">

        <div class="layout-top-spacing">

            <div class="widget widget-three">

                <div class="widget-heading">
                    <h5 class="">Rombongan Belajar</h5>
                    <div class="task-action">
                        <button type="button" onclick="add()" class="btn btn-primary"><i data-feather="plus-circle"></i> <span class="btn-text-inner">Tambah</span></button>

                    </div>
                </div>

                <div class="widget-content">
                    <div class="table-responsive">
                        <table class="table" id="rombelTable" class="display">
                            <thead>
                                <tr>
                                    <th class="text-center">
                                        #
                                    </th>

                                    <th>Nama</th>
                                    <th>Jenis</th>
                                    <th>Walikelas</th>
                                    <th>Pembelajaran</th>
                                    <th>Anggota</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

<div class="modal fade" id="modalcopypembelajaran" role="dialog" aria-labelledby="modelTitleId" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content" style="background-color: #e6f4ff;">
            <div class=" modal-header">
                <h5 class="modal-title">Copy Pembelajaran</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
                    <i data-feather="x"></i>
                </button>
            </div>

            <div class="modal-body">
                <div class="form-group">
                    <input type="hidden" id="rombelasal" class="form-control form-control-sm" required="">
                    <label for="rombelcopy">Pilih Rombel</label>
                    <select class="form-control" name="rombelcopy" id="rombelcopy" required>

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

            <div class="modal-footer">
                <button class="btn btn btn-light-dark" data-bs-dismiss="modal"><i class="flaticon-cancel-12"></i> Cancel</button>
                <button type="button" id="prosesCopy" onclick="prosescopy()" class="btn btn-primary">Proses</button>
            </div>

        </div>
    </div>
</div>
<div class="modal fade" id="modal_form" role="dialog" aria-labelledby="modelTitleId" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Modal title</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
                    <i data-feather="x"></i>
                </button>
            </div>

            <div class="modal-body">
                <div id="errorMessages"></div>
                <form action="#" id="form" class="needs-validation">
                    <input type="hidden" name="id" class="form-control form-control-sm" required="">
                    <div class="form-group mb-3">
                        <label>Kode Rombel</label>
                        <input type="text" name="kode" id="kode" class="form-control form-control-sm" required>
                        <div class="invalid-feedback">Kode Rombel</div>
                    </div>
                    <div class="form-group mb-3">
                        <label>Nama Rombel</label>
                        <input type="text" name="nama" class="form-control form-control-sm" required>
                        <div class="invalid-feedback">Nama Wajib</div>
                    </div>
                    <div class="form-group mb-3">
                        <label>Tingkat Rombel</label>
                        <select class="form-control form-control-sm" name="tingkat" required>
                            <option value="">Pilih Tingkat</option>
                            <?php foreach ($tingkat as $tingkat) { ?>
                                <option value="<?= $tingkat->tingkat ?>"><?= $tingkat->tingkat ?></option>
                            <?php } ?>
                        </select>
                    </div>
                    <div class="form-group mb-3">
                        <label>Jenis Rombel</label>
                        <select class="form-control form-control-sm" name="jenis">
                            <option value="reguler">Reguler</option>
                            <option value="peminatan">Peminatan</option>
                        </select>
                    </div>
                    <div class="form-group mb-3">
                        <label>Wali Kelas</label>
                        <select class="form-control tomselect" name="walikelas">

                        </select>
                    </div>
                    <div class="form-group">
                        <label>Status</label>
                        <select class="form-control form-control-sm" name="status">
                            <option value="aktif">aktif</option>
                            <option value="tidak">tidak aktif</option>
                        </select>
                    </div>
                </form>
            </div>

            <div class="modal-footer">
                <button class="btn btn btn-light-dark" data-bs-dismiss="modal"><i class="flaticon-cancel-12"></i> Discard</button>
                <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
            </div>

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

<div class="modal fade" id="modalpembelajaran" role="dialog" aria-labelledby="modelTitleId" aria-hidden="true">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Mapping Pembelajaran</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
                    <i data-feather="x"></i>
                </button>
            </div>
            <form id="form-mapping">
                <div class="modal-body">
                    <input type="hidden" class="form-control form-control-sm" id="idrombel" name="idrombel">
                    <div id="inputrow-container">
                        <div class="input-row row mb-3">
                            <div class="col-4">
                                <select class="form-control form-control-sm mapel" name="mapel[]" required>
                                    <option value="">Pilih Mata Pelajaran</option>
                                    <?php foreach ($matapelajaran as $mapel) { ?>
                                        <option value="<?= $mapel->id ?>"><?= $mapel->nama_matapelajaran ?></option>
                                    <?php } ?>
                                </select>
                            </div>
                            <div class="col-4">
                                <select class="form-control form-control-sm guru" name="guru[]" required>
                                    <option value="">Pilih Guru</option>
                                    <?php foreach ($guru as $guru) { ?>
                                        <option value="<?= $guru->id ?>"><?= $guru->nama ?></option>
                                    <?php } ?>
                                </select>
                            </div>
                            <div class="col-2">
                                <input type="text" class="form-control form-control-sm urut" name="urut[]" required placeholder="No Urut"></input>
                            </div>
                            <div class="col-1">
                                <a href="javascript:void(0)" class="delete-row"><i data-feather="trash"></i></a>
                            </div>
                        </div>

                    </div>
                    <button type="button" id="add-item" class="btn btn-primary"><i data-feather="plus"></i>Add Item</button>
                    <button type="button" id="copy-item" class="btn btn-primary"><i data-feather="copy"></i>Copy Pembelajaran</button>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn btn-light-dark" data-bs-dismiss="modal"><i class="flaticon-cancel-12"></i> Discard</button>
                    <button type="button" id="btnSaveMapping" class="btn btn-primary">Save</button>
                </div>
            </form>

        </div>
    </div>
</div>
<div class="modal fade" id="modalanggota" role="dialog" aria-labelledby="modelTitleId" aria-hidden="true" data-bs-backdrop="static">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Anggota Rombel</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
                    <i data-feather="x"></i>
                </button>
            </div>

            <div class="modal-body">
                <input class="mb-3" name='users-list-tags' required placeholder="cari siswa by nama, nis, atau kelas">
                <input type="hidden" id="id_rombel">
                <button id="tambah-anggota" type="button" class="btn btn-primary mb-3">Tambah Anggota</button>
                <div class="table-responsive">
                    <table id="tabel-anggota" class="table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Nama Siswa</th>
                                <th>Rombel</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn btn-light-dark" data-bs-dismiss="modal"><i class="flaticon-cancel-12"></i>Close</button>

            </div>

        </div>
    </div>
</div>
<?= $this->endSection(); ?>
<?= $this->section('pagejs'); ?>
<script type="text/javascript">
    $(document).ready(function() {
        // Ketika tombol "Copy Pembelajaran" diklik

        $('#copy-item').on('click', function() {

            // Menyimpan modal pembelajaran dalam variabel
            var $modalPembelajaran = $('#modalpembelajaran');

            // Mendapatkan z-index modal pembelajaran
            var zIndexPembelajaran = $modalPembelajaran.css('z-index');

            // Menetapkan z-index modal baru lebih tinggi dari modal pembelajaran
            $('#modalcopypembelajaran').css('z-index', zIndexPembelajaran + 1);

            // Menampilkan modal copy pembelajaran
            $('#modalcopypembelajaran').modal('show');
        });


        getrombel();

        function getrombel() {
            $.ajax({
                url: '<?= base_url('referensi/rombel/getdata') ?>',
                type: 'GET',
                success: function(response) {
                    response = response.data;
                    // Mengisi pilihan dalam elemen select dengan data yang diterima
                    var select = $('#rombelcopy');
                    // Bersihkan opsi sebelum menambahkan yang baru
                    select.empty();
                    // Tambahkan opsi ke dalam select
                    select.append('<option value="">Pilih Rombel</option>');
                    for (var i = 0; i < response.length; i++) {
                        select.append('<option value="' + response[i].id + '">' + response[i].nama_rombel + ' ' + response[i].jumlah_pembelajaran + ' Pembelajaran</option>');
                    }
                },
                error: function() {
                    console.log('Gagal mendapatkan data.');
                }
            });
        }

        var inputElm = document.querySelector('input[name=users-list-tags]');
        var usrList;
        var usrListInitialized = false; // variabel penanda apakah Tagify telah diinisialisasi

        function tagTemplate(tagData) {
            return `
                    <tag title="${tagData.nis}"
                            contenteditable='false'
                            spellcheck='false'
                            tabIndex="-1"
                            class="tagify__tag ${tagData.class ? tagData.class : ""}"
                            ${this.getAttributes(tagData)}>
                        <x title='' class='tagify__tag__removeBtn' role='button' aria-label='remove tag'></x>
                        <div>
                           
                            <span class='tagify__tag-text'>${tagData.nama}</span>
                        </div>
                    </tag>
                `;
        }

        function suggestionItemTemplate(tagData) {
            return `
                    <div ${this.getAttributes(tagData)}
                        class='tagify__dropdown__item ${tagData.class ? tagData.class : ""}'
                        tabindex="0"
                        role="option">
                        
                        <strong>${tagData.nama} - ${tagData.rombel ? tagData.rombel : ""}</strong>
                        <span>${tagData.nis}</span>
                    </div>
                `;
        }

        // Fungsi untuk melakukan permintaan AJAX dan memperbarui whitelist Tagify
        function getDataFromAjax(idrombel) {
            // Lakukan permintaan AJAX ke endpoint siswa/getsiswarombel

            $.ajax({
                url: '<?= base_url() ?>siswa/getsiswarombel/' + idrombel,
                method: 'GET',
                dataType: 'json',
                success: function(data) {
                    // Ubah format data siswa sesuai dengan kebutuhan Tagify
                    const formattedData = data.map(siswa => ({
                        value: siswa.id,
                        nama: siswa.nama,
                        nis: siswa.nis,
                        rombel: siswa.rombel
                    }));

                    // Perbarui whitelist Tagify dengan data yang telah diformat
                    if (usrList) {
                        usrList.settings.whitelist = formattedData; // Set whitelist
                        usrList.update(); // Perbarui Tagify
                    } else {
                        console.error('usrList is not initialized.'); // Tampilkan pesan kesalahan jika usrList belum diinisialisasi
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error:', error);
                }
            });

        }

        // Fungsi untuk inisialisasi Tagify
        function initializeTagify() {
            // Inisialisasi Tagify dengan data siswa
            if (!usrList) {
                usrList = new Tagify($('input[name=users-list-tags]')[0], {
                    // Konfigurasi lainnya...
                    tagTextProp: 'nama', // very important since a custom template is used with this property as text
                    enforceWhitelist: true,
                    skipInvalid: true, // do not temporarily add invalid tags
                    dropdown: {
                        maxItems: 36,
                        closeOnSelect: false,
                        enabled: 0,
                        classname: 'users-list',
                        searchKeys: ['nama', 'nis', 'rombel'] // very important to set by which keys to search for suggestions when typing
                    },
                    templates: {
                        tag: tagTemplate,
                        dropdownItem: suggestionItemTemplate
                    },
                    whitelist: [] // Initial empty whitelist
                });

                // Tambahkan event listener dan lainnya seperti yang Anda lakukan sebelumnya
                usrList.on('dropdown:show dropdown:updated', onDropdownShow);
                usrList.on('dropdown:select', onSelectSuggestion);
            }
        }

        // Tambahkan fungsi-fungsi tambahan yang diperlukan
        function onDropdownShow(e) {
            var dropdownContentElm = e.detail.tagify.DOM.dropdown.content;

            if (usrList.suggestedListItems.length > 1) {
                addAllSuggestionsElm = getAddAllSuggestionsElm();

                // insert "addAllSuggestionsElm" as the first element in the suggestions list
                dropdownContentElm.insertBefore(addAllSuggestionsElm, dropdownContentElm.firstChild)
            }
        }

        function onSelectSuggestion(e) {
            if (e.detail.elm == addAllSuggestionsElm)
                usrList.dropdown.selectAll();
        }

        // create a "add all" custom suggestion element every time the dropdown changes
        function getAddAllSuggestionsElm() {
            // suggestions items should be based on "dropdownItem" template
            return usrList.parseTemplate('dropdownItem', [{
                class: "addAll",
                nama: "Tambah Semua",
                nis: usrList.whitelist.reduce(function(remainingSuggestions, item) {
                    return usrList.isTagDuplicate(item.value) ? remainingSuggestions : remainingSuggestions + 1
                }, 0) + " Anggota"
            }])
        }

        $('#tambah-anggota').on('click', function() {

            // Ambil nilai dari elemen input Tagify
            var tagifyValue = usrList.value;
            var idrombel = $("#id_rombel").val();
            // Kirim data pengguna ke server menggunakan AJAX
            console.log(tagifyValue);
            $.ajax({
                url: '<?= base_url() ?>referensi/rombel/addanggota', // Ubah sesuai dengan URL endpoint Anda
                method: 'POST',
                data: {
                    'tagify': tagifyValue,
                    'id_rombel': idrombel,
                }, // Kirim array langsung tanpa JSON.stringify()
                success: function(response) {
                    getanggota(idrombel);
                    getDataFromAjax(idrombel);
                    usrList.removeAllTags();
                    usrList.update();
                    Snackbar.show({
                        text: response.message,
                        pos: 'top-center'
                    });
                },
                error: function(xhr, status, error) {
                    console.error('Error:', error);

                }
            });

        });

        function getanggota(idrombel) {
            $.ajax({
                url: '<?= base_url('referensi/rombel/getanggota/') ?>' + idrombel, // Ubah ini sesuai dengan URL endpoint Anda
                type: 'GET',
                dataType: "json",
                success: function(data) {
                    var tbody = $('#tabel-anggota tbody');
                    $("#alert").empty();
                    tbody.empty();
                    $.each(data, function(index, item) {
                        var no = index + 1;
                        var row = '<tr>' +
                            '<td>' + no + '</td>' +
                            '<td>' + item.nama + '</td>' +
                            '<td>' + item.nama_rombel + '</td>' +
                            '<td><btn data-id="' + item.id + '" class="hapus btn btn-outline-danger btn-rounded btn-sm">Hapus</button></td>' +

                            '</tr>';

                        tbody.append(row);
                    });
                },
                error: function(xhr, status, error) {
                    console.error(status, error);
                    // Tindakan yang sesuai jika ada kesalahan dalam pengambilan data
                }
            });
        }

        function deleteanggota(idanggota, idrombel) {
            $.ajax({
                url: '<?= base_url('referensi/rombel/deleteanggota/') ?>' + idanggota, // Sesuaikan dengan URL Controller Anda
                type: 'DELETE',
                success: function(response) {
                    Snackbar.show({
                        text: response.message,
                        pos: 'top-center'
                    });
                    getanggota(idrombel);
                },
                error: function(error) {
                    console.error('Error deleting user:', error);
                }
            });
        }
        // Tambahkan event listener untuk tombol delete
        $('#tabel-anggota').on('click', '.hapus', function() {
            var idrombel = $("#id_rombel").val()
            var idpenilaian = $(this).data('id');
            deleteanggota(idpenilaian, idrombel);
        });
        $('#btnSaveMapping').click(function() {
            // Mengambil data dari form
            var formData = $('#form-mapping').serialize();
            var idrombel = $('#idrombel').val();

            // Validasi formulir
            var isValid = true;

            $('.mapel, .guru, .urut').each(function() {
                if ($(this).val() === '') {
                    isValid = false;
                    $(this).addClass('is-invalid');
                } else {
                    $(this).removeClass('is-invalid');
                }
            });

            // Jika formulir tidak valid, hentikan pengiriman
            if (!isValid) {
                return false;
            }

            // Mengirim data ke server menggunakan AJAX
            $.ajax({
                type: "POST",
                url: "<?php echo base_url('referensi/rombel/addmapping'); ?>",
                data: formData,
                dataType: "json",
                success: function(response) {
                    if (response.success) {
                        getmapping(idrombel);
                        Snackbar.show({
                            text: response.message,
                            pos: 'top-center'
                        });
                        // Lakukan tindakan lain setelah data berhasil disimpan
                    } else {
                        Snackbar.show({
                            text: response.message,
                            pos: 'top-center'
                        });
                    }
                }
            });
        });
        $('#add-item').click(function() {
            // Clone the input-row and append it after the last input-row

            var newRow = $('.input-row').first().clone();
            $('.input-row').last().after(newRow);

            // Clearing the values in the newly added row
            newRow.find('select, input').val('');

            // Adding event listener to the delete button of the newly added row
            newRow.find('.delete-row').click(function() {
                $(this).closest('.input-row').remove();
            });
        });
        $('#kode').on('input', function() {
            // Menghapus spasi dari nilai input
            var cleanedValue = $(this).val().replace(/[^A-Za-z0-9]/g, '');
            $(this).val(cleanedValue);
        });
        $('#rombelTable').dataTable({
            ajax: {
                url: '<?= base_url('referensi/rombel/getdata') ?>', // Sesuaikan dengan URL Controller Anda
                type: 'GET'
            },
            columns: [{
                    data: null,
                    render: function(data, type, row, meta) {
                        return meta.row + 1; // Nomor urut dimulai dari 1, bukan 0
                    },
                    orderable: false // Kolom ini tidak dapat diurutkan
                },
                {
                    data: 'nama_rombel'
                },
                {
                    data: 'jenis'
                },
                {
                    data: 'nama_walas'
                },
                {
                    data: null,
                    render: function(data, type, row) {
                        return '<button class="pembelajaran-btn btn btn-sm btn-outline-info" data-id="' + row.id + '">' + row.jumlah_pembelajaran + ' Pembelajaran</button>';
                    }
                },
                {
                    data: null,
                    render: function(data, type, row) {
                        return '<button class="anggota-btn btn btn-sm btn-outline-success" data-id="' + row.id + '">' + row.jumlah_anggota + ' Anggota</button>';
                    }
                },
                {
                    data: 'status',
                    render: function(data) {
                        // Gunakan badge untuk menunjukkan status
                        return (data === 'aktif') ? '<span class="badge badge-success">Aktif</span>' : '<span class="badge badge-danger">Tidak Aktif</span>';
                    }
                },
                {
                    data: null,
                    render: function(data, type, row) {
                        return '<a href="javascript:void(0)" class="edit-btn" data-id="' + row.id + '"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-edit-2 p-1 br-8 mb-1"><path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"></path></svg>Edit</a> <a href="javascript:void(0)" class="delete-btn" data-id="' + row.id + '"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-trash p-1 br-8 mb-1"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>Hapus</a>';
                    }
                }
            ],
            "dom": "<'dt--top-section'<'row'<'col-12 col-sm-6 d-flex justify-content-sm-start justify-content-center'l><'col-12 col-sm-6 d-flex justify-content-sm-end justify-content-center mt-sm-0 mt-3'f>>>" +
                "<'table-responsive'tr>" +
                "<'dt--bottom-section d-sm-flex justify-content-sm-between text-center'<'dt--pages-count  mb-sm-0 mb-3'i><'dt--pagination'p>>",
            "oLanguage": {
                "oPaginate": {
                    "sPrevious": '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-left"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>',
                    "sNext": '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-right"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>'
                },
                "sInfo": "Showing page _PAGE_ of _PAGES_",
                "sSearch": '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-search"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>',
                "sSearchPlaceholder": "Search...",
                "sLengthMenu": "Results :  _MENU_",
            },
            "stripeClasses": [],
            "lengthMenu": [7, 10, 20, 50],
            "pageLength": 10
        });

        // Tambahkan event listener untuk tombol delete
        $('#rombelTable').on('click', '.delete-btn', function() {
            var userId = $(this).data('id');
            deleteUserData(userId);
        });
        $('#inputrow-container').on('click', '.delete-mapping', function() {
            var userId = $(this).data('id');
            deleteMapping(userId);
        });
        $('#rombelTable').on('click', '.pembelajaran-btn', function() {
            var userId = $(this).data('id');
            $('#modalpembelajaran').modal('show');
            $('#idrombel').val(userId);
            $('.mapel').val("");
            $('.guru').val("");
            $('.urut').val("");
            getmapping(userId);
        });
        $('#rombelTable').on('click', '.edit-btn', function() {
            var userId = $(this).data('id');
            edit(userId);
        });
        $('#rombelTable').on('click', '.anggota-btn', function() {
            var id = $(this).data('id');
            $("#modalanggota").modal('show');
            // Panggil fungsi untuk mendapatkan data siswa dari AJAX saat halaman dimuat
            $("#id_rombel").val(id);
            initializeTagify();

            getDataFromAjax(id);
            getanggota(id);
            // edit(id);
        });
        getwalas();
        $('#modalanggota').on('hidden.bs.modal', function() {
            // Kode untuk menangani penutupan modal di sini
            $('#rombelTable').DataTable().ajax.reload();
        });
    });
    var save_method; //for save method string
    var table;

    function getmapping(id) {
        $.ajax({
            url: '<?= base_url('referensi/rombel/getmapping/') ?>' + id,
            type: 'GET',
            dataType: 'json',
            success: function(data) {
                if (data != "") {
                    $('#inputrow-container').empty();
                }

                $.each(data, function(index, item) {
                    var inputRow = '<div class="input-row row mb-3">' +
                        '<div class="col-4">' +
                        '<select class="form-control form-control-sm mapel" name="mapel[]"></select>' +
                        '</div>' +
                        '<div class="col-4">' +
                        '<select class="form-control form-control-sm guru" name="guru[]"></select>' +
                        '</div>' +
                        '<div class="col-2">' +
                        '<input type="text" class="form-control form-control-sm urut" value="' + item.no_urut + '" name="urut[]" placeholder="No Urut">' +
                        '</div>' +
                        '<div class="col-1">' +
                        '<a class="delete-row delete-mapping" data-id="' + item.id + '" href="javascript:void(0)"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-trash p-1 br-8 mb-1"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg></a>' +
                        '</div>' +
                        '</div>';
                    $('#inputrow-container').append(inputRow);
                    // Memasukkan data guru ke dalam select guru
                    var guruSelect = $('#inputrow-container').find('.guru').last();
                    guruSelect.append('<option value="" >Pilih Guru</option>');
                    $.each(item.user, function(index, user) {
                        var selected = (user.id_user == item.id_guru) ? 'selected' : '';
                        guruSelect.append('<option value="' + user.id_user + '" ' + selected + '>' + user.nama_user + '</option>');
                    });

                    // Memasukkan data mata pelajaran ke dalam select mapel
                    var mapelSelect = $('#inputrow-container').find('.mapel').last();
                    mapelSelect.append('<option value="" >Pilih Mata Pelajaran</option>');
                    $.each(item.mapel, function(index, mapel) {
                        var selected = (mapel.id_mapel == item.id_matapelajaran) ? 'selected' : '';
                        mapelSelect.append('<option value="' + mapel.id_mapel + '" ' + selected + '>' + mapel.nama_mapel + '</option>');
                    });
                });
            }
        });
    }

    function getwalas() {
        $.ajax({
            url: '<?= base_url('referensi/rombel/getwalas') ?>',
            type: 'GET',
            success: function(response) {
                // Mengisi pilihan dalam elemen select dengan data yang diterima

                // Tambahkan opsi ke dalam select
                for (var i = 0; i < response.length; i++) {
                    tomselect.addOption({
                        id: response[i].id,
                        title: response[i].nama,

                    });

                }
            },
            error: function() {
                console.log('Gagal mendapatkan data.');
            }
        });
    }

    function add() {
        $('#form').removeClass('was-validated');
        save_method = 'add';
        $('#form')[0].reset(); // reset form on modals
        tomselect.clear(); // clear
        $('#modal_form').modal('show'); // show bootstrap modal
        $('.modal-title').text('Tambah rombel');
    }

    function edit(id) {
        save_method = 'update';
        $('#form')[0].reset(); // reset form on modals
        $('[name="password"]').removeAttr('required');
        <?php header('Content-type: application/json'); ?>
        //Ajax Load data from ajax
        $.ajax({
            url: "<?php echo site_url('referensi/rombel/edit') ?>/" + id,
            type: "GET",
            dataType: "JSON",
            success: function(data) {
                // console.log(data);
                tomselect.setValue(data.walikelas);
                $('[name="id"]').val(data.id);
                $('[name="kode"]').val(data.kode_rombel);
                $('[name="nama"]').val(data.nama_rombel);
                $('[name="tingkat"]').val(data.tingkat);
                $('[name="jenis"]').val(data.jenis);
                $('[name="status"]').val(data.status);
                $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
                $('.modal-title').text('Edit Rombel'); // Set title to Bootstrap modal title
            },
            error: function(jqXHR, textStatus, errorThrown) {
                //console.log(jqXHR);
                alert('Error get data from ajax');
            }
        });
    }

    function save() {
        var url;
        if (save_method == 'add') {
            url = "<?= base_url('referensi/rombel/add') ?>";
        } else {
            url = "<?= base_url('referensi/rombel/update') ?>";
        }
        $('#form').find('input').focus(function() {
            // $(this).removeClass('is-invalid');
            $('#errorMessages').html('');
        });
        // ajax adding data to database
        if ($('#form')[0].checkValidity() === false) {
            event.preventDefault();
            event.stopPropagation();
            $('#form').addClass('was-validated');
        } else {
            $.ajax({
                url: url,
                type: "POST",
                data: $('#form').serialize(),
                dataType: "JSON",
                success: function(data) {
                    if (data.success) {
                        //if success close modal and reload ajax table
                        $('#modal_form').modal('hide');
                        $('#rombelTable').DataTable().ajax.reload();
                        Snackbar.show({
                            text: data.message,
                            pos: 'top-center'
                        });
                    } else {
                        if (data.errors) {
                            // Tampilkan pesan kesalahan
                            var errorMessages = '<div class="alert alert-danger" role="alert">';
                            errorMessages += '<ul>';
                            $.each(data.errors, function(key, value) {
                                errorMessages += '<li>' + value + '</li>';
                            });
                            errorMessages += '</ul></div>';
                            $('#errorMessages').html(errorMessages);
                        } else {
                            Snackbar.show({
                                text: data.message,
                                pos: 'top-center'
                            });
                        }
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    Snackbar.show({
                        text: data.message,
                        pos: 'top-center'
                    });
                }
            });
        }
    }

    function deleteUserData(userId) {
        Swal.fire({
            title: 'Are you sure?',
            text: "ini akan menghapus data yang kamu pilih!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '<?= base_url('referensi/rombel/delete/') ?>' + userId, // Sesuaikan dengan URL Controller Anda
                    type: 'DELETE',
                    success: function(response) {
                        Swal.fire(
                            'Deleted!',
                            'Your file has been deleted.',
                            'success'
                        )
                        $('#rombelTable').DataTable().ajax.reload();
                    },
                    error: function(error) {
                        console.error('Error deleting user:', error);
                    }
                });

            }
        })

    }

    function deleteMapping(userId) {
        var idrombel = $('#idrombel').val();
        Swal.fire({
            title: 'Are you sure?',
            text: "Hati hati saat menghapus data ini akan menyebabkan semua yang terkait hilang!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '<?= base_url('referensi/rombel/deletemapping/') ?>' + userId, // Sesuaikan dengan URL Controller Anda
                    type: 'DELETE',
                    success: function(response) {
                        Snackbar.show({
                            text: 'berhasil dihapus',
                            pos: 'top-center'
                        });
                        getmapping(idrombel);
                    },
                    error: function(error) {
                        console.error('Error deleting user:', error);
                    }
                });

            }
        })

    }

    function prosescopy() {
        var rombel2 = $('#idrombel').val();
        // Mendapatkan nilai rombel yang dipilih
        var rombel1 = $('#rombelcopy').val();

        // Memeriksa apakah rombel telah dipilih
        if (rombel1) {
            // Kirim nilai rombel melalui Ajax
            $.ajax({
                url: '<?= base_url() ?>referensi/rombel/copypembelajaran', // Ganti dengan URL endpoint Anda
                type: 'POST',
                dataType: 'json',
                data: {
                    rombel1: rombel1,
                    rombel2: rombel2
                },
                success: function(response) {
                    Snackbar.show({
                        text: response.message,
                        pos: 'top-center'
                    });
                    getmapping(rombel2);
                },
                error: function(xhr, status, error) {
                    console.error(status, error);
                    // Tanggapan gagal, lakukan sesuatu jika perlu
                }
            });
        } else {
            // Jika rombel tidak dipilih, tampilkan pesan kesalahan
            $('#rombelcopy').addClass('is-invalid'); // Tambahkan kelas is-invalid ke input
            $('#rombelcopy').siblings('.invalid-feedback').text('Silakan pilih rombel.'); // Tampilkan pesan kesalahan
        }
    }
</script>
<?= $this->endSection(); ?>