<?= $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">

                <div class="widget-heading">
                    <h5 class="">Rekap Absensi</h5>

                </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>Sakit</th>
                                    <th>Ijin</th>
                                    <th>Alfa</th>
                                    <th>Total Absensi</th>
                                    <th>Catatan</th>

                                </tr>
                            </thead>
                            <tbody>

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

</div>



<div class="modal fade" id="modalabsensi" 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">Absensi Siswa</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 type="hidden" id="id_rombel">
                <div class="table-responsive">
                    <table id="table-absensi" class="table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Nama</th>
                                <th>Rombel</th>
                                <th>Sakit</th>
                                <th>Ijin</th>
                                <th>Alfa</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> Discard</button>
                <button type="button" id="simpanAbsensi" class="btn btn-primary">Save</button>
            </div>

        </div>
    </div>
</div>
<div class="modal fade" id="modalcatatan" 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">Catatan Walikelas</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 type="hidden" id="id_rombel">
                <div class="table-responsive">
                    <table id="table-catatan" class="table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Nama</th>
                                <th>Rombel</th>
                                <th>Catatan Wali Kelas</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> Discard</button>
                <button type="button" id="simpanCatatan" class="btn btn-primary">Save</button>
            </div>

        </div>
    </div>
</div>
<?= $this->endSection(); ?>
<?= $this->section('pagejs'); ?>
<script type="text/javascript">
    $(document).ready(function() {
        $('#table-catatan').on('keydown', 'input, textarea', function(e) {
            var code = e.keyCode || e.which;
            var $this = $(this);
            var $td = $this.closest('td');
            var $tr = $td.closest('tr');
            var index = $td.index();

            if (code == 40) { // Panah bawah
                e.preventDefault();
                var $nextTr = $tr.next();
                var $nextTd = $nextTr.children().eq(index).find('input, textarea');
                if ($nextTd.length > 0) {
                    $nextTd.focus().select();
                } else {
                    var $nextInput = $tr.next().find('input, textarea').eq(0);
                    if ($nextInput.length > 0) {
                        $nextInput.focus().select();
                    }
                }
            } else if (code == 38) { // Panah atas
                e.preventDefault();
                var $prevTr = $tr.prev();
                var $prevTd = $prevTr.children().eq(index).find('input, textarea');
                if ($prevTd.length > 0) {
                    $prevTd.focus().select();
                } else {
                    var $prevInput = $tr.prev().find('input, textarea').eq(0);
                    if ($prevInput.length > 0) {
                        $prevInput.focus().select();
                    }
                }
            } else if (code == 37) { // Panah kiri
                e.preventDefault();
                var $prevTd = $td.prev('td').find('input, textarea');
                if ($prevTd.length > 0) {
                    $prevTd.focus().select();
                }
            } else if (code == 39) { // Panah kanan
                e.preventDefault();
                var $nextTd = $td.next('td').find('input, textarea');
                if ($nextTd.length > 0) {
                    $nextTd.focus().select();
                }
            }
        });
        $('#table-absensi').on('keydown', 'input, textarea', function(e) {
            var code = e.keyCode || e.which;
            var $this = $(this);
            var $td = $this.closest('td');
            var $tr = $td.closest('tr');
            var index = $td.index();

            if (code == 40) { // Panah bawah
                e.preventDefault();
                var $nextTr = $tr.next();
                var $nextTd = $nextTr.children().eq(index).find('input, textarea');
                if ($nextTd.length > 0) {
                    $nextTd.focus().select();
                } else {
                    var $nextInput = $tr.next().find('input, textarea').eq(0);
                    if ($nextInput.length > 0) {
                        $nextInput.focus().select();
                    }
                }
            } else if (code == 38) { // Panah atas
                e.preventDefault();
                var $prevTr = $tr.prev();
                var $prevTd = $prevTr.children().eq(index).find('input, textarea');
                if ($prevTd.length > 0) {
                    $prevTd.focus().select();
                } else {
                    var $prevInput = $tr.prev().find('input, textarea').eq(0);
                    if ($prevInput.length > 0) {
                        $prevInput.focus().select();
                    }
                }
            } else if (code == 37) { // Panah kiri
                e.preventDefault();
                var $prevTd = $td.prev('td').find('input, textarea');
                if ($prevTd.length > 0) {
                    $prevTd.focus().select();
                }
            } else if (code == 39) { // Panah kanan
                e.preventDefault();
                var $nextTd = $td.next('td').find('input, textarea');
                if ($nextTd.length > 0) {
                    $nextTd.focus().select();
                }
            } else if (code == 13) { // Tombol enter
                e.preventDefault();
                var $nextTr = $tr.next();
                var $nextTd = $nextTr.children().eq(index).find('input, textarea');
                if ($nextTd.length > 0) {
                    $nextTd.focus().select();
                } else {
                    var $nextInput = $tr.next().find('input, textarea').eq(0);
                    if ($nextInput.length > 0) {
                        $nextInput.focus().select();
                    }
                }
            }
        });
        // Ketika input-nilai berubah
        $(document).on('input', '.input-nilai', function() {
            // Hapus semua karakter selain angka dari nilai input
            $(this).val($(this).val().replace(/\D/g, ''));
        });
        $('#table-absensi').on('paste', '.input-nilai', function(event) {
            var clipboardData = (event.originalEvent || event).clipboardData;
            var pastedData = clipboardData.getData('text');
            var rows = pastedData.split('\n');

            $('#table-absensi .dataRow').each(function(index, row) {
                var values = rows[index] ? rows[index].split('\t') : [];
                $(row).find('.input-nilai').each(function(index, input) {
                    $(input).val(values[index] || '');
                });
            });

            event.preventDefault(); // Prevent the default paste behavior
        });
        $('#simpanAbsensi').on('click', function() {
            $(this).prop('disabled', true);
            var absensiData = [];
            // Loop melalui elemen input dan tambahkan nilai ke dalam objek absensiData
            $('input[name="sakit[]"]').each(function(index) {
                var siswaId = $(this).data('siswa');
                var sakit = $(this).val();
                var id_absensi = $('input[name="idabsensi[]"]').eq(index).data('id');
                var ijin = $('input[name="ijin[]"]').eq(index).val();
                var alfa = $('input[name="alfa[]"]').eq(index).val();

                // Menambahkan data ke dalam objek absensiData
                var absensi = {
                    id_absensi: id_absensi,
                    id_siswa: siswaId,
                    sakit: sakit,
                    ijin: ijin,
                    alfa: alfa
                };
                absensiData.push(absensi);
            });
            console.log(absensiData);
            var idrombel = $('#id_rombel').val();
            //Kirim data absensiData ke server melalui AJAX
            $.ajax({
                url: '<?= base_url('penilaian/absensi/simpan') ?>',
                method: 'POST',
                dataType: 'json',
                data: {
                    absensiData: absensiData
                },
                success: function(response) {
                    $('#simpanAbsensi').prop('disabled', false);

                    getpenilaian(idrombel);
                    // Handle response dari server (jika diperlukan)
                    Snackbar.show({
                        text: response.message,
                        pos: 'top-center'
                    });
                },
                error: function(xhr, status, error) {
                    // Handle error (jika diperlukan)
                    console.error('Terjadi kesalahan saat menyimpan data:', error);
                }
            });
        });
        $('#simpanCatatan').on('click', function() {
            var absensiData = [];
            // Loop melalui elemen input dan tambahkan nilai ke dalam objek absensiData
            $('textarea[name="catatan[]"]').each(function(index) {
                var siswaId = $(this).data('siswa');
                var catatan = $(this).val();
                var id_absensi = $('input[name="idabsensi[]"]').eq(index).data('id');

                // Menambahkan data ke dalam objek absensiData
                var absensi = {
                    id_absensi: id_absensi,
                    id_siswa: siswaId,
                    catatan: catatan,

                };
                absensiData.push(absensi);
            });
            console.log(absensiData);
            //Kirim data absensiData ke server melalui AJAX
            $.ajax({
                url: '<?= base_url('penilaian/absensi/simpancatatan') ?>',
                method: 'POST',
                dataType: 'json',
                data: {
                    absensiData: absensiData
                },
                success: function(response) {
                    // Handle response dari server (jika diperlukan)
                    Snackbar.show({
                        text: response.message,
                        pos: 'top-center'
                    });
                },
                error: function(xhr, status, error) {
                    // Handle error (jika diperlukan)
                    console.error('Terjadi kesalahan saat menyimpan data:', error);
                }
            });
        });
        $('#rombelTable').dataTable({
            ajax: {
                url: '<?= base_url('penilaian/absensi/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=" btn btn-sm btn-outline-secondary">' + (row.total_sakit != null ? row.total_sakit : 0) + '</button>';
                    }
                },
                {
                    data: null,
                    render: function(data, type, row) {
                        return '<button class=" btn btn-sm btn-outline-warning">' + (row.total_ijin != null ? row.total_ijin : 0) + '</button>';
                    }
                },
                {
                    data: null,
                    render: function(data, type, row) {
                        return '<button class=" btn btn-sm btn-outline-danger">' + (row.total_alfa != null ? row.total_alfa : 0) + '</button>';
                    }
                },
                {
                    data: null,
                    render: function(data, type, row) {
                        var totalAbsensi = (
                            (row.total_sakit !== null ? parseInt(row.total_sakit) : 0) +
                            (row.total_ijin !== null ? parseInt(row.total_ijin) : 0) +
                            (row.total_alfa !== null ? parseInt(row.total_alfa) : 0)
                        );
                        return '<button class="absensi-btn btn btn-sm btn-outline-info" data-id="' + row.id + '">' + totalAbsensi + ' Absensi</button>';
                    }
                },
                {
                    data: null,
                    render: function(data, type, row) {
                        return '<button class="catatan-btn btn btn-sm btn-outline-success" data-id="' + row.id + '"> Catatan</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
        });

        // 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', '.absensi-btn', function() {
            var idrombel = $(this).data('id');
            $('#modalabsensi').modal('show');
            $('#id_rombel').val(idrombel);
            getpenilaian(idrombel);
        });
        $('#rombelTable').on('click', '.catatan-btn', function() {
            var idrombel = $(this).data('id');
            $('#modalcatatan').modal('show');
            $('#id_rombel').val(idrombel);
            getcatatan(idrombel);
        });
        $('#rombelTable').on('click', '.edit-btn', function() {
            var userId = $(this).data('id');
            edit(userId);
        });

        $('#modalabsensi').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 getpenilaian(idrombel) {
        $.ajax({
            url: '<?= base_url('penilaian/absensi/getsiswa/') ?>' + idrombel, // Ubah ini sesuai dengan URL endpoint Anda
            type: 'GET',
            dataType: "json",
            success: function(data) {
                var tbody = $('#table-absensi tbody');
                $("#alert").empty();
                tbody.empty();
                $.each(data, function(index, item) {
                    var no = index + 1;
                    var row = '<tr class="dataRow">' +
                        '<td>' + no + '<input type="hidden" data-id="' + item.id_absensi + '" name="idabsensi[]" ></td>' +
                        '<td>' + item.nama + '</td>' +
                        '<td>' + item.nama_rombel + '</td>' +
                        '<td><input type="text" data-siswa="' + item.id_siswa + '" class="input-nilai form-control form-control-sm" name="sakit[]" value="' + (item.sakit != null ? item.sakit : 0) + '"></td>' +
                        '<td><input type="text" data-siswa="' + item.id_siswa + '" class="input-nilai form-control form-control-sm" name="ijin[]" value="' + (item.ijin != null ? item.ijin : 0) + '"></td>' +
                        '<td><input type="text" data-siswa="' + item.id_siswa + '" class="input-nilai form-control form-control-sm" name="alfa[]" value="' + (item.alfa != null ? item.alfa : 0) + '"></td>' +
                        '</tr>';

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

    function getcatatan(idrombel) {
        $.ajax({
            url: '<?= base_url('penilaian/absensi/getsiswa/') ?>' + idrombel, // Ubah ini sesuai dengan URL endpoint Anda
            type: 'GET',
            dataType: "json",
            success: function(data) {
                var tbody = $('#table-catatan tbody');

                tbody.empty();
                $.each(data, function(index, item) {
                    var no = index + 1;
                    var row = '<tr class="dataRow">' +
                        '<td>' + no + '<input type="hidden" data-id="' + item.id_absensi + '" name="idabsensi[]" ></td>' +
                        '<td>' + item.nama + '</td>' +
                        '<td>' + item.nama_rombel + '</td>' +
                        '<td><textarea data-siswa="' + item.id_siswa + '" class="form-control form-control-sm" name="catatan[]" >' + item.catatan + '</textarea></td>' +
                        '</tr>';

                    tbody.append(row);
                });
            },
            error: function(xhr, status, error) {
                console.error(status, error);
                // Tindakan yang sesuai jika ada kesalahan dalam pengambilan 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="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);
                    }
                });

            }
        })

    }
</script>
<?= $this->endSection(); ?>