<?= $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>
                    Data User </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">Data User</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 pb-0 card-no-border ">
                    <!-- <h4 class="mb-3">HTML (DOM) sourced data</h4> -->
                    <div class="d-flex justify-content-end">
                        <button type="button" onclick="add()" class="btn btn-primary"><i class="fa fa-plus"></i> Tambah</button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive custom-scrollbar">
                        <table class="table" id="userTable" style="width:100%">
                            <thead>
                                <tr>
                                    <th class="text-center">
                                        #
                                    </th>
                                    <th>NIP</th>
                                    <th>Nama User</th>
                                    <th>Username</th>
                                    <th>Role</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="modalimport" 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">Import Excel</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>

            </div>
            <div class="modal-body">
                <input type="file" id="xlsx_file" accept=".xlsx"></br>
                <a href="#" class="badge badge-primary mt-3">Download Template</a>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" id="importbtn" class="btn btn-primary">Save</button>
            </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>NIP</label>
                        <input type="text" name="nip" class="form-control form-control-sm" required>
                        <div class="invalid-feedback">NIP Wajib diisi</div>
                    </div>

                    <div class="form-group mb-3">
                        <label>Nama Lengkap</label>
                        <input type="text" name="nama" class="form-control form-control-sm" required>
                        <div class="invalid-feedback">Nama Wajib diisi</div>
                    </div>
                    <div class="form-group mb-3">
                        <label>Username</label>
                        <input type="text" name="username" class="form-control form-control-sm" required>
                        <div class="invalid-feedback">Username Wajib diisi</div>
                    </div>
                    <div class="form-group mb-3">
                        <label>Password</label>
                        <input type="password" name="password" class="form-control form-control-sm" required>
                        <div class="invalid-feedback"></div>
                    </div>
                    <div class="form-group mb-3">
                        <label>Role Akun</label>
                        <select class="form-control form-control-sm select2" multiple="" name="role[]" id="selectrole">
                            <option value="admin">administrator</option>

                        </select>
                    </div>
                    <div class="form-group mb-3">
                        <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>

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

        $('#userTable').dataTable({
            ajax: {
                url: '<?= base_url('user/getUsers') ?>', // 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: 'nip'
                },
                {
                    data: 'nama'
                },
                {
                    data: 'username'
                },
                {
                    data: 'role',
                    render: function(data) {
                        var roles = data.split(','); // Pisahkan string menjadi array berdasarkan koma
                        var badgeHTML = ''; // String kosong untuk menampung HTML badge
                        // Loop melalui setiap role dan ubah menjadi badge
                        roles.forEach(function(role) {
                            badgeHTML += '<span class="badge badge-primary">' + role.trim() + '</span>&nbsp;';
                            // Di sini, badge warna biru digunakan untuk setiap role
                        });
                        return badgeHTML; // Kembalikan HTML badge yang sudah dibuat
                    }
                },
                {
                    data: 'status',
                    render: function(data) {
                        // Gunakan badge untuk menunjukkan status
                        return (data === 'aktif') ? '<span class="badge badge-success">Aktif</span>' : '<span class="badge badge-danger">Tidak Aktif</span>';
                    }
                },

                {
                    data: null,
                    render: function(data, type, row) {
                        return '<a href="javascript:void(0)" class="text-success edit-btn" data-id="' + row.id + '"><i class="fa fa-edit fa-2x"></i></a>  <a href="javascript:void(0)" class="text-danger delete-btn" data-id="' + row.id + '"><i class="fa fa-trash fa-2x"></i></a>';
                    }
                }
            ],

            "lengthMenu": [7, 10, 20, 50],
            "pageLength": 10
        });

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

        $('#importbtn').on('click', function() {
            var fileInput = $('#xlsx_file')[0].files[0];
            var formData = new FormData();
            formData.append('xlsx_file', fileInput);

            $.ajax({
                url: '<?= base_url('user/import') ?>',
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function(response) {
                    $('#modalimport').modal('hide');
                    $('#userTable').DataTable().ajax.reload();
                    showToast(response.message);
                },
                error: function() {
                    $('#message').text('Terjadi kesalahan. Silakan coba lagi.');
                }
            });
        });
    });
    var save_method; //for save method string
    var table;

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

    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('user/edit') ?>/" + id,
            type: "GET",
            dataType: "JSON",
            success: function(data) {
                var datarole = data.role.split(',').map(function(item) {
                    return item.trim(); // Hilangkan spasi di sekitar nilai jika ada
                });

                $('[name="id"]').val(data.id);
                $('[name="nama"]').val(data.nama);
                $('[name="nip"]').val(data.nip);
                $('[name="username"]').val(data.username);
                $('[name="status"]').val(data.status);
                $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
                $('.modal-title').text('Edit User'); // 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('user/add') ?>";
        } else {
            url = "<?= base_url('user/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 {
            console.log($('#form').serialize());
            $.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');
                        $('#userTable').DataTable().ajax.reload();
                        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 deleteUserData(userId) {
        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('user/delete/') ?>' + userId, // Sesuaikan dengan URL Controller Anda
                    type: 'DELETE',
                    success: function(response) {
                        // Reload DataTable setelah penghapusan berhasil
                        $('#userTable').DataTable().ajax.reload();
                    },
                    error: function(error) {
                        console.error('Error deleting user:', error);
                    }
                });
            }
        })

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