<?= $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="">Penilaian Projek</h5>

                </div>

                <div class="widget-content">

                    <div class="d-flex justify-content-end mb-3">
                        <div class="form-group col-md-2 col-6">
                            <select class="form-control form-control-sm" name="rombel" id="rombel">

                            </select>
                        </div>&nbsp;&nbsp;
                        <button id="simpannilai" type="button" class="btn btn-primary"><i data-feather="save"></i> <span class="btn-text-inner">Simpan</span></button>
                    </div>
                    <div class="table-responsive">
                        <div id="table-container"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>


<?= $this->endSection(); ?>
<?= $this->section('pagejs'); ?>
<script type="text/javascript">
    $(document).ready(function() {
        getrombel();

        function getrombel() {
            $.ajax({
                url: '<?= base_url('projek/penilaian/getrombel') ?>',
                type: 'GET',
                success: function(response) {
                    // Mengisi pilihan dalam elemen select dengan data yang diterima
                    var select = $('#rombel');
                    // 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 + '</option>');
                    }
                },
                error: function() {
                    console.log('Gagal mendapatkan data.');
                }
            });
        }
        $("#simpannilai").hide();
        $('#rombel').change(function() {
            var id_rombel = $(this).val();
            console.log(id_rombel);
            if (id_rombel == '') {
                $("#simpannilai").hide();
            } else {
                gettablepenilaian(id_rombel);
                $("#simpannilai").show();
            }

        });
        $('#simpannilai').click(function(e) {
            e.preventDefault(); // Menghentikan aksi default tombol "btn-save"
            var nilaiArray = [];
            $('select[name="nilai[]"]').each(function() {
                var id_siswa = $(this).data('siswa');
                var id_dimensi = $(this).data('dimensi');
                var id_projek = $(this).data('projek');
                var nilai = $(this).val(); // Ambil nilai dari input
                nilaiArray.push({
                    id_dimensi: id_dimensi,
                    id_siswa: id_siswa,
                    id_projek: id_projek,
                    nilai: nilai
                });
            });

            console.log(nilaiArray);
            $.ajax({
                url: '<?= base_url('projek/penilaian/save') ?>',
                type: 'POST',
                dataType: 'json',
                data: {
                    nilai: nilaiArray,
                },
                success: function(response) {
                    Snackbar.show({
                        text: response.message,
                        pos: 'top-center'
                    });

                },
                error: function(xhr, status, error) {
                    console.error(status, error); // Handle error jika terjadi
                }
            });


        });


        function gettablepenilaian(id_rombel) {
            $.ajax({
                url: "<?= base_url() ?>projek/penilaian/getpenilaian/" + id_rombel,
                type: "GET",
                dataType: "json",
                success: function(data) {
                    $('#table-container').empty();
                    // Membuat tabel dari data JSON
                    var table = $('<table>').addClass('table table-bordered');
                    var thead = $('<thead>').appendTo(table);
                    var tbody = $('<tbody>').appendTo(table);

                    // Menambahkan header tabel
                    var headerRow = $('<tr>').appendTo(thead);
                    $('<th>').text('Nama').appendTo(headerRow);
                    $('<th>').text('Rombel').appendTo(headerRow);
                    $('<th>').text('Projek').appendTo(headerRow);

                    // Menambahkan baris untuk setiap siswa
                    data.forEach(function(siswa) {
                        var row = $('<tr>').appendTo(tbody);
                        $('<td>').text(siswa.nama).appendTo(row);
                        $('<td>').text(siswa.nama_rombel).appendTo(row);

                        // Menambahkan projek untuk setiap siswa
                        var projekCell = $('<td>').appendTo(row);


                        // Menambahkan baris untuk setiap projek
                        siswa.projek.forEach(function(projek) {
                            $('<span>').text('Nama Projek: ' + projek.nama_projek).appendTo(projekCell);
                            var nilaiDimensiList = $('<ul>').addClass('list-group mb-2').appendTo(projekCell);
                            projek.nilai_dimensi.forEach(function(nilaiDimensi) {
                                var nilaiDimensiItem = $('<li>').addClass('list-group-item').appendTo(nilaiDimensiList);
                                $('<span>').text('Dimensi: ' + nilaiDimensi.dimensi).appendTo(nilaiDimensiItem);
                                // Menambahkan opsi ke select list
                                var selectList = $('<select>').addClass('form-select form-select-sm').attr({
                                    'name': 'nilai[]',
                                    'data-siswa': siswa.id_siswa,
                                    'data-dimensi': nilaiDimensi.id_dimensi, // Menambahkan atribut data-id
                                    'data-projek': projek.id_projek // Menambahkan atribut data-id
                                }).appendTo(nilaiDimensiItem); // Menambahkan opsi ke select list
                                $('<option>').val('').text('Pilih Nilai').appendTo(selectList);
                                $('<option>').val('B').text('Mulai Berkembang').prop('selected', nilaiDimensi.nilai === 'B').appendTo(selectList);
                                $('<option>').val('SB').text('Sedang Berkembang').prop('selected', nilaiDimensi.nilai === 'SB').appendTo(selectList);
                                $('<option>').val('BSH').text('Berkembang Sesuai Harapan').prop('selected', nilaiDimensi.nilai === 'BSH').appendTo(selectList);
                                $('<option>').val('SSB').text('Sangat Berkembang').prop('selected', nilaiDimensi.nilai === 'SSB').appendTo(selectList);
                            });
                        });
                    });

                    // Menambahkan tabel ke dalam dokumen
                    table.appendTo('#table-container');
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.error('Error:', errorThrown);
                }
            });
        }

    });
    var save_method; //for save method string
    var table;
    var cekselect = false;
    var selectDimensi; // Deklarasikan variabel selectDimensi di luar fungsi


    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 projek');
        getdimensi2(function() {
            // Callback akan dipanggil ketika selectDimensi sudah siap

        });
        if (selectDimensi) {
            selectDimensi.setValue([]);
        }
    }

    function edit(id) {
        save_method = 'update';
        $('#form')[0].reset(); // reset form on modals
        <?php header('Content-type: application/json'); ?>
        //Ajax Load data from ajax
        $.ajax({
            url: "<?php echo site_url('projek/perencanaan/getid') ?>/" + id,
            type: "GET",
            dataType: "JSON",
            success: function(data) {
                var dimensi = data.id_dimensi.split(',').map(function(item) {
                    return item.trim(); // Hilangkan spasi di sekitar nilai jika ada
                });
                if (selectDimensi) {
                    selectDimensi.clear();
                    selectDimensi.setValue(dimensi);
                } else {
                    getdimensi2(function() {
                        // Callback akan dipanggil ketika selectDimensi sudah siap
                        if (selectDimensi) {
                            selectDimensi.setValue(dimensi);
                        }
                    });
                }
                // console.log(data);
                $('[name="id"]').val(data.id);
                $('[name="tema"]').val(data.tema);
                $('[name="rombel"]').val(data.id_rombel);
                $('[name="nama"]').val(data.nama_projek);
                $('[name="deskripsi"]').val(data.deskripsi);
                $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
                $('.modal-title').text('Edit Projek'); // 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('projek/perencanaan/add') ?>";
        } else {
            url = "<?= base_url('projek/perencanaan/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');
                        $('#projekTable').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(xhr, status, error) {
                    console.error('There was a problem with the fetch operation:', error);
                }
            });
        }
    }

    function deleteUserData(userId) {
        Swal.fire({
            title: 'Are you sure?',
            text: "ini akan menghapus data dan semua nilai projek yang berkaitan!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '<?= base_url('projek/perencanaan/delete/') ?>' + userId, // Sesuaikan dengan URL Controller Anda
                    type: 'DELETE',
                    success: function(response) {
                        // Reload DataTable setelah penghapusan berhasil
                        $('#projekTable').DataTable().ajax.reload();
                        Snackbar.show({
                            text: response.message,
                            pos: 'top-center'
                        });
                    },
                    error: function(error) {
                        console.error('Error deleting user:', error);
                    }
                });

            }
        })

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