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

$(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 + 'blog-list',
            "type": "POST"
        },
        
        "columnDefs": [{
            "targets": [0, 5, 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>');
        },
    });
});

// Initialize CKEditor for Blog Description
function initializeBlogCKEditor() {
    if (blogDescriptionEditor) {
        blogDescriptionEditor.destroy();
    }

    blogDescriptionEditor = CKEDITOR.replace('blog_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="blog_title"]').focus();
    setTimeout(function() {
        initializeBlogCKEditor();
    }, 100);
});

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

var save_method;

function add_data() 
{
    save_method = 'add';
    $('#id').val(''); 
    $('#get_old_image').val('');
    $('#get_old_banner').val('');
    
    $("#img_preview").hide();
    $("#banner_preview").hide();
    $("#preview_img_tag").hide();
    $("#preview_banner_tag").hide();
    
    $("#dropzone-preview-image li").remove();
    $("#dropzone-preview-banner li").remove();
    
    $(".image-dropzone").removeClass("dropzone_required");
    $(".banner-dropzone").removeClass("dropzone_required");
    
    if (typeof dropzoneImage !== 'undefined' && dropzoneImage) dropzoneImage.removeAllFiles();
    if (typeof dropzoneBanner !== 'undefined' && dropzoneBanner) dropzoneBanner.removeAllFiles();
    
    $('#form').parsley().reset();
    $('#form')[0].reset();
    
    if (blogDescriptionEditor) {
        blogDescriptionEditor.setData('');
    }
    
    $(".modal-title").html('Add Blog');
    $('#submit').attr('disabled', false);    
    $("#submit").html('Save');
    
    setTimeout(function() {
        initializeBlogCKEditor();
    }, 100);
}

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

    $.ajax({
        url: BASEURL + 'blog/edit/' + id,
        type: "GET",
        dataType: "JSON",
        success: function (data) {
            if(data.error) {
                alert('Error! ' + data.error);
                return;
            }
            
            $('[name="id"]').val(data.id);
            $('[name="blog_title"]').val(data.blog_title);
            $('[name="blog_category"]').val(data.blog_category);
            $('[name="blog_date"]').val(data.blog_date);
            $('[name="blog_tags"]').val(data.blog_tags);
            $('[name="get_old_image"]').val(data.blog_image);
            $('[name="get_old_banner"]').val(data.blog_banner);
            $('.img_name_get').html(data.blog_image);
            $('.banner_name_get').html(data.blog_banner);
            
            if (blogDescriptionEditor) {
                blogDescriptionEditor.setData(data.blog_description || '');
            } else {
                setTimeout(function() {
                    if (blogDescriptionEditor) {
                        blogDescriptionEditor.setData(data.blog_description || '');
                    }
                }, 500);
            }
            
            if (data.blog_image != "" && data.blog_image != null) 
            {
                $("#img_preview").show();
                $("#preview_img_tag").attr("src", BASEURL + '../admin_panel/assets/images/blogs/' + data.blog_image).show();
            }
            else 
            {
                $("#img_preview").hide();
                $("#preview_img_tag").hide();
            }

            if (data.blog_banner != "" && data.blog_banner != null) 
            {
                $("#banner_preview").show();
                $("#preview_banner_tag").attr("src", BASEURL + '../admin_panel/assets/images/blogs/' + data.blog_banner).show();
            }
            else 
            {
                $("#banner_preview").hide();
                $("#preview_banner_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 + 'blog/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 + 'blog/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');  
    
    Swal.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(function (result) {
        if (result.value) {
            $.ajax({
                type: 'POST',
                url: BASEURL + 'blog/delete/' + id,
                data: {id: id},
                dataType: 'json',
                beforeSend: function () {
                    $('.dataTables_processing').css('visibility', 'visible');
                },
                success: function (returnData) {
                    if (returnData.status == 'ok') {
                        Swal.fire({
                            title: "Deleted!",
                            text: "Blog has been deleted.",
                            icon: "success"
                        });
                        reload_table();
                    } else if (returnData.status == 'not') {
                        Swal.fire({
                            title: "Cancelled",
                            text: "Blog can't delete, Because they are used in " + returnData.tbc_name + ".",
                            icon: "error"
                        });
                    }
                },
                complete: function () {
                    $('.dataTables_processing').css('visibility', 'hidden');
                },
                error: function() {
                    Swal.fire({
                        title: "Error!",
                        text: "Something went wrong!",
                        icon: "error"
                    });
                }
            });
        }
    });
}); 

Dropzone.autoDiscover = false; 

var previewTemplateImage, dropzoneImage, dropzonePreviewNodeImage = document.querySelector("#dropzone-preview-list-image");
var previewTemplateBanner, dropzoneBanner, dropzonePreviewNodeBanner = document.querySelector("#dropzone-preview-list-banner");
var submissionInProgress = false;
 
if (dropzonePreviewNodeImage) {
    previewTemplateImage = dropzonePreviewNodeImage.parentNode.innerHTML;
    dropzonePreviewNodeImage.parentNode.removeChild(dropzonePreviewNodeImage);
    
    dropzoneImage = new Dropzone(".image-dropzone", {
        url: BASEURL + 'blog/submit',
        method: "post",
        previewTemplate: previewTemplateImage,
        previewsContainer: "#dropzone-preview-image", 
        autoProcessQueue: false,
        acceptedFiles: ".jpeg,.jpg,.png",
        maxFilesize: 2,
        paramName: "blog_image",
        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 (dropzonePreviewNodeBanner) {
    previewTemplateBanner = dropzonePreviewNodeBanner.parentNode.innerHTML;
    dropzonePreviewNodeBanner.parentNode.removeChild(dropzonePreviewNodeBanner);
    
    dropzoneBanner = new Dropzone(".banner-dropzone", {
        url: BASEURL + 'blog/submit',
        method: "post",
        previewTemplate: previewTemplateBanner,
        previewsContainer: "#dropzone-preview-banner", 
        autoProcessQueue: false,
        acceptedFiles: ".jpeg,.jpg,.png",
        maxFilesize: 2,
        paramName: "blog_banner",
        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 (blogDescriptionEditor) {
        blogDescriptionEditor.updateElement();
    }
    
    if (submissionInProgress) {
        return false;
    }
    
    if ($('#form').parsley().isValid()) {
        submissionInProgress = true;
        $('#submit').attr('disabled', true);
        $("#submit").html('<i class="mdi mdi-loading mdi-spin"></i> Processing...');
        
        var get_id = $('#id').val();
        var get_old_image = $('#get_old_image').val();
        var get_old_banner = $('#get_old_banner').val();
        
        var hasImageFile = dropzoneImage && dropzoneImage.getQueuedFiles().length > 0;
        var hasBannerFile = dropzoneBanner && dropzoneBanner.getQueuedFiles().length > 0;
        
        $(".image-dropzone").removeClass("dropzone_required");
        $(".banner-dropzone").removeClass("dropzone_required");
         
        if (hasImageFile && hasBannerFile) {
            var formData = new FormData();
            
            var formFields = $('#form').serializeArray();
            $.each(formFields, function(key, field) {
                formData.append(field.name, field.value);
            });
            
            var imageFiles = dropzoneImage.getQueuedFiles();
            if (imageFiles.length > 0) {
                formData.append('blog_image', imageFiles[0]);
            }
            
            var bannerFiles = dropzoneBanner.getQueuedFiles();
            if (bannerFiles.length > 0) {
                formData.append('blog_banner', bannerFiles[0]);
            }
            
            $.ajax({
                url: BASEURL + 'blog/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);
                    handleFormError('Upload failed. Please try again.');
                }
            });
        }
        else if (hasImageFile && !hasBannerFile) {
            dropzoneImage.on("success", function(file, response) {
                dropzoneImage.off("success");
                handleFormSuccess(typeof response === 'string' ? JSON.parse(response) : response);
            });
            dropzoneImage.on("error", function(file, errorMessage) {
                dropzoneImage.off("error");
                handleFormError(errorMessage);
            });
            dropzoneImage.processQueue();
        }
        else if (!hasImageFile && hasBannerFile) {
            dropzoneBanner.on("success", function(file, response) {
                dropzoneBanner.off("success");
                handleFormSuccess(typeof response === 'string' ? JSON.parse(response) : response);
            });
            dropzoneBanner.on("error", function(file, errorMessage) {
                dropzoneBanner.off("error");
                handleFormError(errorMessage);
            });
            dropzoneBanner.processQueue();
        }
        else {
            $.ajax({
                url: BASEURL + 'blog/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);
                    handleFormError('Submit failed. Please try again.');
                }
            });
        }
    }
    
    return false;
});

function handleFormSuccess(result) {
    submissionInProgress = false;
    
    if (result.status == 'ok') {
        $('.modal1').modal('hide');
        reload_table(); 
        
        $('#id').val(''); 
        $('#get_old_image').val('');
        $('#get_old_banner').val('');
        
        if (dropzoneImage) dropzoneImage.removeAllFiles();
        if (dropzoneBanner) dropzoneBanner.removeAllFiles();
        
        $('#form').parsley().reset();
        $('#form')[0].reset();
        
        if (blogDescriptionEditor) {
            blogDescriptionEditor.setData('');
        }
        
        $('#submit').html('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 {
        $('.modal1').modal('hide');
        
        if (blogDescriptionEditor) {
            blogDescriptionEditor.setData('');
        }
        
        $('#submit').html('Save');
        $('#submit').attr('disabled', false);
        
        $(".alert-success").hide();
        $(".alert-danger").show();
        $(".alert-danger-msg").html(result.message);
        setTimeout(function () {
            $(".alert-danger").fadeOut(500);
        }, 5000);
    }
}

function handleFormError(errorMessage) {
    submissionInProgress = false;
    
    $('.modal1').modal('hide');
    
    if (blogDescriptionEditor) {
        blogDescriptionEditor.setData('');
    }
    
    $('#submit').html('Save');
    $('#submit').attr('disabled', false);
    
    $(".alert-success").hide();
    $(".alert-danger").show();
    $(".alert-danger-msg").html(errorMessage);
    setTimeout(function () {
        $(".alert-danger").fadeOut(500);
    }, 5000);
}