
$("#btnSave").on('click',function(e){
    e.preventDefault();
    data_id = $('#data-id').val();
    let url = parseInt(data_id) === 0 ? save_url : update_url;
    $.ajax({
        url: url,
        type:"POST",
        data :{
            "_token": csrf_token,
            uid : data_id,
            name_en: $('#name-en').val(),
            lab_ids: $('#lab-ids').val()
        },
        success:function(res){
            handleMessage(res.success, res.message)
            if(res.success) setTimeout(function () {location.reload()}, messageDuration)
        },
    });
});

function delete_lab(uid){
    Swal.fire({
        text: confirm_delete_record,
        icon: 'question',
        showCancelButton: true,
        cancelButtonClass:'danger',
        confirmButtonText: confirm_ok_delete,
        cancelButtonText: confirm_cancel
    }).then((result) => {
        if (result.value) {
            $.ajax({
                url: delete_url,
                method:'POST',
                data:{
                    "_token": csrf_token,
                    uid : uid,
                },
                success:function(res){
                    handleMessage(res.success, res.message)
                    if(res.success) setTimeout(function () {location.reload()}, messageDuration)
                }
            })
        }
    });
}

function restore_lab(uid){
    Swal.fire({
        text: confirm_restore_record,
        icon: 'question',
        showCancelButton: true,
        cancelButtonClass:'danger',
        confirmButtonText: confirm_ok_restore,
        cancelButtonText: confirm_cancel_restore,
    }).then((result) => {
        if (result.value) {
            $.ajax({
                url: restore_url,
                method:'POST',
                data:{
                    "_token": csrf_token,
                    uid : uid,
                },
                success:function(res){
                    handleMessage(res.success, res.message)
                    if(res.success) setTimeout(function () {location.reload()}, messageDuration)
                }
            })
        }
    });
}


$('#modal-role').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget) // Button that triggered the modal
    var action = button.data('action') // Extract info from data-* attributes
    var modal = $(this);
    if(action === "new"){
        // Clear inputs
        modal.find('.modal-body select[name="lab_ids"]').attr('multiple', true)
        modal.find('.modal-body input').val("");
        modal.find('.modal-body input[name="uid"]').val(0);
        modal.find('.modal-title').html(modal_add_title);
    }else if(action === "edit"){
        uid = button.data('uid');
        modal.find('.modal-body select[name="lab_ids"]').attr('multiple', false)
        modal.find('.modal-body input[name="uid"]').val(uid);
        modal.find('.modal-title').html(modal_edit_title);
        $.ajax({
            url: get_url,
            type:"POST",
            data:{
                "_token": csrf_token,
                uid: uid,
            },
            success:function(res){
                let data = res.data;
                modal.find('.modal-body input[name="name_en"]').val(data.name_en);
                modal.find('.modal-body input[name="name_kh"]').val(data.name_kh);
                modal.find('.modal-body select[name="lab_ids"]').val(data.lab_id).trigger('change');
                if(!res.success) handleMessage(res.success, res.message)
            },
            error: function(response) {
            },
        });
    }
})

$('#modal-role-permission').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget) // Button that triggered the modal
    uid = button.data('uid');
    $('#role-id').val(uid)
    name = button.data('name');
    $('#modal-role-permission .modal-title').text(role_permission_title +': ' + name)
    $.ajax({
        url: system_url + '/role-permission/'+uid,
        type:"get",
        success:function(res){
            if(res.success){
                //$('#modal-role-permission .table tbody').empty()
                $('#modal-role-permission #role-permission').empty()
                let permissions = res.data
                for (var i in permissions){
                    let permission_group = permissions[i];
                    group_permissions(permission_group)
                    // for sub group
                    permission_group.permissions.map(item => {
                        for(j in item){
                            if(item[j].permissions){
                                group_permissions(item[j], '4')
                            }
                        }
                    })

                }
            }
            else handleMessage(res.success, res.message)
        },
        error: function(response) {
        },
    });
})

function group_permissions(permission, level = 0)
{
    let group_permission = document.createElement('DIV')
    group_permission.classList.add('col-sm-12', 'pl-'+level)
    group_permission.style.border="1px dashed gray;"
    let permission_group_name = document.createElement('h6');
    permission_group_name.classList.add('my-3', 'font-14'); permission_group_name.innerHTML = permission.name
    group_permission.append(permission_group_name)
    group_permission.append(permissions(permission))

    $('#modal-role-permission #role-permission').append(group_permission)
}

function permissions(permission) {

    let permissions = document.createElement('DIV')
    permissions.classList.add('row')
    permission.permissions.map(item => {
        permissions.append(permissionElement(item))
    })
    return permissions
}

function permissionElement(item) {
    let singlePermission = document.createElement('div')
    singlePermission.classList.add('col-sm-12','bg-light','rounded','px-4','col-md-12','col-lg-6','col-xl-3','border','border-white')
    singlePermission.innerHTML = '<div class="form-check my-1"><label class="form-check-label font-13"><input '+(item.is_can>=1 ? 'checked':'')+' name="permission_id[]" value="'+item.id+'" type="checkbox" class="form-check-input" id="select-all-lab">'+item.name+' <i class="input-helper"></i></label></div> ';
    return singlePermission;
}
