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

$(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 + 'career/ajax_list',
            "type": "POST"
        },
        "columnDefs": [{
            "targets": [0, 4, 5], 
            "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 initializeCareerCKEditor() {
    if (careerDescriptionEditor) {
        careerDescriptionEditor.destroy();
    }

    careerDescriptionEditor = 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="title"]').focus();
    setTimeout(function() {
        initializeCareerCKEditor();
    }, 100);
});

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

var save_method;

function add_data() 
{
    save_method = 'add';
    $('#id').val('');
    $('#title').val('');
    $('#department').val('');
    $('#location').val('Rajkot');
    $('#experience').val('');
    $('#qualification').val('');
    
    if (careerDescriptionEditor) {
        careerDescriptionEditor.setData('');
    }
    
    
    var today = new Date();
    var dd = String(today.getDate()).padStart(2, '0');
    var mm = String(today.getMonth() + 1).padStart(2, '0');
    var yyyy = today.getFullYear();
    $('#posted_date').val(dd + '-' + mm + '-' + yyyy);
    
    $(".modal-title").html('Add Career');
    $('#submit').attr('disabled', false);
    $("#submit").html('Save');
    
    setTimeout(function() {
        initializeCareerCKEditor();
    }, 100);
}

function edit_data(id) 
{
    save_method = 'update';
    $(".modal-title").html('Edit Career');
    $("#submit").html('Update');
    $('#submit').attr('disabled', false);
    $('.modal1').modal('show');

    $.ajax({
        url: BASEURL + 'career/edit/' + id,
        type: "GET",
        dataType: "JSON",
        success: function (data) {
            $('#id').val(data.id);
            $('#title').val(data.title);
            $('#department').val(data.department);
            $('#location').val(data.location);
            $('#experience').val(data.experience);
            $('#qualification').val(data.qualification);
            $('#posted_date').val(data.posted_date);
            
            if (careerDescriptionEditor) {
                careerDescriptionEditor.setData(data.description || '');
            } else {
                setTimeout(function() {
                    if (careerDescriptionEditor) {
                        careerDescriptionEditor.setData(data.description || '');
                    }
                }, 500);
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('Error! Unable to get data from database.');
        }
    });
}

$('#submit').click(function(e) {
    e.preventDefault();
    
    if (careerDescriptionEditor) {
        careerDescriptionEditor.updateElement();
    }
    
    if($('#title').val() === '') {
        alert('Please enter position title');
        return;
    }

    var formData = {
        id: $('#id').val(),
        title: $('#title').val(),
        department: $('#department').val(),
        location: $('#location').val(),
        experience: $('#experience').val(),
        qualification: $('#qualification').val(),
        description: $('#description').val(),
        posted_date: $('#posted_date').val()
    };

    $('#submit').attr('disabled', true);
    
    $.ajax({
        url: BASEURL + 'career/submit',
        type: "POST",
        data: formData,
        dataType: "JSON",
        success: function (result) 
        {
            if (result.status == 'ok') 
            {
                reload_table(); 
                $('.modal1').modal('hide');
                $('#id').val('');
                $('#title').val('');
                $('#department').val('');
                $('#location').val('');
                $('#experience').val('');
                $('#qualification').val('');
                
                if (careerDescriptionEditor) {
                    careerDescriptionEditor.setData('');
                }
                
                $('#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('');
                $('#title').val('');
                $('#department').val('');
                $('#location').val('');
                $('#experience').val('');
                $('#qualification').val('');
                
                if (careerDescriptionEditor) {
                    careerDescriptionEditor.setData('');
                }
                
                $('#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(jqXHR, textStatus, errorThrown) {
            $('#submit').attr('disabled', false);
            alert('Error submitting data!');
        }
    });
});

function deactive(id) 
{
    $.ajax({
        type: "POST",
        url: BASEURL + 'career/deactive/' + id,
        data: "id=" + id,
        dataType: "json",
        success: function (data) {
            reload_table();
        },
        error: function() {
            alert('Status update failed');
        }
    });
}

function active(id) 
{
    $.ajax({
        type: "POST",
        url: BASEURL + 'career/active/' + id,
        data: "id=" + id,
        dataType: "json",
        success: function (data) {
            reload_table();
        },
        error: function() {
            alert('Status update failed');
        }
    });
}

$(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 + 'career/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"
                })
            }
        }
    )
});