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

var save_method;

function add_data() 
{
    save_method = 'add';
    $('#id').val(''); 
    $('#get_old_image').val('');
    $('#get_old_banner').val('');
    
    // Hide preview areas
    $("#img_preview").hide();
    $("#banner_preview").hide();
    $("#preview_img_tag").hide();
    $("#preview_banner_tag").hide();
    
    // Clear dropzone previews
    $("#dropzone-preview-image li").remove();
    $("#dropzone-preview-banner li").remove();
    
    // Remove required classes
    $("#blog-image-dropzone").removeClass("dropzone_required");
    $("#blog-banner-dropzone").removeClass("dropzone_required");
    
    $('#form').parsley().reset();
    $('#form')[0].reset();
    $(".modal-title").html('Add Blog');
    $('#submit').attr('disabled', false);    
    $("#submit").html('Save');
}

function edit_data(id) 
{
    save_method = 'update';
    
    // Clear dropzone previews
    $("#dropzone-preview-image li").remove();
    $("#dropzone-preview-banner li").remove();
    
    // Remove required classes
    $("#blog-image-dropzone").removeClass("dropzone_required");
    $("#blog-banner-dropzone").removeClass("dropzone_required");
    
    $('#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_description"]').val(data.blog_description);
            $('[name="blog_tags"]').val(data.blog_tags);
            $('[name="get_old_image"]').val(data.blog_image);
            $('[name="get_old_banner"]').val(data.blog_banner);
            
            // Show existing image
            if (data.blog_image != "" && data.blog_image != null) 
            {
                $("#img_preview").show();
                $('.img_name_get').html(data.blog_image);
                $("#preview_img_tag").attr("src", BASEURL + '../assets/images/gallery/large/' + data.blog_image).show();
            }
            else 
            {
                $("#img_preview").hide();
                $("#preview_img_tag").hide();
            }

            // Show existing banner
            if (data.blog_banner != "" && data.blog_banner != null) 
            {
                $("#banner_preview").show();
                $('.banner_name_get').html(data.blog_banner);
                $("#preview_banner_tag").attr("src", BASEURL + '../assets/images/gallery/large/' + 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 Configuration
Dropzone.autoDiscover = false;

// Blog Image Dropzone
var previewNodeImage = document.querySelector("#dropzone-preview-list-image");
previewNodeImage.id = "";
var previewTemplateImage = previewNodeImage.parentNode.innerHTML;
previewNodeImage.parentNode.removeChild(previewNodeImage);

var dropzoneImage = new Dropzone("#blog-image-dropzone", {
    url: BASEURL + 'blog/submit',
    method: "post",
    previewTemplate: previewTemplateImage,
    previewsContainer: "#dropzone-preview-image",
    autoProcessQueue: false,
    acceptedFiles: ".jpeg,.jpg,.png",
    maxFilesize: 2,
    paramName: "file",
    
    init: function () {
        var myDropzoneImage = this;
        
        this.on('sending', function(file, xhr, formData) {
            var data = $('#form').serializeArray();
            $.each(data, function(key, el) {
                formData.append(el.name, el.value);
            });
        });
        
        this.on("success", function (file, response) {
            handleDropzoneSuccess(response);
        });
    }
});

// Blog Banner Dropzone
var previewNodeBanner = document.querySelector("#dropzone-preview-list-banner");
previewNodeBanner.id = "";
var previewTemplateBanner = previewNodeBanner.parentNode.innerHTML;
previewNodeBanner.parentNode.removeChild(previewNodeBanner);

var dropzoneBanner = new Dropzone("#blog-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",
    
    init: function () {
        var myDropzoneBanner = this;
        
        this.on('sending', function(file, xhr, formData) {
            var data = $('#form').serializeArray();
            $.each(data, function(key, el) {
                formData.append(el.name, el.value);
            });
        });
        
        this.on("success", function (file, response) {
            handleDropzoneSuccess(response);
        });
    }
});

function handleDropzoneSuccess(response) {
    let result = JSON.parse(response);
    if (result.status == 'ok') {
        reload_table(); 
        $('.modal1').modal('hide');
        $('#id').val(''); 
        $('#get_old_image').val('');
        $('#get_old_banner').val('');
        $('#form').parsley().reset();
        $('#form')[0].reset();
        $('#submit').text('Save');
        $('#submit').attr('disabled', false);
        
        // Remove dropzone files
        dropzoneImage.removeAllFiles();
        dropzoneBanner.removeAllFiles();
        
        $(".alert-danger").hide();
        $(".alert-success").show();
        $(".alert-success-msg").html(result.message);                
        setTimeout(function () {
            $(".alert-success").fadeOut(500);
        }, 5000);
    } else {
        $('.modal1').modal('hide');
        $('#id').val(''); 
        $('#get_old_image').val('');
        $('#get_old_banner').val('');
        $('#form').parsley().reset();
        $('#form')[0].reset();
        $('#submit').text('Save');
        $('#submit').attr('disabled', false);
        
        // Remove dropzone files
        dropzoneImage.removeAllFiles();
        dropzoneBanner.removeAllFiles();
        
        $(".alert-success").hide();
        $(".alert-danger").show();
        $(".alert-danger-msg").html(result.message);
        setTimeout(function () {
            $(".alert-danger").fadeOut(500);
        }, 5000);
    }
}

$('#form').submit(function (e) {
    e.preventDefault();
    
    if ($('#form').parsley().isValid()) {
        var get_id = $('#id').val();
        var get_old_image = $('#get_old_image').val();
        var get_old_banner = $('#get_old_banner').val();
        
        var hasImageFile = $("ul#dropzone-preview-image").has("li").length > 0;
        var hasBannerFile = $("ul#dropzone-preview-banner").has("li").length > 0;
        
        // For new entry: require at least image
        if (get_id == 0 && !hasImageFile) {
            $("#blog-image-dropzone").addClass("dropzone_required");
            return false;
        }
        
        // Remove required class if valid
        $("#blog-image-dropzone").removeClass("dropzone_required");
        $("#blog-banner-dropzone").removeClass("dropzone_required");
        
        $('#submit').attr('disabled', true);
        $("#submit").html('<i class="mdi mdi-loading mdi-spin"></i> Processing...');
        
        // Check if we need to process dropzone or submit normally
        if (hasImageFile || hasBannerFile) {
            // Process dropzone uploads
            if (hasImageFile) {
                dropzoneImage.processQueue();
            } else if (hasBannerFile) {
                dropzoneBanner.processQueue();
            }
        } else {
            // Submit without dropzone (update with no new images)
            var formData = new FormData(this);
            
            $.ajax({
                url: BASEURL + 'blog/submit',
                type: "POST",
                data: formData,
                processData: false,
                contentType: false,
                cache: false,
                dataType: "JSON",
                success: function (result) {
                    if (result.status == 'ok') {
                        $('.modal1').modal('hide');
                        reload_table(); 
                        
                        $('#id').val(''); 
                        $('#get_old_image').val('');
                        $('#get_old_banner').val('');
                        $('#form').parsley().reset();
                        $('#form')[0].reset();
                        $('#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');
                        
                        $('#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);
                    }
                },
                error: function(xhr, status, error) {
                    console.log('AJAX Error:', xhr.responseText);
                    
                    $('#submit').html('Save');
                    $('#submit').attr('disabled', false);
                    
                    $('.modal1').modal('hide');
                    
                    var errorMsg = 'Error: ' + error;
                    if(xhr.responseText) {
                        try {
                            var errorData = JSON.parse(xhr.responseText);
                            errorMsg = errorData.message || errorMsg;
                        } catch(e) {
                            errorMsg = xhr.responseText.substring(0, 200);
                        }
                    }
                    
                    $(".alert-success").hide();
                    $(".alert-danger").show();
                    $(".alert-danger-msg").html(errorMsg);
                    setTimeout(function () {
                        $(".alert-danger").fadeOut(500);
                    }, 5000);
                }
            });
        }
    }
    
    return false;
});