<?= $this->extend('Admin/Layout/app_layout'); ?>
<?= $this->section('content'); ?>
<div class="container-fluid">
    <div class="page-title">
        <div class="row">
            <div class="col-6">
                <h4>
                    Pengumuman </h4>
            </div>
            <div class="col-6">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="<?= base_url('home') ?>">
                            <svg class="stroke-icon">
                                <use href="<?= base_url() ?>assets/svg/icon-sprite.svg#stroke-home"></use>
                            </svg></a></li>
                    <li class="breadcrumb-item active">Pengumuman</li>
                </ol>
            </div>
        </div>
    </div>
</div>
<div class="container-fluid">
    <div class="row">
        <!-- HTML (DOM) sourced data  Starts-->
        <div class="col-sm-12">
            <div class="card">
                <div class="card-header card-no-border total-revenue">
                    <h4>Pengumuman List</h4>

                    <div class="card-header-right-icon">
                        <button type="button" onclick="add();" class="btn btn-primary"><i class="fa fa-plus"></i> Tambah</button>
                    </div>

                </div>
                <div class="card-body pt-0">
                    <div id="pengumuman-list">

                    </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">
                </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>Judul Pengumuman</label>
                        <input type="text" name="judul" class="form-control form-control-sm" required>
                        <div class="invalid-feedback">Judul Wajib diisi</div>
                    </div>
                    <div class="form-group mb-3">
                        <label>Pengumuman</label>
                        <div id="editor-container" style="height: 200px;"></div>
                        <input type="hidden" id="hidden-pengumuman" name="pengumuman">
                        <div class="invalid-feedback">Pengumuman Wajib diisi</div>
                    </div>
                    <div class="form-group mb-3">
                        <label>Status</label>
                        <select class="form-control form-control-sm" name="status" required>
                            <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>

<!-- Modal -->
<!-- Container-fluid Ends-->
<?= $this->endSection(); ?>
<?= $this->section('pagejs'); ?>
<script type="text/javascript">
    $(document).ready(function() {
        // Inisialisasikan Quill editor
        getPengumuman();
    });

    function getPengumuman() {
        $.ajax({
            url: '<?= base_url() ?>pengumuman/getdata',
            type: 'GET',
            success: function(response) {
                // Kosongkan pengumuman-list sebelum menambahkan pengumuman baru
                $('#pengumuman-list').empty();

                // Iterasi melalui setiap pengumuman dalam respons
                response.forEach(function(pengumuman) {
                    // Buat elemen card baru untuk setiap pengumuman
                    var cardHtml = '<div class="card-body">' +
                        '<div class="d-flex">' +
                        '<div class="m-r-20"><i class="fa fa-bullhorn fa-2x"></i></div>' +
                        '<div class="flex-grow-1">' +
                        '<h6 class="f-w-600"><a href="#">' + pengumuman.judul + '</a></h6>' +
                        '<button type="button" data-id="' + pengumuman.id + '" class="delete btn btn-outline-danger pull-right btn-xs m-l-5"><i class="fa fa-trash"></i> Hapus</button>' +
                        '<button type="button" data-id="' + pengumuman.id + '" class="edit btn btn-outline-warning pull-right btn-xs"><i class="fa fa-edit"></i> Edit</button>' +
                        '<p>' + pengumuman.created_at + '</p>' +
                        '</div>' +
                        '</div>' +
                        '<p>' + pengumuman.pengumuman + '</p>' +
                        '</div>';

                    // Tambahkan card HTML ke pengumuman-list
                    $('#pengumuman-list').append(cardHtml);
                });
            },
            error: function(xhr, status, error) {
                console.error('Terjadi kesalahan:', error);
            }
        });

    }

    // Tambahkan event listener untuk tombol delete
    $('#pengumuman-list').on('click', '.delete', function() {
        var pengumumanId = $(this).data('id');
        deletepengumumanData(pengumumanId);
    });
    $('#pengumuman-list').on('click', '.edit', function() {
        var pengumumanId = $(this).data('id');
        edit(pengumumanId);
    });


    var save_method; //for save method string
    var table;
    var quill = new Quill('#editor-container', {
        theme: 'snow' // Anda bisa memilih tema yang lain jika diinginkan
    });
    // Tambahkan event listener untuk menyimpan konten Quill editor ke dalam input hidden setiap kali terjadi perubahan
    quill.on('text-change', function() {
        var html = quill.root.innerHTML;
        document.getElementById('hidden-pengumuman').value = html;
    });

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

    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('pengumuman/edit') ?>/" + id,
            type: "GET",
            dataType: "JSON",
            success: function(data) {

                $('[name="id"]').val(data.id);
                $('[name="judul"]').val(data.judul);
                // $('[name="pengumuman"]').val(data.pengumuman);
                quill.root.innerHTML = data.pengumuman;
                $('[name="status"]').val(data.status);
                $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
                $('.modal-title').text('Edit pengumuman'); // 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('pengumuman/add') ?>";
        } else {
            url = "<?= base_url('pengumuman/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');
                        getPengumuman();
                        showToast(data.message);
                    } 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 {
                            showToast(data.message);
                        }
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    showToast(textStatus);
                }
            });
        }
    }

    function deletepengumumanData(pengumumanId) {
        swal({
            title: 'Are you sure?',
            text: "Yakin akan menghapus data ini!",
            icon: "warning",
            buttons: {
                cancel: "Batal",
                text: "Ya Hapus!",
            },
            dangerMode: true,
        }).then((result) => {
            if (result) {
                $.ajax({
                    url: '<?= base_url('pengumuman/delete/') ?>' + pengumumanId, // Sesuaikan dengan URL Controller Anda
                    type: 'DELETE',
                    success: function(response) {
                        // Reload DataTable setelah penghapusan berhasil
                        getPengumuman();
                    },
                    error: function(error) {
                        console.error('Error deleting pengumuman:', error);
                    }
                });
            }
        })

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