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

$(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 + 'awards-list',
            "type": "POST"
        },
        
        "columnDefs": [{
            "targets": [0, 3, 4, 6, 7], 
            "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 initializeCKEditor() {
    if (descriptionEditor) {
        descriptionEditor.destroy();
    }
    
    descriptionEditor = 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() {
        initializeCKEditor();
    }, 100);
});

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

var save_method;

function add_data() 
{
    save_method = 'add';
    $('#id').val(''); 
    $('#get_old_person_doc').val('');
    $('#get_old_award_doc').val('');
    
    $("#person_img_preview").hide();
    $("#award_img_preview").hide();
    $("#preview_person_img_tag").hide();
    $("#preview_award_img_tag").hide();
    
    $("#dropzone-preview-person li").remove();
    $("#dropzone-preview-award li").remove();
    
    $(".person-dropzone").removeClass("dropzone_required");
    $(".award-dropzone").removeClass("dropzone_required");
  
    if (typeof dropzonePerson !== 'undefined' && dropzonePerson) dropzonePerson.removeAllFiles();
    if (typeof dropzoneAward !== 'undefined' && dropzoneAward) dropzoneAward.removeAllFiles();
    
    $('#form').parsley().reset();
    $('#form')[0].reset();
    
    if (descriptionEditor) {
        descriptionEditor.setData('');
    }
    
    $(".modal-title").html('Add Awards & Achievements');
    $('#submit').attr('disabled', false);    
    $("#submit").html('Save');
    
    setTimeout(function() {
        initializeCKEditor();
    }, 100);
}

function edit_data(id) 
{
    save_method = 'update';
    
    $("#dropzone-preview-person li").remove();
    $("#dropzone-preview-award li").remove();
    
    $(".person-dropzone").removeClass("dropzone_required");
    $(".award-dropzone").removeClass("dropzone_required");
    
    if (typeof dropzonePerson !== 'undefined' && dropzonePerson) dropzonePerson.removeAllFiles();
    if (typeof dropzoneAward !== 'undefined' && dropzoneAward) dropzoneAward.removeAllFiles();
    
    $('#form').parsley().reset();
    $('#form')[0].reset();
    $(".modal-title").html('Edit Awards & Achievements');
    $("#submit").html('Update');
    $('#submit').attr('disabled', false);
    $('.modal1').modal('show');    

    $.ajax({
        url: BASEURL + 'awards/edit/' + id,
        type: "GET",
        dataType: "JSON",
        success: function (data) {
            if(data.error) {
                alert('Error! ' + data.error);
                return;
            }
            
            $('[name="id"]').val(data.id);
            $('[name="title"]').val(data.title);
            $('[name="get_old_person_doc"]').val(data.person_img);
            $('[name="get_old_award_doc"]').val(data.award_img);
            $('.person_img_name_get').html(data.person_img);
            $('.award_img_name_get').html(data.award_img);
            
            if (descriptionEditor) {
                descriptionEditor.setData(data.description || '');
            } else {
                setTimeout(function() {
                    if (descriptionEditor) {
                        descriptionEditor.setData(data.description || '');
                    }
                }, 500);
            }
            
            if (data.person_img != "" && data.person_img != null) 
            {
                $("#person_img_preview").show();
                $("#preview_person_img_tag").attr("src", BASEURL + '../assets/images/awards/' + data.person_img).show();
            }
            else 
            {
                $("#person_img_preview").hide();
                $("#preview_person_img_tag").hide();
            }

            if (data.award_img != "" && data.award_img != null) 
            {
                $("#award_img_preview").show();
                $("#preview_award_img_tag").attr("src", BASEURL + '../assets/images/awards/' + data.award_img).show();
            }
            else 
            {
                $("#award_img_preview").hide();
                $("#preview_award_img_tag").hide();
            }

            $("#btnSave").html('Update');
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('Error:', jqXHR.responseText);
            alert('Error! Get data from database. Please check console for details.');
        }
    });
} 

function deactive(id) 
{
    $.ajax({
        type: "POST",
        url: BASEURL + 'awards/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 + 'awards/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 + 'awards/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: "Award & Achievement has been deleted.",
                            icon: "success"
                        })
                        reload_table();
                    } else if (returnData.status == 'not') {
                        var tbc_name = returnData.tbc_name;
                        Swal.fire({
                            title: "Cancelled",
                            text: "Award & Achievement 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"
            })
        }
    });
}); 

Dropzone.autoDiscover = false; 

var previewTemplatePersons, dropzonePerson, dropzonePreviewNodePerson = document.querySelector("#dropzone-preview-list-person");
var previewTemplateAward, dropzoneAward, dropzonePreviewNodeAward = document.querySelector("#dropzone-preview-list-award");
var submissionInProgress = false; 
 
if (dropzonePreviewNodePerson) {
    previewTemplatePersons = dropzonePreviewNodePerson.parentNode.innerHTML;
    dropzonePreviewNodePerson.parentNode.removeChild(dropzonePreviewNodePerson);
    
    dropzonePerson = new Dropzone(".person-dropzone", {
        url: BASEURL + 'awards/submit',
        method: "post",
        previewTemplate: previewTemplatePersons,
        previewsContainer: "#dropzone-preview-person", 
        autoProcessQueue: false,
        acceptedFiles: ".jpeg,.jpg,.png",
        maxFilesize: 2,
        paramName: "person_file",
        parallelUploads: 1,
        uploadMultiple: false,
        init: function () {
            this.on('sending', function(file, xhr, formData) {
                var data = $('#form').serializeArray();
                $.each(data, function(key, el) {
                    formData.append(el.name, el.value);
                });
            });
        }
    });
}
 
if (dropzonePreviewNodeAward) {
    previewTemplateAward = dropzonePreviewNodeAward.parentNode.innerHTML;
    dropzonePreviewNodeAward.parentNode.removeChild(dropzonePreviewNodeAward);
    
    dropzoneAward = new Dropzone(".award-dropzone", {
        url: BASEURL + 'awards/submit',
        method: "post",
        previewTemplate: previewTemplateAward,
        previewsContainer: "#dropzone-preview-award", 
        autoProcessQueue: false,
        acceptedFiles: ".jpeg,.jpg,.png",
        maxFilesize: 2,
        paramName: "award_file",
        parallelUploads: 1,
        uploadMultiple: false,
        init: function () {
            this.on('sending', function(file, xhr, formData) {
                var data = $('#form').serializeArray();
                $.each(data, function(key, el) {
                    formData.append(el.name, el.value);
                });
            });
        }
    });
}
 
$('#form').on('submit', function (e) {
    e.preventDefault();
    
    if (descriptionEditor) {
        descriptionEditor.updateElement();
    }
    
    if (submissionInProgress) {
        return false;
    }
    
    if ($('#form').parsley().isValid()) {
        submissionInProgress = true;
        $('#submit').attr('disabled', true);
        
        var get_id = $('#id').val();
        var get_old_person_doc = $('#get_old_person_doc').val();
        var get_old_award_doc = $('#get_old_award_doc').val();
        
        var hasPersonFile = dropzonePerson && dropzonePerson.getQueuedFiles().length > 0;
        var hasAwardFile = dropzoneAward && dropzoneAward.getQueuedFiles().length > 0;
        
        $(".person-dropzone").removeClass("dropzone_required");
        $(".award-dropzone").removeClass("dropzone_required");
        
        if (hasPersonFile && hasAwardFile) {
            var formData = new FormData();
            
            var formFields = $('#form').serializeArray();
            $.each(formFields, function(key, field) {
                formData.append(field.name, field.value);
            });
            
            var personFiles = dropzonePerson.getQueuedFiles();
            if (personFiles.length > 0) {
                formData.append('person_file', personFiles[0]);
            }
            
            var awardFiles = dropzoneAward.getQueuedFiles();
            if (awardFiles.length > 0) {
                formData.append('award_file', awardFiles[0]);
            }
            
            $.ajax({
                url: BASEURL + 'awards/submit',
                type: "POST",
                data: formData,
                processData: false,
                contentType: false,
                cache: false,
                dataType: "JSON",
                success: function (result) {
                    handleFormSuccess(result);
                },
                error: function(xhr, status, error) {
                    console.error('Upload error:', error);
                    alert('Upload failed. Please try again.');
                    submissionInProgress = false;
                    $('#submit').attr('disabled', false);
                }
            });
        }
        else if (hasPersonFile && !hasAwardFile) {
            dropzonePerson.on("success", function(file, response) {
                dropzonePerson.off("success");
                handleFormSuccess(typeof response === 'string' ? JSON.parse(response) : response);
            });
            dropzonePerson.processQueue();
        }
        else if (!hasPersonFile && hasAwardFile) {
            dropzoneAward.on("success", function(file, response) {
                dropzoneAward.off("success");
                handleFormSuccess(typeof response === 'string' ? JSON.parse(response) : response);
            });
            dropzoneAward.processQueue();
        }
        else {
            $.ajax({
                url: BASEURL + 'awards/submit',
                type: "POST",
                data: new FormData(this),
                processData: false,
                contentType: false,
                cache: false,
                dataType: "JSON",
                success: function (result) {
                    handleFormSuccess(result);
                },
                error: function(xhr, status, error) {
                    console.error('Submit error:', error);
                    alert('Submit failed. Please try again.');
                    submissionInProgress = false;
                    $('#submit').attr('disabled', false);
                }
            });
        }
    }
    
    return false;
});

function handleFormSuccess(result) {
    submissionInProgress = false;
    
    if (result.status == 'ok') {
        reload_table(); 
        $('.modal').modal('hide');
        $('#id').val(''); 
        $('#get_old_person_doc').val('');
        $('#get_old_award_doc').val('');
        
        if (dropzonePerson) dropzonePerson.removeAllFiles();
        if (dropzoneAward) dropzoneAward.removeAllFiles();
        
        if (descriptionEditor) {
            descriptionEditor.setData('');
        }
        
        $('#form').parsley().reset();
        $('#form')[0].reset();
        $('#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);
        }, 5000);
    } else {
        $('.modal').modal('hide');
        $('#id').val(''); 
        $('#get_old_person_doc').val('');
        $('#get_old_award_doc').val('');
        
        if (dropzonePerson) dropzonePerson.removeAllFiles();
        if (dropzoneAward) dropzoneAward.removeAllFiles();
        
        if (descriptionEditor) {
            descriptionEditor.setData('');
        }
        
        $('#form').parsley().reset();
        $('#form')[0].reset();
        $('#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);
        }, 5000);
    }
}