<link rel="stylesheet" href="<?php echo e(asset('public/assets/css/datatables/jquery.dataTables.min.css')); ?>">
<link rel="stylesheet" href="<?php echo e(asset('public/assets/css/datatables/jquery.datatables.buttons.min.css')); ?>">
<link href="<?php echo e(asset('public/assets/css/bootstrap/bootstrap.css')); ?> " rel="stylesheet">

<link rel="stylesheet  ">
<style>
.user_privillage {
    padding: 10px;
}
</style>

<?php $__env->startSection('content'); ?>
<section style="margin-left: 20px; margin-top: 20px;">
    <div class="col-lg-8 col-md-8 col-sm-12">
        <div class="card shadow">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div>
                        <h2 class="card-title">Designations</h2>
                    </div>
                </div>
                <div class="d-flex align-items-center justify-content-between mb-3">
                    <div>
                        <button class="btn btn-light" onclick="reload()"><i
                                class="fas fa-sync mr-1"></i>Refresh</button>
                    </div>
                    <div class="d-flex align-items-center">
                        <button class="btn bg-primary text-white" onclick="showDesignationModal()">Add</button>
                    </div>
                </div>


                <table id="dataTable-1" class="table table-bordered table-hover mb-0">
                    <thead>
                        <tr>
                            <th>Designation</th>
                            <th style="width: 50px;">Action</th>
                        </tr>
                    </thead>
                    <tbody id="designations_table">

                    </tbody>
                </table>
            </div>
        </div>

        <div class="modal fade" id="add_designation_modal" tabindex="-1" role="dialog"
            aria-labelledby="addDesignationModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addDesignationModalLabel">Add Designation</h5>

                        <button type="button" class="btn btn-sm bg-danger text-white" class="close" data-dismiss="modal"
                            aria-label="Close">
                            <span aria-hidden="true" style="color: white;">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="col-12">
                            <div class="form-group">
                                <label for="designation">Designation</label>
                                <input type="text" class="form-control" id="designation" name="designation" />
                            </div>
                        </div>

                        <div class="d-flex align-items-center justify-content-end mt-2">
                            <button class="btn btn-sm bg-primary text-white" onclick="addDesignation()"><i
                                    class="fas fa-save me-1"></i>Save</button>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div> <!-- Bordered table -->
    <?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 designations = [];
    let submitBtn;
    $(document).ready(function() {
        $('#dataTable-1').DataTable();
        designations = <?php echo json_encode($designations); ?>;
        submitBtn = document.getElementById('submit_btn');
        renderTable(designations);

        $('#designations_table').on('click', 'button', function(e) {
            let id = $(this).attr('id');
            let splitted_id = id.split('-');
            let type = splitted_id[0];
            let actual_id = splitted_id[1];
            let designation_index = designations.findIndex(d => d['id'] == actual_id);
            if (designation_index != -1) {
                let designation = designations[designation_index];
                console.log(designation);
                if (type == 'edit_designation') {
                    let designation_name = document.getElementById('designation');
                    designation_name.value = designation['name'];
                    localStorage.setItem('designation_id', actual_id);
                    $('#add_designation_modal').modal('show');
                }

                if (type == 'assign_privillages') {
                    console.log('Working', actual_id);
                    window.location = `<?php echo e(url('/set-designation-privillages/${actual_id}')); ?>`;
                }

                if (type == 'delete_designation') {
                    const csrfToken = document.head.querySelector("[name~=csrf-token][content]")
                        .content;
                    let data = {
                        designation_id: actual_id,
                        _token: csrfToken
                    }

                    Swal.fire({
                        title: 'Info',
                        text: 'Do you want to delete designation?',
                        icon: 'info',
                        confirmButtonText: 'Yes',
                        showCancelButton: true,
                        cancelButtonText: 'No',
                        confirmButtonColor: '#1cc88a',
                        cancelButtonColor: '#d33',
                    }).then((result) => {
                        if (result.isConfirmed) {
                            $.ajax({
                                url: `<?php echo e(url('/delete-designation')); ?>`,
                                method: 'POST',
                                data: data,
                                success: function(result_) {
                                    result_ = JSON.parse(result_);
                                    designations = result_['data'];
                                    localStorage.setItem('designation_id', '0');
                                    $('#add_designation_modal').modal('hide');
                                    Swal.fire({
                                        title: 'Info',
                                        text: result_['status'] ==
                                            'success' ?
                                            'Designation has been deleted successfully!!' :
                                            'Designation could not be deleted!',
                                        icon: 'info',
                                        confirmButtonText: 'Okay',
                                        confirmButtonColor: '#1cc88a'

                                    }).then((result) => {
                                        renderTable(designations);
                                    })
                                }
                            });
                        }
                    })
                }
            } else {
                Swal.fire({
                    title: 'Info',
                    text: 'Designation does not exists',
                    icon: 'error',
                    confirmButtonText: 'Okay',
                    confirmButtonColor: '#1cc88a'
                }).then((isConfirmed) => {
                    designation_name.value = "";
                    $('#add_designation_modal').modal('hide');
                })
            }

        });
    });

    function showDesignationModal() {
        $('#add_designation_modal').modal('show');
    }

    function addDesignation() {
        let designation_id = localStorage.getItem('designation_id');
        let designation_name = document.getElementById('designation');
        let designation_index = designations.findIndex(d => d['name'].toLowerCase() == designation_name
            .value.toLowerCase());
        if (designation_index != -1) {
            $('#add_designation_modal').modal('hide');
            Swal.fire({
                title: 'Info',
                text: 'Designation already exists',
                icon: 'error',
                confirmButtonText: 'Okay',
                confirmButtonColor: '#1cc88a'
            }).then((isConfirmed) => {
                designation_name.value = "";
            })
            return;
        }
        const csrfToken = document.head.querySelector("[name~=csrf-token][content]").content;

        let data = {
            designation_id: designation_id,
            designation_name: designation_name.value,
            created_at: new Date().toLocaleDateString(),
            _token: csrfToken
        };

        $.ajax({
            url: `<?php echo e(url('/add-designation')); ?>`,
            method: 'POST',
            data: data,
            success: function(result_) {
                result_ = JSON.parse(result_);
                designations = result_['data'];
                localStorage.setItem('designation_id', '0');
                $('#add_designation_modal').modal('hide');
                Swal.fire({
                    title: 'Info',
                    text: result_['status'] == 'success' ?
                        'Designation has been saved successfully!' :
                        'Designation could not be saved',
                    icon: result_['status'],
                    confirmButtonText: 'Okay',
                    confirmButtonColor: '#1cc88a'

                }).then((result) => {
                    renderTable(designations);
                })
            }
        });
    }

    function addPrivillage() {
        var selectedValue = $("#user_privillage").val();
        console.log(selectedValue);


    }

    function renderTable(designations_) {
        $('#designations_table td').parent().remove();
        designations_.forEach((designation, product_index) => {
            let tb = $('#designations_table');
            let tr = $(`<tr id="${designation.id}"></tr>`);
            let designation_name = $('<td>' + designation.name + '</td>');
            let checkBtn = $(
                '<td><div class="d-flex align-items-center"><button type="button" title="Edit Designation" class="d-flex align-items-center btn mr-1" id="edit_designation-' +
                designation.id +
                '"><i class="fas fa-edit"></i></button> <button type="button" title="Assign Privillage" class="d-flex align-items-center btn mr-1" id="assign_privillages-' +
                designation.id +
                '"><i class="fas fa-shield"></i></button> <button type="button" title="Delete designation" class="d-flex align-items-center btn" id="delete_designation-' +
                designation.id + '"><i class="fas fa-trash text-danger "></i></button></td>');
            tr.append(designation_name);
            tr.append(checkBtn);
            tb.append(tr);
        })


    }


    function reload() {
        window.location = `<?php echo e(url('/designations')); ?>`;
    }

    $(".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 assignProducts() {
        let pids_ = JSON.stringify(pids);
        const csrfToken = document.head.querySelector("[name~=csrf-token][content]").content;
        Swal.fire({
            title: 'Info',
            text: 'Do you want to assign products?',
            icon: 'question',
            confirmButtonText: 'Yes',
            showCancelButton: true,
            cancelButtonText: 'No',
            confirmButtonColor: '#1cc88a',
            cancelButtonColor: '#d33',

        }).then((result) => {
            if (result.isConfirmed) {
                submitBtn.disabled = true;
                $.ajax({
                    url: `<?php echo e(url('/assign-products')); ?>`,
                    method: 'POST',
                    data: {
                        user_id: '',
                        products: pids_,
                        _token: csrfToken
                    },
                    success: function(result_) {
                        Swal.fire({
                            title: 'Info',
                            text: result_ == 'success' ?
                                'Products has been assigned successfully!' :
                                'Products could not be assigned!',
                            icon: result_,
                            confirmButtonText: 'Okay',
                            confirmButtonColor: '#1cc88a'

                        }).then((result) => {
                            window.location.reload();
                        })
                    }
                });

            } else if (result.isDenied) {
                submitBtn.disabled = false;
                Swal.fire('Changes are not saved', '', 'info')
            }
        });
    }

    function resetPrivillages() {
        let pids_ = JSON.stringify([]);
        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;
                $.ajax({
                    url: `<?php echo e(url('/assign-products')); ?>`,
                    method: 'POST',
                    data: {
                        user_id: '',
                        products: pids_,
                        _token: csrfToken
                    },
                    success: function(result_) {
                        Swal.fire({
                            title: 'Info',
                            text: result_ == 'success' ?
                                'Products privillages has been resetted successfully!' :
                                'Products privillages could not be resetted!',
                            icon: result_,
                            confirmButtonText: 'Okay',
                            confirmButtonColor: '#1cc88a'

                        }).then((result) => {
                            window.location.reload();
                        })
                    }
                });

            } else if (result.isDenied) {
                submitBtn.disabled = false;
                Swal.fire('Changes are not saved', '', 'info')
            }
        });
    }
    </script>
<?php echo $__env->make('master_view', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>