<?= $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="">Perencanaan Projek</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="projekTable" class="display">
                            <thead>
                                <tr>
                                    <th class="text-center">
                                        #
                                    </th>
                                    <th>Rombel</th>
                                    <th>Tema</th>
                                    <th>Nama Projek</th>
                                    <th>Deskripsi</th>
                                    <th>Action</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 modal-lg" 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 row align-items-center mb-3">
                        <label class="form-control-label col-sm-3 text-md-right" for="tema">Tema Projek</label>
                        <div class="col-sm-6 col-md-9">
                            <select class="form-control form-control-sm" name="tema" id="tema">
                                <option value="">Pilih Tema</option>
                                <?php foreach ($tema as $tema) { ?>
                                    <option value="<?= $tema->id ?>"> <?= $tema->nama_tema ?> </option>
                                <?php } ?>
                            </select>
                        </div>
                    </div>
                    <div class="form-group row align-items-center mb-3">
                        <label class="form-control-label col-sm-3 text-md-right" for="rombel">Pilih Rombel</label>
                        <div class="col-sm-6 col-md-9">
                            <select class="form-control form-control-sm" name="rombel" id="rombel">
                                <option value="">Pilih Rombel</option>
                                <?php foreach ($rombel as $rombel) { ?>
                                    <option value="<?= $rombel->id ?>"> <?= $rombel->nama_rombel ?> </option>
                                <?php } ?>
                            </select>
                        </div>
                    </div>
                    <div class="form-group row align-items-center mb-3">
                        <label class="form-control-label col-sm-3 text-md-right">Nama Projek</label>
                        <div class="col-sm-6 col-md-9">
                            <input type="text" name="nama" class="form-control form-control-sm" required>
                            <div class="invalid-feedback">Nama Wajib diisi</div>
                        </div>
                    </div>

                    <div class="form-group row align-items-center mb-3">
                        <label class="form-control-label col-sm-3 text-md-right">Deskripsi Projek</label>
                        <div class="col-sm-6 col-md-9">
                            <input type="text" name="deskripsi" class="form-control form-control-sm" required>
                            <div class="invalid-feedback">Deskripsi Wajib diisi</div>
                        </div>
                    </div>
                    <!-- <div class="form-group mb-3">
                        <label for="fase">Pilih Fase</label>
                        <select class="form-control form-control-sm" name="fase" id="fase">
                           <option value="A">Fase A (Tingkat 1-2)</option>
                           <option value="B">Fase B (Tingkat 3-4)</option>
                           <option value="C">Fase C (Tingkat 5-6)</option>
                           <option value="D">Fase D (Tingkat 7-9)</option>
                           <option value="E">Fase E (Tingkat 10-12)</option>
                        </select>
                    </div> -->
                    <div class="form-group mb-3">
                        <label for="dimensi">Pilih Dimensi</label>
                        <select class="form-control form-control-sm" multiple name="dimensi[]" id="dimensi">

                        </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>


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

        $('#projekTable').dataTable({
            ajax: {
                url: '<?= base_url('projek/perencanaan/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: 'nama_tema'
                },
                {
                    data: 'nama_projek'
                },
                {
                    data: 'deskripsi'
                },
                {
                    data: null,
                    render: function(data, type, row) {
                        return '<a href="javascript:void(0)" class="edit-btn" data-id="' + row.id_projek + '"><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_projek + '"><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": [7, 10, 20, 50],
            "pageLength": 10
        });

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

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

    function getdimensi2(callback) {
        if (!cekselect) {
            var url = '<?= base_url('projek/perencanaan/getdimensi') ?>';
            $.ajax({
                url: url,
                method: 'GET',
                dataType: 'json',
                success: function(json) {
                    // Atur nilai default pada TomSelect berdasarkan nilai tambah_iddimensi
                    selectDimensi = new TomSelect('#dimensi', {
                        valueField: 'id',
                        labelField: 'dimensi',
                        searchField: ['dimensi', 'elemen', 'deskripsi'],
                        options: json,
                        items: [], // Jika tidak ada nilai tambah_iddimensi, gunakan array kosong
                        render: {
                            option: function(item, escape) {
                                return `<div class="py-2 d-flex">
                                <div>
                                    <div class="mb-1">
                                        <span class="h5">${ escape(item.dimensi) }</span>
                                        <span class="text-muted">Fase : ${ escape(item.fase) } Elemen : ${ escape(item.elemen) }</span>
                                    </div>
                                    <span class="h6">${ escape(item.subelemen) } </span>
                                    <div class="description">${ escape(item.deskripsi) }</div>
                                </div>
                            </div>`;
                            },
                            item: function(item, escape) {
                                return `<div class="py-2 d-flex">
                                <div>
                                    <div class="mb-1">
                                        <span class="h4">${ escape(item.dimensi) }</span>
                                        <span class="text-muted">Fase : ${ escape(item.fase) } Elemen : ${ escape(item.elemen) }</span>
                                    </div>
                                    <span class="h6">${ escape(item.subelemen) } </span>
                                    <div class="description">${ escape(item.deskripsi) }</div>
                                </div>
                            </div>`;
                            }
                        }
                    });

                    cekselect = true;
                    callback(); // Panggil callback untuk menandakan bahwa selectDimensi sudah siap
                },
                error: function(xhr, status, error) {
                    console.error('There was a problem with the fetch operation:', error);
                }
            });
        }
    }

    function getdimensi(iddimensi) {

        if (!cekselect) {
            var selectDimensi = new TomSelect('#dimensi', {
                valueField: 'id',
                labelField: 'dimensi',
                searchField: ['dimensi', 'elemen'],
                // fetch remote data
                load: function(query, callback) {
                    var url = '<?= base_url('projek/perencanaan/getdimensi') ?>';
                    fetch(url)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Network response was not ok');
                            }
                            return response.json();
                        })
                        .then(json => {
                            console.log('Data yang diterima:', json); // Tambahkan ini untuk melihat data yang diterima
                            callback(json);
                            selectDimensi.setValue(iddimensi ? iddimensi.split(',') : []);
                        })
                        .catch(error => {
                            console.error('There was a problem with the fetch operation:', error);
                            callback(); // Atau bisa juga callback([]) tergantung dari kebutuhan Anda
                        });
                },
                // custom rendering functions for options and items
                render: {
                    option: function(item, escape) {

                        return `<div class="py-2 d-flex">
							<div>
								<div class="mb-1">
									<span class="h5">
										${ escape(item.dimensi) }
									</span>
									<span class="text-muted">Elemen : ${ escape(item.elemen) }</span>
								</div>
                                <span class="h6">${ escape(item.subelemen) } </span>
						 		<div class="description">${ escape(item.deskripsi) }</div>
							</div>
						</div>`;
                    },
                    item: function(item, escape) {
                        return `<div class="py-2 d-flex">
							<div>
								<div class="mb-1">
									<span class="h4">
										${ escape(item.dimensi) }
									</span>
									<span class="text-muted">Elemen : ${ escape(item.elemen) }</span>
								</div>
                                <span class="h6">${ escape(item.subelemen) } </span>
						 		<div class="description">${ escape(item.deskripsi) }</div>
							</div>
						</div>`;
                    }
                },

            });
            cekselect = true;
        }



    }

    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(); ?>