$(".alert-dismissible").fadeOut(0);
var table;
$(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 + 'management-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 reload_table() 
{
    table.ajax.reload(null,false);  
}

$('.modal').on('shown.bs.modal', function () {
    $('[name="name"]').focus()
})

var save_method;
function add_data() 
{
    save_method = 'add';
    $('#id').val(''); 
    $('#get_old_doc').val('');     
    $("#img_preview").hide();
    $('#form').parsley().reset();
    $('#form')[0].reset();
    $(".modal-title").html('Add Management');
    $('#submit').attr('disabled', false);    
    $("#submit").html('Save');     
}


function edit_data(id) 
{
    save_method = 'update';
    $('#form')[0].reset();
    $('#form').parsley().reset();

    $(".modal-title").html('Edit Management');
    $("#submit").html('Update');

    $('.modal1').modal('show');

    $.ajax({
        url: BASEURL + 'management/edit/' + id,
        type: "GET",
        dataType: "JSON",
        success: function (data) {
            $('#id').val(data.id);
            $('#director_name').val(data.director_name);
            $('#description').val(data.description);
            $('#sequence_no').val(data.sequence_no);
            $('#get_old_doc').val(data.image);
             
            if(data.image && data.image !== '') {
                $('#preview_img_tag').attr('src', BASEURL + '../assets/images/slider/' + data.image);
                $('#img_preview').show();
            } else {
                $('#img_preview').hide();
            }
        },
        error: function () {
            alert('Error fetching data');
        }
    });
}

function deactive(id) 
{
    $.ajax({
        type: "POST",
        url: BASEURL + 'management/deactive/' + id,
        data: "id=" + id,
        dataType: "json",
        success: function (data) {
            if (data == 'sucess') {
                reload_table();
            } else {
                alert('Status Update Fail');
            }
        }
    });
}

function active(id) 
{
    $.ajax({
        type: "POST",
        url: BASEURL + 'management/active/' + id,
        data: "id=" + id,
        dataType: "json",
        success: function (data) {
            if (data == 'sucess') {
                reload_table();
            } else {
                alert('Status Update Fail');
            }
        }
    });
}
 

$(document).on("click", ".delete_btn", function (event) {
var id = $(this).attr('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: !1
    }),
    e = Swal.mixin({
        toast: !0,
        position: "top-end",
        showConfirmButton: !1,
        timer: 3e3,
        timerProgressBar: !0,
        didOpen: function(t) {
            t.addEventListener("mouseenter", Swal.stopTimer), t.addEventListener("mouseleave", Swal.resumeTimer)
        }
    });
     t.fire({
        title: "Are you sure?",
        text: "You won't be able to revert this!",
        icon: "warning",
        showCancelButton: !0,
        confirmButtonColor: "#34c38f",
        cancelButtonColor: "#f03b3b",
        confirmButtonText: "Yes, delete it!",
        cancelButtonText: "No, cancel!"
    }).then(
    function (t) {
        if (t.value) {
            var $url = BASEURL + 'management/delete/' + id;
            $.ajax({
                type: 'POST',
                url: $url,
                async: false,
                data: {
                    id: id
                },
                dataType: 'json',
                beforeSend: function () {
                    $('.dataTables_processing').css('visibility', 'visible');
                },
                success: function (returnData) {
                    if (returnData.status == 'ok') {
                        Swal.fire({
                            title: "Deleted!",
                            text: "Record has been deleted.",
                            icon: "success"
                        })
                        reload_table();
                    } else if (returnData.status == 'not') {
                        var tbc_name = returnData.tbc_name;
                        Swal.fire({
                            title: "Cancelled",
                            text: "Record can't delete, Because they are used in " + tbc_name + ".",
                            icon: "error"
                        })
                        reload_table();
                    }
                },
                complete: function () {
                    $('.dataTables_processing').css('visibility', 'hidden');
                }
            });
        } else {
            t.dismiss === Swal.DismissReason.cancel && Swal.fire({
                title: "Cancelled",
                text: "Congrates! Your data is safe.",
                icon: "error"
            })
        }
    })
}); 
$('#form').submit(function (e) {
    e.preventDefault();

    if (!$('#form').parsley().isValid()) {
        return;
    }

    var formData = new FormData(this);

    $.ajax({
        url: BASEURL + 'management/submit',
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        dataType: "json",
        beforeSend: function () {
            $('#submit').prop('disabled', true).html('Saving...');
        },
        success: function (res) {
            if (res.status == 'ok') {
                Swal.fire(res.heading, res.message, "success");
                $('.modal1').modal('hide');
                reload_table();
            } else {
                Swal.fire("Error", "Something went wrong", "error");
            }
        },
        complete: function () {
            $('#submit').prop('disabled', false).html('Submit');
        }
    });
});
