<?= $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="">Tujuan Pembelajaran</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="tujuanTable" class="display">
                            <thead>
                                <tr>
                                    <th class="text-center">
                                        #
                                    </th>
                                    <th>Mata Pelajaran</th>
                                    <th>Rombel</th>
                                    <th>Guru</th>
                                    <th>Tujuan</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>Mata Pelajaran</label>
                        <input type="text" name="mapel" class="form-control form-control-sm" required>
                        <div class="invalid-feedback">Nama Wajib diisi</div>
                    </div>
                    <div class="form-group mb-3">
                        <label for="tujuan">Tujuan Pembelajaran</label>
                        <textarea class="form-control" name="tujuan" id="tujuan" rows="3"></textarea>
                    </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="modalcopytujuan" 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 Tujuan 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="tujuancopy">Pilih Rombel</label>
                    <select class="form-control" name="tujuancopy" id="tujuancopy" 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="modaltujuan" role="dialog" aria-labelledby="modelTitleId" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Tujuan 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-pembelajaran">
                <div class="modal-body">
                    <input type="hidden" class="form-control form-control-sm" id="idpembelajaran" name="idpembelajaran">
                    <input type="hidden" class="form-control form-control-sm" id="idrombel" name="idrombel">
                    <input type="hidden" class="form-control form-control-sm" id="idmapel" name="idmapel">
                    <div id="inputrow-container">
                        <div class="input-row row mb-3">
                            <input type="hidden" class="form-control form-control-sm" name="id[]">
                            <div class="col-8">
                                <textarea class="form-control form-control-sm tujuan" name="tujuan[]" rows="2" placeholder="Masukan tujuan pembelajaran tanpa kata Peserta didik dapat" required></textarea>
                            </div>
                            <div class="col-3">
                                <select class="form-control form-control-sm status" name="status[]" required>
                                    <option value="aktif">aktif</option>
                                    <option value="tidak">tidak aktif</option>
                                </select>
                            </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 Tujuan</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="btnSaveTujuan" class="btn btn-primary">Save</button>
                </div>
            </form>

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

<?= $this->endSection(); ?>
<?= $this->section('pagejs'); ?>
<script type="text/javascript">
    $(document).ready(function() {
        $('#copy-item').on('click', function() {

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

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

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

            // Menampilkan modal copy pembelajaran
            $('#modalcopytujuan').modal('show');
        });
        $('#btnSaveTujuan').click(function() {
            // Mengambil data dari form
            var formData = $('#form-pembelajaran').serialize();
            var idpembelajaran = $('#idpembelajaran').val();

            // Validasi formulir
            var isValid = true;

            $('.tujuan, .status').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/tujuan/add'); ?>",
                data: formData,
                dataType: "json",
                success: function(response) {
                    if (response.success) {
                        gettujuan(idpembelajaran);
                        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('textarea, 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();
            });
        });
        $('#tujuanTable').dataTable({
            ajax: {
                url: '<?= base_url('referensi/tujuan/getpembelajaran') ?>', // 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_matapelajaran'
                },
                {
                    data: 'nama_rombel'
                },
                {
                    data: 'nama_guru'
                },

                {
                    data: null,
                    render: function(data, type, row) {
                        return '<button class="tujuan-btn btn-rounded btn btn-outline-secondary" data-rombel="' + row.id_rombel + '" data-mapel="' + row.id_matapelajaran + '" data-id="' + row.id + '">' + row.jumlah_tp + ' Tujuan</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
        });


        $('#tujuanTable').on('click', '.tujuan-btn', function() {
            var id = $(this).data('id');
            var idmapel = $(this).data('mapel');
            var idrombel = $(this).data('rombel');
            $('#modaltujuan').modal('show');
            $('#idpembelajaran').val(id);
            $('#idmapel').val(idmapel);
            $('#idrombel').val(idrombel);
            $('#inputrow-container').find('textarea, input').val('');
            gettujuan(id); //

        });
        $('#inputrow-container').on('click', '.delete-tujuan', function() {
            var id = $(this).data('id');
            deleteTujuan(id);
        });
        $('#modaltujuan').on('hidden.bs.modal', function() {
            $('#tujuanTable').DataTable().ajax.reload();
        });
    });
    getrombel();

    function getrombel() {
        $.ajax({
            url: '<?= base_url('referensi/tujuan/getpembelajaran') ?>',
            type: 'GET',
            success: function(response) {
                response = response.data;
                // Mengisi pilihan dalam elemen select dengan data yang diterima
                var select = $('#tujuancopy');
                // 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].nama_matapelajaran + '</option>');
                }
            },
            error: function() {
                console.log('Gagal mendapatkan data.');
            }
        });
    }
    var save_method; //for save method string
    var table;

    function gettujuan(id) {
        $.ajax({
            url: '<?= base_url('referensi/tujuan/gettujuan/') ?>' + id,
            type: 'GET',
            dataType: 'json',
            success: function(data) {
                $('#inputrow-container').empty();
                if (data == "") {
                    var inputRow = '<div class="input-row row mb-3">' +
                        '<input type="hidden" class="form-control form-control-sm" name="id[]">' +
                        '<div class="col-8">' +
                        '<textarea class="form-control form-control-sm" name="tujuan[]" rows="2" placeholder=""></textarea>' +
                        '</div>' +
                        '<div class="col-3">' +
                        '<select class="form-control form-control-sm" name="status[]">' +
                        '<option value="aktif">aktif</option>' +
                        '<option value="tidak">tidak aktif</option>' +
                        '</select>' +
                        '</div>' +
                        '<div class="col-1">' +
                        '<a class="delete-row delete-tujuan" 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);
                }

                $.each(data, function(index, item) {
                    var inputRow = '<div class="input-row row mb-3">' +

                        '<input type="hidden" class="form-control form-control-sm" name="id[]" value="' + item.id + '">' +

                        '<div class="col-8">' +
                        '<textarea class="form-control form-control-sm" name="tujuan[]" rows="2" placeholder="">' + item.tujuan + '</textarea>' +
                        '</div>' +
                        '<div class="col-3">' +
                        '<select class="form-control form-control-sm" name="status[]">' +
                        '<option value="aktif"' + (item.status === 'aktif' ? ' selected' : '') + '>aktif</option>' +
                        '<option value="tidak"' + (item.status === 'tidak' ? ' selected' : '') + '>tidak aktif</option>' +
                        '</select>' +
                        '</div>' +
                        '<div class="col-1">' +
                        '<a class="delete-row delete-tujuan" 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

                });
            }
        });
    }

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

    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/tujuan/edit') ?>/" + id,
            type: "GET",
            dataType: "JSON",
            success: function(data) {
                // console.log(data);
                $('[name="id"]').val(data.id);
                $('[name="kode"]').val(data.kode_tujuan);
                $('[name="nama"]').val(data.nama_tujuan);
                $('[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/tujuan/add') ?>";
        } else {
            url = "<?= base_url('referensi/tujuan/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');
                        $('#tujuanTable').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 deleteTujuan(Id) {
        var idpembelajaran = $('#idpembelajaran').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/tujuan/delete/') ?>' + Id, // Sesuaikan dengan URL Controller Anda
                    type: 'DELETE',
                    success: function(response) {
                        Snackbar.show({
                            text: 'berhasil dihapus',
                            pos: 'top-center'
                        });
                        gettujuan(idpembelajaran);
                    },
                    error: function(error) {
                        console.error('Error deleting user:', error);
                    }
                });
            }
        })
    }

    function prosescopy() {
        var pembelajaran2 = $('#idpembelajaran').val();
        var idrombel = $('#idrombel').val();
        // Mendapatkan nilai rombel yang dipilih
        var pembelajaran1 = $('#tujuancopy').val();

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