<?= $this->extend('Admin/Layout/app_layout'); ?>
<?= $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="">Ekstrakulikuler</h5>

                </div>

                <div class="widget-content">
                    <div class="table-responsive">
                        <table class="table" id="ekstrakulikulerTable" class="display">
                            <thead>
                                <tr>
                                    <th class="text-center">
                                        #
                                    </th>
                                    <th>Ekstrakulikuler</th>
                                    <th>Pembina</th>
                                    <th>Jumlah Anggota</th>

                                </tr>
                            </thead>
                            <tbody>

                            </tbody>
                        </table>
                    </div>
                </div>
            </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>Nama Ekstrakulikuler</label>
                        <input type="text" name="nama" class="form-control form-control-sm" required>
                        <div class="invalid-feedback">Nama Wajib diisi</div>
                    </div>
                    <div class="form-group mb-3">
                        <label>Pembina</label>
                        <select class="form-control tomselect" name="pembina">

                        </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="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 Ekstrakulikuler</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_eskul">
                <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>Kelas</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() {
        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>
                `;
        }
        // Lakukan permintaan AJAX untuk mendapatkan data siswa
        function getDataFromAjax() {
            // Lakukan permintaan AJAX ke endpoint siswa/getsiswa
            // Pastikan endpoint ini mengembalikan data siswa dalam format JSON
            if (!usrListInitialized) {
                $.ajax({
                    url: '<?= base_url() ?>referensi/ekstrakulikuler/getsiswa',
                    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, // Misalnya, gunakan NIS sebagai email
                            rombel: siswa.rombel // Simpan informasi rombongan di sini
                        }));

                        // Inisialisasi Tagify dengan data siswa yang telah diformat
                        usrList = initializeTagify(formattedData);
                        usrListInitialized = true;
                    },
                    error: function(xhr, status, error) {
                        console.error('Error:', error);
                    }
                });
            }
        }

        // Inisialisasi Tagify dengan data siswa dari respons AJAX
        function initializeTagify(data) {
            // Inisialisasi Tagify dengan data siswa
            var 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 remporarily 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 suggesttions when typing
                },
                templates: {
                    tag: tagTemplate,
                    dropdownItem: suggestionItemTemplate
                },
                whitelist: data // Gunakan data siswa dari respons AJAX sebagai daftar putih
            });

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

        // 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 ideskul = $("#id_eskul").val();
            // Kirim data pengguna ke server menggunakan AJAX
            console.log(tagifyValue);
            $.ajax({
                url: '<?= base_url() ?>referensi/ekstrakulikuler/addanggota', // Ubah sesuai dengan URL endpoint Anda
                method: 'POST',
                data: {
                    'tagify': tagifyValue,
                    'id_eskul': ideskul,
                }, // Kirim array langsung tanpa JSON.stringify()
                success: function(response) {
                    getanggota(ideskul);
                    Snackbar.show({
                        text: response.message,
                        pos: 'top-center'
                    });
                },
                error: function(xhr, status, error) {
                    console.error('Error:', error);

                }
            });

        });

        function getanggota(ideskul) {
            $.ajax({
                url: '<?= base_url('referensi/ekstrakulikuler/getanggota/') ?>' + ideskul, // 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.rombel + '</td>' +
                            '<td><btn data-id="' + item.id_penilaian + '" 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, ideskul) {
            $.ajax({
                url: '<?= base_url('referensi/ekstrakulikuler/deleteanggota/') ?>' + idanggota, // Sesuaikan dengan URL Controller Anda
                type: 'DELETE',
                success: function(response) {
                    Snackbar.show({
                        text: response.message,
                        pos: 'top-center'
                    });
                    getanggota(ideskul);
                },
                error: function(error) {
                    console.error('Error deleting user:', error);
                }
            });
        }
        // Tambahkan event listener untuk tombol delete
        $('#tabel-anggota').on('click', '.hapus', function() {
            var ideskul = $("#id_eskul").val()
            var idpenilaian = $(this).data('id');
            console.log(idpenilaian);
            deleteanggota(idpenilaian, ideskul);
        });
        getpembina();
        $('#ekstrakulikulerTable').dataTable({
            ajax: {
                url: '<?= base_url('referensi/ekstrakulikuler/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_ekstrakulikuler'
                },
                {
                    data: 'nama'
                },
                {
                    data: null,
                    render: function(data, type, row) {
                        return '<button data-id="' + row.id + '" class="btn btn-anggota btn-outline-info btn-rounded mb-2 me-4">' + row.anggota + ' Anggota</button>';
                    }
                },

            ],
            "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
        });
        // Event yang dipanggil ketika modal ditutup
        $('#modalanggota').on('hidden.bs.modal', function() {
            refreshDatatable(); // Memuat ulang data DataTable setelah modal ditutup
        });
        // Tambahkan event listener untuk tombol delete
        $('#ekstrakulikulerTable').on('click', '.delete-btn', function() {
            var userId = $(this).data('id');
            deleteUserData(userId);
        });
        $('#ekstrakulikulerTable').on('click', '.edit-btn', function() {
            var userId = $(this).data('id');
            edit(userId);
        });
        $('#ekstrakulikulerTable').on('click', '.btn-anggota', function() {
            var id = $(this).data('id');
            $("#modalanggota").modal('show');
            // Panggil fungsi untuk mendapatkan data siswa dari AJAX saat halaman dimuat
            $("#id_eskul").val(id);
            getDataFromAjax();
            getanggota(id);
            // edit(id);
        });

    });
    var save_method; //for save method string
    var table;

    function getpembina() {
        $.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
        $('#modal_form').modal('show'); // show bootstrap modal
        $('.modal-title').text('Tambah ekstrakulikuler');
    }

    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/ekstrakulikuler/edit') ?>/" + id,
            type: "GET",
            dataType: "JSON",
            success: function(data) {
                // console.log(data);
                tomselect.setValue(data.pembina);
                $('[name="id"]').val(data.id);
                $('[name="kode"]').val(data.kode_ekstrakulikuler);
                $('[name="nama"]').val(data.nama_ekstrakulikuler);
                $('[name="status"]').val(data.status);
                $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
                $('.modal-title').text('Edit Tahun Pelajaran'); // 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/ekstrakulikuler/add') ?>";
        } else {
            url = "<?= base_url('referensi/ekstrakulikuler/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');
                        $('#ekstrakulikulerTable').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 refreshDatatable() {
        $('#ekstrakulikulerTable').DataTable().ajax.reload();
    }

    function deleteUserData(userId) {
        $.ajax({
            url: '<?= base_url('referensi/ekstrakulikuler/delete/') ?>' + userId, // Sesuaikan dengan URL Controller Anda
            type: 'DELETE',
            success: function(response) {
                // Reload DataTable setelah penghapusan berhasil
                $('#ekstrakulikulerTable').DataTable().ajax.reload();
            },
            error: function(error) {
                console.error('Error deleting user:', error);
            }
        });
    }
</script>
<?= $this->endSection(); ?>