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

$(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 + 'video-gallery/gallery-list',
            "type": "POST"
        },
        
        "columnDefs": [{
            "targets": [0, 4, 8], 
            "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>');
        },
    });
 
    load_categories();
    load_doctors(); 
    
    initializeDropzone();
});

function initializeDropzone() {
    Dropzone.autoDiscover = false;
    
    dropzone = new Dropzone(".dropzone", {
        url: "#",
        autoProcessQueue: false,
        uploadMultiple: false,
        maxFiles: 1,
        acceptedFiles: "image/jpeg,image/jpg,image/png",
        maxFilesize: 1,
        addRemoveLinks: true,
        previewsContainer: "#dropzone-preview",
        previewTemplate: document.querySelector("#dropzone-preview-list").innerHTML,
        init: function() {
            this.on("addedfile", function(file) {
                if (this.files.length > 1) {
                    this.removeFile(this.files[0]);
                }
                $(".dropzone").removeClass("dropzone_required");
            });
            
            this.on("error", function(file, message) {
                alert(message);
                this.removeFile(file);
            });
        }
    });
    
    document.querySelector("#dropzone-preview-list").innerHTML = "";
}

function load_categories()
{
    $.ajax({
        url: BASEURL + 'video-gallery/get_categories',
        type: "GET",
        dataType: "JSON",
        success: function (data) {
            var options = '<option value="">Select Category</option>';
            $.each(data, function(index, item) {
                options += '<option value="' + item.id + '">' + item.cat_name + '</option>';
            });
            $('#video_cat_id').html(options);
        },
        error: function() {
            console.log('Error loading categories');
        }
    });
}
 
function load_doctors()
{
    $.ajax({
        url: BASEURL + 'video-gallery/get_doctors',
        type: "GET",
        dataType: "JSON",
        success: function (data) {
            var options = '<option value="">Select Doctor</option>';
            $.each(data, function(index, item) {
                options += '<option value="' + item.id + '">' + item.doc_name + '</option>';
            });
            $('#doctor_id').html(options);
        },
        error: function() {
            console.log('Error loading doctors');
        }
    });
}

function reload_table() 
{
    table.ajax.reload(null, false);  
}

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

var save_method;

function add_data() 
{
    save_method = 'add';
    $('#id').val(''); 
    $('#get_old_doc').val('');     
    $("#img_preview").hide();
    $("#preview_img_tag").hide();
    
    if (dropzone.files.length > 0) {
        dropzone.removeAllFiles(true);
    }
    $("#dropzone-preview").html("");
    
    $(".dropzone").removeClass("dropzone_required");
    $(".dropzone").addClass("dropzone_required");  
    
    $('#form').parsley().reset();
    $('#form')[0].reset();
    $(".modal-title").html('Add Video Gallery');
    $('#submit').attr('disabled', false);    
    $("#submit").html('Save');
    
    load_categories();
    load_doctors();
}

function edit_data(id) 
{ 
     
    save_method = 'update';
    
    if (dropzone.files.length > 0) {
        dropzone.removeAllFiles(true);
    }
    $("#dropzone-preview").html("");
    
    $(".dropzone").removeClass("dropzone_required");  
    
    $('#form').parsley().reset();
    $('#form')[0].reset();
    $(".modal-title").html('Edit Video Gallery');
    $("#submit").html('Update');
    $('#submit').attr('disabled', false);
     
    load_categories();
    load_doctors();
    
    $('.modal1').modal('show');    

    $.ajax({
        url: BASEURL + 'videogallery/edit/' + id,
        type: "GET",
        dataType: "JSON",
        success: function (data) {
            console.log('Edit Data:', data);  
            
            if(data.error) {
                alert(data.error);
                return;
            }
            
            $('[name="id"]').val(data.id);
            
            setTimeout(function() {
                $('[name="video_cat_id"]').val(data.video_cat_id);
                
                 
                if(data.doctor_id) {
                    setTimeout(function() {
                        $('[name="doctor_id"]').val(data.doctor_id);
                    }, 500);
                }
            }, 300);
            
            $('[name="title"]').val(data.title); 
            $('[name="video_url"]').val(data.video_url);
            $('[name="get_old_doc"]').val(data.image); 
            $('.img_name_get').html(data.image); 
            $('[name="sequence_no"]').val(data.sequence_no);

            if (data.image != "" && data.image != null) 
            { 
                $("#img_preview").show(); 
                $("#preview_img_tag").attr("src", 'assets/images/videogallery/' + data.image).show();
            }
            else 
            {
                $("#img_preview").hide();
                $("#preview_img_tag").hide();
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('Edit Error:', jqXHR.responseText);  
            alert('Error! Get data from database: ' + errorThrown);
        }
    });
} 

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

$('#form').submit(function (e) {
    e.preventDefault();
    
    if ($('#form').parsley().isValid()) 
    { 
        var get_id = $('#id').val();
        var get_old_doc = $('#get_old_doc').val();
        
        console.log('Form Submit - ID:', get_id, 'Old Doc:', get_old_doc, 'Save Method:', save_method);  
        
        var hasDropzoneFile = dropzone.files.length > 0;
        var hasOldImage = get_old_doc != "";
        
        console.log('Has Dropzone File:', hasDropzoneFile, 'Has Old Image:', hasOldImage); 
        
        if (save_method == 'add' && !hasDropzoneFile) {
            $(".dropzone").addClass("dropzone_required");
            alert("Please upload a thumbnail image!");
            return false;
        }
        
        if (save_method == 'update' && !hasDropzoneFile && !hasOldImage) {
            $(".dropzone").addClass("dropzone_required");
            alert("Please upload a thumbnail image!");
            return false;
        }
        
        $('#submit').attr('disabled', true);
        $("#submit").html('<i class="mdi mdi-loading mdi-spin"></i> Processing...');
        
        var formData = new FormData(this);
        
        if (hasDropzoneFile) {
            formData.append('file', dropzone.files[0]);
            console.log('Dropzone file added to FormData');
        }
        
        for (var pair of formData.entries()) {
            console.log(pair[0] + ': ' + pair[1]);
        }
        
        $.ajax({
            url: BASEURL + 'video-gallery/submit',
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            cache: false,
            dataType: "JSON",
            success: function (result) 
            {
                console.log('Submit Result:', result);  
                
                if (result.status == 'ok') 
                {
                    reload_table(); 
                    $('.modal1').modal('hide');
                    
                    $('#id').val(''); 
                    $('#get_old_doc').val('');     
                    $('#form').parsley().reset();
                    $('#form')[0].reset();
                    
                    if (dropzone.files.length > 0) {
                        dropzone.removeAllFiles(true);
                    }
                    $("#dropzone-preview").html("");
                    
                    $('#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_method == 'add' ? 'Save' : 'Update');
                    $('#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('Submit Error:', xhr.responseText);
                $('#submit').html(save_method == 'add' ? 'Save' : 'Update');
                $('#submit').attr('disabled', false);
                
                alert('Error: ' + error);
            }
        });
    }
    
    return false;
});