<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 class="m-5">
    <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><b>Assign Document Type</b></h2>
                        <span>Assign Document Type To </b> </span>
                    </div>
                </div>
                <div>
                    <div class="d-flex align-items-center mb-3">
                        <select class="form-control select user_document_type me-2" multiple="multiple" name="user_program[]"
                            id="user_program" required>
                            <php ?>
                                <?php   foreach ($document_types 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="addDocumentType()">Add</button>
                        <button class="btn bg-secondary ms-2 text-white" onclick="addAllDocumentTypes()">Add All</button>
                    </div>
                </div>


                <table class="table table-bordered table-hover mb-0">
                    <thead>
                        <tr>
                            <th>Document Type</th>
                            <th style="width: 100px;">Action</th>
                        </tr>
                    </thead>
                    <tbody id="user_document_types">

                    </tbody>
                </table>

                <div class="d-flex justify-content-end align-items-center mt-3">
                    <button class="btn btn-danger text-white me-1" onclick="resetUserDocumentTypes()"><i
                            class="fas fa-undo me-1"></i>Reset Records</button>
                    <button class="btn btn-primary text-white" id="submit_btn" onclick="saveUserDocumentTypes();">
                        <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 document_types = [];
let user_id = "";
let user_document_types = [];
let submitBtn;
$(document).ready(function() {
    $('#dataTable-1').DataTable();

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

    $("#save-programs").show();
    $("#progress-indicator").hide();

    document_types = <?php echo json_encode($document_types); ?>;
    user_document_types = <?php echo json_encode($user_document_types); ?>;
    user_id = <?php echo json_encode($user_id); ?>;

    submitBtn = document.getElementById('submit_btn');
    renderTable(user_document_types);

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

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

function addDocumentType() {
    var selectedValue = $("#user_document_type").val();
    selectedValue.forEach((value, value_index) => {
        let value_ = document_types.filter(v => v == value);
        let document_type = "";
        if (value_.length > 0) {
            document_type = value_[0];
        }

        let obj = {
            id: document_type,
            value: document_type
        }


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

        if (value_index == selectedValue.length - 1) {
            $("#user_document_type").val('').trigger('change')
        }
    });
}

function addAllDocumentTypes() {
    console.log(document_types)
    let keys = Object.keys(document_types);
    user_document_types = Object.values(document_types).map((document_type, index) => {
        let key = keys[index];
        return {
            id: key,
            value: document_type
        }
    });
    renderTable(user_document_types);
}

function renderTable(privillages__) {
    $('#user_document_types td').parent().remove();
    privillages__.forEach((privillage, privillage_index) => {
        let tb = $('#user_document_types');
        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 alterPrograms() {
    if ($('.custom-control-input').is(":checked")) {
        console.log('Checked');
    } else {
        console.log('Not checked');
    }
    // console.log(this.id, value);
}

function removeProgram() {

}



function saveUserDocumentTypes() {
    const csrfToken = document.head.querySelector("[name~=csrf-token][content]").content;

    let postData = {
        user_programs: JSON.stringify(user_document_types),
        user_id: user_id,
        _token: csrfToken
    }

    Swal.fire({
        title: 'Info',
        text: 'Do you want to save document types?',
        icon: 'question',
        confirmButtonText: 'Yes',
        showCancelButton: true,
        cancelButtonText: 'No',
        confirmButtonColor: '#1cc88a',
        cancelButtonColor: '#d33',

    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: `<?php echo e(url('/save-user-programs')); ?>`,
                method: 'POST',
                data: postData,
                success: function(result_) {
                    Swal.fire({
                        title: 'Info',
                        text: result_ == 'success' ?
                            'User document types have been saved successfully!' :
                            'User document types could not be saved!',
                        icon: result_,
                        confirmButtonText: 'Okay',
                        confirmButtonColor: '#1cc88a'

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

        } else if (result.isDenied) {
            Swal.fire('Changes could not be saved!', '', 'info')
        }

    })
}

function resetUserDocumentTypes() {
    const csrfToken = document.head.querySelector("[name~=csrf-token][content]").content;

    let postData = {
        user_programs: JSON.stringify([]),
        user_id: user_id,
        _token: csrfToken
    }

    Swal.fire({
        title: 'Info',
        text: 'Do you want to reset user document types?',
        icon: 'question',
        confirmButtonText: 'Yes',
        showCancelButton: true,
        cancelButtonText: 'No',
        confirmButtonColor: '#1cc88a',
        cancelButtonColor: '#d33',

    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: `<?php echo e(url('/save-user-programs')); ?>`,
                method: 'POST',
                data: postData,
                success: function(result_) {
                    Swal.fire({
                        title: 'Info',
                        text: result_ == 'success' ?
                            'User programs have been saved successfully!' :
                            'User programs could not be saved!',
                        icon: result_,
                        confirmButtonText: 'Okay',
                        confirmButtonColor: '#1cc88a'
                    }).then((res) => {
                        window.location.reload();
                    });
                }
            });
        } else if (result.isDenied) {
            Swal.fire('Changes could not be saved!', '', 'info')
        }

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