$(".alert-dismissible").fadeOut(0);
var table;
var facilityDescriptionEditor; 

$(document).ready(function () 
{
    table = $('#datatable-fixedheader').DataTable({
        retrieve: true,
        columnDefs: [],
        "processing": true,
        "serverSide": true,
        "lengthChange": true,
        "ordering": true,
        'autoWidth': false,
        "pagingType": "full_numbers",
        "iDisplayLength": 10,
        "lengthMenu": [
            [10, 25, 50, -1],
            [10, 25, 50, "All"]
        ],
        "order": [],  
        "ajax": {
            "url": BASEURL + 'facility-list',
            "type": "POST"
        },
        "columnDefs": [{
            "targets": [0, 3, 6], 
            "orderable": false,        
        }],
        "fnInitComplete": function () 
        { 
            $(".dt-container .dt-search").append('<button type="button" id="cb-add" class="btn btn-secondary waves-effect waves-light" data-bs-toggle="modal" data-bs-target=".modal1" onclick="add_data()">+ Add New</button>');
        },
    });
});

 
function initializeFacilityCKEditor() {
    if (facilityDescriptionEditor) {
        facilityDescriptionEditor.destroy();
    }

    facilityDescriptionEditor = CKEDITOR.replace('description', {
        height: 200,
        versionCheck: false,
        toolbar: [
            { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike'] },
            { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent'] },
            { name: 'links', items: ['Link', 'Unlink'] },
            { name: 'styles', items: ['Format', 'Font', 'FontSize'] },
            { name: 'colors', items: ['TextColor', 'BGColor'] },
            { name: 'tools', items: ['Maximize'] },
            { name: 'editing', items: ['Source'] }
        ],
        removePlugins: 'elementspath',
        resize_enabled: false
    });
}

 
function reload_table() {
    table.ajax.reload(null,false);
}

 
$('.modal1').on('shown.bs.modal', function () {
    $('[name="name"]').focus();
    setTimeout(function() {
        initializeFacilityCKEditor();
    }, 100);
});

 
$('.modal1').on('hidden.bs.modal', function () {
    if (facilityDescriptionEditor) {
        facilityDescriptionEditor.destroy();
        facilityDescriptionEditor = null;
    }
});

var save_method;
function add_data() {
    save_method = 'add';
    $('#id').val(''); 
    $('#form').parsley().reset();
    $('#form')[0].reset();

    if (facilityDescriptionEditor) {
        facilityDescriptionEditor.setData('');
    }

    $(".modal-title").html('Add Facility');
    $('#submit').attr('disabled', false);    
    $("#submit").html('Save');

    setTimeout(function() {
        initializeFacilityCKEditor();
    }, 100);
}

function edit_data(id) {
    save_method = 'update';
    $('#form').parsley().reset();
    $('#form')[0].reset();
    $(".modal-title").html('Edit Facility');
    $("#submit").html('Update');
    $('#submit').attr('disabled', false);
    $('.modal1').modal('show');

    $.ajax({
        url: BASEURL + 'facility/edit/' + id,
        type: "GET",
        dataType: "JSON",
        success: function (data) {
            $('[name="id"]').val(data.id);
            $('[name="name"]').val(data.name); 
            $('[name="sequence_no"]').val(data.sequence_no);  

            if (facilityDescriptionEditor) {
                facilityDescriptionEditor.setData(data.description || '');
            } else {
                setTimeout(function() {
                    if (facilityDescriptionEditor) {
                        facilityDescriptionEditor.setData(data.description || '');
                    }
                }, 500);
            }
        },
        error: function () {
            alert('Error! Could not get data.');
        }
    });
}

 
$(document).on("click", ".delete_btn", function () {
    var id = $(this).data('id');  
    var t = Swal.mixin({
        customClass: {
            confirmButton: "btn btn-success mx-1",
            denyButton: "btn btn-secondary mx-1",
            cancelButton: "btn btn-danger mx-1"
        },
        buttonsStyling: false
    });

    t.fire({
        title: "Are you sure?",
        text: "You won't be able to revert this!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#34c38f",
        cancelButtonColor: "#f03b3b",
        confirmButtonText: "Yes, delete it!",
        cancelButtonText: "No, cancel!"
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                type: 'POST',
                url: BASEURL + 'facility/delete/' + id,
                data: { id: id },
                dataType: 'json',
                beforeSend: function () {
                    $('.dataTables_processing').css('visibility', 'visible');
                },
                success: function (returnData) {
                    if (returnData.status == 'ok') {
                        Swal.fire("Deleted!", "Record has been deleted.", "success");
                        reload_table();
                    } else if (returnData.status == 'not') {
                        Swal.fire("Cancelled", "Record can't delete, because it's used in " + returnData.tbc_name, "error");
                        reload_table();
                    }
                },
                complete: function () {
                    $('.dataTables_processing').css('visibility', 'hidden');
                }
            });
        } else if (result.dismiss === Swal.DismissReason.cancel) {
            Swal.fire("Cancelled", "Your data is safe.", "error");
        }
    });
});


// Submit Facility Form
$('#form').submit(function (e) {
    e.preventDefault();

    if (facilityDescriptionEditor) {
        facilityDescriptionEditor.updateElement();
    }

    if ($('#form').parsley().isValid()) {
        $('#submit').attr('disabled', true);

        $.ajax({
            url: BASEURL + 'facility/submit',
            type: "POST",
            data: $('#form').serialize(),
            dataType: "JSON",
            success: function (result) {
                if (result.status == 'ok') {
                    reload_table(); 
                    $('.modal1').modal('hide');
                    $('#id').val(''); 
                    $('#form').parsley().reset();
                    $('#form')[0].reset();

                    if (facilityDescriptionEditor) {
                        facilityDescriptionEditor.setData('');
                    }

                    $('#submit').text('Save');
                    $('#submit').attr('disabled', false);
                    $(".alert-danger").hide();
                    $(".alert-success").show();
                    $(".alert-success-msg").html(result.message);                        
                    setTimeout(function () { $(".alert-success").fadeOut(500); }, 10000);
                } else {
                    $('.modal1').modal('hide');
                    $('#id').val(''); 
                    $('#form').parsley().reset();
                    $('#form')[0].reset();

                    if (facilityDescriptionEditor) {
                        facilityDescriptionEditor.setData('');
                    }

                    $('#submit').text('Save');
                    $('#submit').attr('disabled', false);
                    $(".alert-success").hide();
                    $(".alert-danger").show();
                    $(".alert-danger-msg").html(result.message);
                    setTimeout(function () { $(".alert-danger").fadeOut(500); }, 10000);
                }
            },
            error: function() {
                alert('Error submitting form. Please try again.');
                $('#submit').attr('disabled', false);
            }
        });
    }

    return false;
});
