<link rel="stylesheet" href="<?php echo e(asset('public/assets/css/datatables/jquery.dataTables.min.css')); ?>">
<style>
    .user_privillage {
        padding: 10px;
    }
</style>

<?php $__env->startSection('content'); ?>
    <section>
        <div class="col-lg-8 col-md-8 col-sm-12" style="margin: 10px;">
            <div class="card shadow">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <h2><b>Set User Privilege(s)</b></h2>
                            <span>For <?php echo e($system_user->firstname); ?> <?php echo e($system_user->lastname); ?> </span>
                        </div>


                    </div>
                    <div>
                        <div class="d-flex align-items-center mb-3">
                            <select class="form-control select user_privillage mr-2" multiple="multiple"
                                name="user_privillage[]" id="user_privillage" required>
                                <?php   foreach ($user_privillages as $key => $value):?>
                                <option value="<?php echo e($key); ?>"><?php echo e($value); ?></option>
                                <?php endforeach ?>
                            </select>
                            <button class="btn bg-primary ms-2 text-white" onclick="addPrivillage()">Add</button>
                             <button class="btn bg-secondary ms-2" style="width: 100px;" onclick="addAllPrivilleges()">Add All</button>
                        </div>
                    </div>
                    <table class="table table-bordered table-hover mb-0">
                        <thead>
                            <tr>
                                <th>Privillage</th>
                                <th style="width: 100px;">Action</th>
                            </tr>
                        </thead>
                        <tbody id="user_privillages">

                        </tbody>
                    </table>

                    <div class="d-flex justify-content-end align-items-center mt-3">
                        <button class="btn btn-danger text-white me-1" onclick="resetPrivillages()"><i
                                class="fas fa-undo mr-1"></i>Reset Privillages</button>
                        <button class="btn btn-primary text-white " id="submit_btn" onclick="savePrivillages();">
                            <div id="save-privillages">
                                <i class="fas fa-save me-1"></i> Save Changes
                            </div>
                            <div id="progress-indicator" style="display: none;">
                                <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                                Saving...
                            </div>
                        </button>

                    </div>
                </div>
            </div>
        </div> <!-- Bordered table -->
    </section>
<?php $__env->stopSection(); ?>

<script src="<?php echo e(asset('public/assets/js/jquery.min.js')); ?>"></script>
<script src="<?php echo e(asset('public/assets/js/datatables/jquery.dataTables.min.js')); ?>"></script>

<script>
    let privillages = [];
    let user_privillages = [];
    let submitBtn;
    $(document).ready(function() {
        $('#dataTable-1').DataTable();

        $(function() {
            $('select').select2({
                placeholder: "Select a privillage",
                allowClear: true
            });
        });

        $("#save-privillages").show();
        $("#progress-indicator").remove();
        let system_user = <?php echo json_encode($system_user); ?>;
        user_privillages = <?php echo json_encode($user_privillages); ?>;
        submitBtn = document.getElementById('submit_btn');
        privillages = JSON.parse(system_user['privillages']);
        renderTable(privillages);

        $('#user_privillages').on('click', 'button', function(e) {
            Swal.fire({
                title: 'Info',
                text: 'Do you want to remove privillage?',
                icon: 'question',
                confirmButtonText: 'Yes',
                showCancelButton: true,
                cancelButtonText: 'No',
                confirmButtonColor: '#1cc88a',
                cancelButtonColor: '#d33',

            }).then((result) => {
                if (result.isConfirmed) {
                    let id = $(this).attr('id');
                    privillages = privillages.filter(p => p['id'] != id);
                    renderTable(privillages);
                }
            });

        });
    });

    function addPrivillage() {
        var selectedValue = $("#user_privillage").val();
        selectedValue.forEach((value, value_index) => {
            let value_ = user_privillages[value];
            let obj = {
                id: value,
                value: value_
            }

            let p_index = privillages.findIndex(p => p['id'] == value);
            if (p_index == -1) {
                privillages.push(obj);
                renderTable(privillages);
            }

            if (value_index == selectedValue.length - 1) {
                $("#user_privillage").val('').trigger('change')
            }
        });
    }
    
    
function addAllPrivilleges() {
    privillages = [];
    let privillege_keys = Object.keys(user_privillages);
    privillege_keys.forEach((key, key_index) => {
        let value_ = user_privillages[key];
        let obj = {
            id: key,
            value: value_
        }
        privillages.push(obj);
        if (key_index == (privillege_keys.length - 1)) {
            renderTable(privillages);
        }
    });
}

    function renderTable(privillages__) {
        $('#user_privillages td').parent().remove();
        privillages__.forEach((privillage, privillage_index) => {
            let tb = $('#user_privillages');
            let tr = $(`<tr id="${privillage.id}"></tr>`);
            let privillage_ = $('<td>' + privillage.value + '</td>');
            let deleteButton = $(
                `<td><button class="btn btn-sm d-flex align-items-center delete_btn" id="${privillage.id}" name="${privillage.id}" style="background-color: crimson; color: white;"> <i class="fa fa-trash text-white me-1"></i> Remove</button></td>`
            );
            tr.append(privillage_);
            tr.append(deleteButton);
            tb.append(tr);
        })


    }


    $(".delete_btn").click(function() {
        alert("Handler for .click() called.");
    });

    function alterPrivillage() {
        if ($('.custom-control-input').is(":checked")) {
            console.log('Checked');
        } else {
            console.log('Not checked');
        }
        // console.log(this.id, value);
    }


    function savePrivillages() {
        let privillages_ = JSON.stringify(privillages);
        let system_user = <?php echo json_encode($system_user); ?>;
        const csrfToken = document.head.querySelector("[name~=csrf-token][content]").content;
        Swal.fire({
            title: 'Info',
            text: 'Do you want to save privillages?',
            icon: 'question',
            confirmButtonText: 'Yes',
            showCancelButton: true,
            cancelButtonText: 'No',
            confirmButtonColor: '#1cc88a',
            cancelButtonColor: '#d33',

        }).then((result) => {
            if (result.isConfirmed) {
                submitBtn.disabled = true;
                $("#save-privillages").remove();
                $("#progress-indicator").show();
                $.ajax({
                    url: `<?php echo e(url('/set-user-privillages')); ?>`,
                    method: 'POST',
                    data: {
                        user_id: system_user['id'],
                        privillages: privillages_,
                        _token: csrfToken
                    },
                    success: function(result_) {
                        $("#save-privillages").show();
                        $("#progress-indicator").remove();
                        Swal.fire({
                            title: 'Info',
                            text: result_ == 'success' ?
                                'Privillages has been saved successfully!' :
                                'Privillages could not be saved!',
                            icon: result_,
                            confirmButtonText: 'Okay',
                            confirmButtonColor: '#1cc88a'

                        }).then((result) => {

                            let url = window.location.href;
                            if (url.includes('edit-product')) {
                                window.location = `<?php echo e(url('/dashboard')); ?>`;
                                localStorage.setItem('product-information', '');
                            } else {
                                location.reload();
                            }
                        })
                    }
                });

            } else if (result.isDenied) {
                submitBtn.disabled = false;
                $("#save-privillages").show();
                $("#progress-indicator").remove();
                Swal.fire('Changes are not saved', '', 'info')
            }
        });
    }

    function resetPrivillages() {
        let privillages_ = JSON.stringify([]);
        let system_user = <?php echo json_encode($system_user); ?>;
        const csrfToken = document.head.querySelector("[name~=csrf-token][content]").content;
        Swal.fire({
            title: 'Info',
            text: 'Do you want to reset privillages?',
            icon: 'question',
            confirmButtonText: 'Yes',
            showCancelButton: true,
            cancelButtonText: 'No',
            confirmButtonColor: '#1cc88a',
            cancelButtonColor: '#d33',

        }).then((result) => {
            if (result.isConfirmed) {
                submitBtn.disabled = true;
                $("#save-privillages").remove();
                $("#progress-indicator").show();
                $.ajax({
                    url: `<?php echo e(url('/set-user-privillages')); ?>`,
                    method: 'POST',
                    data: {
                        user_id: system_user['id'],
                        privillages: privillages_,
                        _token: csrfToken
                    },
                    success: function(result_) {
                        $("#save-privillages").show();
                        $("#progress-indicator").remove();
                        Swal.fire({
                            title: 'Info',
                            text: result_ == 'success' ?
                                'Privillages has been saved successfully!' :
                                'Privillages could not be saved!',
                            icon: result_,
                            confirmButtonText: 'Okay',
                            confirmButtonColor: '#1cc88a'

                        }).then((result) => {

                            let url = window.location.href;
                            if (url.includes('edit-product')) {
                                window.location = `<?php echo e(url('/dashboard')); ?>`;
                                localStorage.setItem('product-information', '');
                            } else {
                                location.reload();
                            }
                        })
                    }
                });

            } else if (result.isDenied) {
                submitBtn.disabled = false;
                $("#save-privillages").show();
                $("#progress-indicator").remove();
                Swal.fire('Changes are not saved', '', 'info')
            }
        });
    }
</script>

<?php echo $__env->make('master_view', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>