<?= $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="">Data User</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>
                        <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#modalimport"><i data-feather="upload"></i> <span class="btn-text-inner">Import</span></button>

                    </div>
                </div>

                <div class="widget-content">
                    <div class="table-responsive">
                        <table class="table " id="userTable" class="display">
                            <thead>
                                <tr>
                                    <th class="text-center">
                                        #
                                    </th>
                                    <th>Foto</th>
                                    <th>NIS</th>
                                    <th>Nama Siswa</th>
                                    <th>Username</th>
                                    <th>Kelas</th>
                                    <th>Rombel</th>
                                    <th>No HP</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>

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

</div>
<div class="modal fade" id="modalimport" 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">Import Excel</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="form-control " type="file" id="xlsx_file" accept=".xlsx"></br>
                <a href="<?= base_url('src/assets/template/template_import_siswa.xlsx') ?>" class="badge badge-info mt-3">Download Template</a>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" id="importbtn" class="btn btn-primary">Save</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>NIS</label>
                        <input type="text" name="nis" class="form-control form-control-sm" required>
                        <div class="invalid-feedback">NIS Wajib diisi</div>
                    </div>
                    <div class="form-group mb-3">
                        <label>Nama Lengkap</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>Username</label>
                        <input type="text" name="username" class="form-control form-control-sm" required>
                        <div class="invalid-feedback">Username Wajib diisi</div>
                    </div>
                    <div class="form-group mb-3">
                        <label>Password</label>
                        <input type="password" name="password" class="form-control form-control-sm" required>
                        <div class="invalid-feedback"></div>
                    </div>
                    <div class="form-group mb-3">
                        <label>rombel</label>
                        <select class="form-control tomselect" name="rombel" id="rombel" required>
                            <option></option>
                        </select>
                    </div>

                    <div class="form-group mb-3">
                        <label>Nomer HP</label>
                        <input type="text" name="nohp" class="form-control form-control-sm" required>
                        <div class="invalid-feedback">No HP Wajib diisi</div>
                    </div>
                    <div class="form-group mb-3">
                        <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 type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
            </div>

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

<?= $this->endSection(); ?>
<?= $this->section('pagejs'); ?>
<script type="text/javascript">
    $(document).ready(function() {
        $('#uploadFoto').submit(function(e) {
            e.preventDefault(); // Mencegah form untuk melakukan submit secara default

            var form = $(this);
            var formData = new FormData(form[0]); // Mengambil data form

            // Melakukan pengiriman data form menggunakan Ajax
            $.ajax({
                type: 'POST',
                url: '<?= base_url('siswa/uploadfoto') ?>',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    // Menangani respons dari server setelah upload berhasil
                    alert('Upload berhasil');
                    // Lakukan ekstraksi file ZIP dan penyimpanan di folder assets/img/fotosiswa
                    // Anda dapat menggunakan endpoint lain di server untuk menangani ekstraksi dan penyimpanan
                },
                error: function(xhr, status, error) {
                    // Menangani kesalahan saat upload
                    alert('Upload gagal: ' + error);
                }
            });
        });
        getrombel();
        // getrombelpeminatan();
        $('#userTable').dataTable({
            ajax: {
                url: '<?= base_url('siswa/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: 'foto',
                    render: function(data) {
                        // Gunakan badge untuk menunjukkan status
                        return '<img class="rounded-circle" width="50" src="' + '<?= base_url('assets/img/fotosiswa/') ?>' + data + '" />';
                    }
                },
                {
                    data: 'nis'
                },
                {
                    data: null,
                    render: function(data, type, row) {
                        return '<a href="<?= base_url('siswa/detail/') ?>' + row.id + '">' + row.nama + '</a>';
                    }
                },
                {
                    data: 'username'
                },
                {
                    data: 'rombel'
                },
                {
                    data: 'nama_rombel',
                    render: function(data) {
                        // Gunakan badge untuk menunjukkan status
                        return (data) ? data : '<span class="badge badge-danger">Belum</span>';
                    }
                },
                {
                    data: 'nohp'
                },
                {
                    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": [10, 20, 50, 100],
            "pageLength": 10
        });

        // Tambahkan event listener untuk tombol delete
        $('#userTable').on('click', '.delete-btn', function() {
            var userId = $(this).data('id');
            deleteUserData(userId);
        });
        $('#userTable').on('click', '.edit-btn', function() {
            var userId = $(this).data('id');
            edit(userId);
        });

        $('#importbtn').on('click', function() {
            var fileInput = $('#xlsx_file')[0].files[0];
            var formData = new FormData();
            formData.append('xlsx_file', fileInput);

            $.ajax({
                url: '<?= base_url('siswa/import') ?>',
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function(response) {
                    $('#modalimport').modal('hide');
                    $('#userTable').DataTable().ajax.reload();
                    Snackbar.show({
                        text: response.message,
                        pos: 'top-center'
                    });
                },
                error: function() {
                    $('#message').text('Terjadi kesalahan. Silakan coba lagi.');
                }
            });
        });
    });

    function getrombel() {
        $.ajax({
            url: '<?= base_url('siswa/getrombel') ?>',
            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].kode_rombel,
                        title: response[i].nama_rombel,

                    });
                    console.log(response[i].nama_rombel);
                }
            },
            error: function() {
                console.log('Gagal mendapatkan data.');
            }
        });
    }

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

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

    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 User');
    }

    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('siswa/edit') ?>/" + id,
            type: "GET",
            dataType: "JSON",
            success: function(data) {
                // getrombel();
                $('[name="id"]').val(data.id);
                $('[name="nis"]').val(data.nis);
                $('[name="id_presensi"]').val(data.id_presensi);
                $('[name="nama"]').val(data.nama);
                $('[name="username"]').val(data.username);
                tomselect.setValue(data.rombel);

                $('[name="nohp"]').val(data.nohp);
                $('[name="status"]').val(data.status);
                $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
                $('.modal-title').text('Edit User'); // 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('siswa/add') ?>";
        } else {
            url = "<?= base_url('siswa/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');
                        $('#userTable').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) {

                }
            });
        }
    }

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