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

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

    load_specialities();
});

 
function initializeCKEditors() {
  
    if (descriptionEditor) {
        descriptionEditor.destroy();
    }
    if (specialInterestEditor) {
        specialInterestEditor.destroy();
    }
    
    
    descriptionEditor = CKEDITOR.replace('description', {
        height: 150,
        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
    });
    
 
    specialInterestEditor = CKEDITOR.replace('special_interest', {
        height: 120,
        versionCheck: false,
        toolbar: [
            { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline'] },
            { name: 'paragraph', items: ['NumberedList', 'BulletedList'] },
            { name: 'links', items: ['Link', 'Unlink'] },
            { name: 'tools', items: ['Maximize'] }
        ],
        removePlugins: 'elementspath',
        resize_enabled: false
    });
}

function load_specialities()
{
    $.ajax({
        url: BASEURL + 'doctor/get_specialities',
        type: "GET",
        dataType: "JSON",
        success: function (data) {
            var options = '';
            $.each(data, function(index, item) {
                options += '<option value="' + item.id + '">' + item.cat_name + '</option>';
            });
            $('#doc_cat_id').html(options);
            
            // Initialize Select2 for multiple selection
            $('#doc_cat_id').select2({
                placeholder: "-- Select Specialities --",
                allowClear: true,
                width: '100%'
            });
        },
        error: function() {
            console.log('Error loading specialities');
        }
    });
}

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

$('.modal1').on('shown.bs.modal', function () {
    $('[name="doc_name"]').focus();
     
    setTimeout(function() {
        initializeCKEditors();
    }, 100);
});

$('.modal1').on('hidden.bs.modal', function () {
   
    if (descriptionEditor) {
        descriptionEditor.destroy();
        descriptionEditor = null;
    }
    if (specialInterestEditor) {
        specialInterestEditor.destroy();
        specialInterestEditor = null;
    }
    
    // Destroy Select2
    if ($('#doc_cat_id').hasClass("select2-hidden-accessible")) {
        $('#doc_cat_id').select2('destroy');
    }
});

var save_method;

function add_data() 
{
    save_method = 'add';
    $('#id').val(''); 
    $('#get_old_doc').val('');     
    $("#img_preview").hide();
    $("#preview_img_tag").hide();
    $("#dropzone-preview li").remove();
    $(".dropzone").removeClass("dropzone_required"); 
    $('#form').parsley().reset();
    $('#form')[0].reset();
    
     
    if (descriptionEditor) {
        descriptionEditor.setData('');
    }
    if (specialInterestEditor) {
        specialInterestEditor.setData('');
    }
    
    $(".modal-title").html('Add Doctor');
    $('#submit').attr('disabled', false);    
    $("#submit").html('Save');
   
    if ($('#doc_cat_id').hasClass("select2-hidden-accessible")) {
        $('#doc_cat_id').select2('destroy');
    }
    $('#doc_cat_id').val(null);
    
    load_specialities();
    
   
    setTimeout(function() {
        initializeCKEditors();
    }, 100);
}

function edit_data(id) 
{
    save_method = 'update';
    $("#dropzone-preview li").remove();
    $(".dropzone").removeClass("dropzone_required");
    $('#form').parsley().reset();
    $('#form')[0].reset();
    $(".modal-title").html('Edit Doctor');
    $("#submit").html('Update');
    $('#submit').attr('disabled', false);
    $('.modal1').modal('show');    

    
    load_specialities();

    $.ajax({
        url: BASEURL + 'doctor/edit/' + id,
        type: "GET",
        dataType: "JSON",
        success: function (data) {
            if(data.error) {
                alert('Error! ' + data.error);
                return;
            }
            
            $('[name="id"]').val(data.id);
            
            setTimeout(function () {
 
                $('#doc_cat_id').val(data.doc_cat_id).trigger('change');
            }, 300);
            
            $('[name="doc_cat_sub"]').val(data.doc_cat_sub);
            $('[name="doc_name"]').val(data.doc_name);
            $('[name="qualification"]').val(data.qualification);
            $('[name="contact_no"]').val(data.contact_no);
            $('[name="email"]').val(data.email);
            $('[name="consulting_days1"]').val(data.consulting_days1);
            $('[name="consulting_days2"]').val(data.consulting_days2);
            $('[name="sequence_no"]').val(data.sequence_no);
            $('[name="meta_title"]').val(data.meta_title);
            $('[name="meta_description"]').val(data.meta_description);
            $('[name="meta_keywords"]').val(data.meta_keywords);
            $('[name="get_old_doc"]').val(data.image);
            $('.img_name_get').html(data.image);
            
        
            setTimeout(function() {
                if (descriptionEditor) {
                    descriptionEditor.setData(data.description || '');
                }
                if (specialInterestEditor) {
                    specialInterestEditor.setData(data.special_interest || '');
                }
            }, 500);
             
            if (data.image != "" && data.image != null) 
            {
                $("#img_preview").show();
                $("#preview_img_tag").attr("src", BASEURL + '../assets/images/doctors/' + data.image).show();
            }
            else 
            {
                $("#img_preview").hide();
                $("#preview_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 + 'doctor/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 + 'doctor/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 + 'doctor/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: "Doctor has been deleted.",
                            icon: "success"
                        })
                        reload_table();
                    } else if (returnData.status == 'not') {
                        var tbc_name = returnData.tbc_name;
                        Swal.fire({
                            title: "Cancelled",
                            text: "Doctor 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"
            })
        }
    });
}); 

$('#form').submit(function (e) 
{
   
    if (descriptionEditor) {
        descriptionEditor.updateElement();
    }
    if (specialInterestEditor) {
        specialInterestEditor.updateElement();
    }
    
    if ($('#form').parsley().isValid()) 
    { 
        var get_id = $('#id').val();
        var get_old_doc = $('#get_old_doc').val();

        if ($("ul#dropzone-preview").has("li").length == 0 && get_id > 0 && get_old_doc != "") 
        {
            $(".dropzone").removeClass("dropzone_required");
            $('#submit').attr('disabled', true);
            e.preventDefault();
            $.ajax({
                url: BASEURL + 'doctor/submit',
                type: "POST",
                data: new FormData(this),
                processData: false,
                contentType: false,
                cache: false,
                async: false,
                dataType: "JSON",
                success: function (result) 
                {
                    if (result.status == 'ok') 
                    {
                        reload_table(); 
                        $('.modal1').modal('hide');
                        $('#id').val(''); 
                        $('#get_old_doc').val('');     
                        $('#form').parsley().reset();
                        $('#form')[0].reset();
                        
 
                        if (descriptionEditor) {
                            descriptionEditor.setData('');
                        }
                        if (specialInterestEditor) {
                            specialInterestEditor.setData('');
                        }
                        
                      
                        $('#doc_cat_id').val(null).trigger('change');
                        
                        $('#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 
                    {
                        $('.modal1').modal('hide');
                        $('#id').val(''); 
                        $('#get_old_doc').val('');     
                        $('#form').parsley().reset();
                        $('#form')[0].reset();
                        
                      
                        if (descriptionEditor) {
                            descriptionEditor.setData('');
                        }
                        if (specialInterestEditor) {
                            specialInterestEditor.setData('');
                        }
                        
                        $('#doc_cat_id').val(null).trigger('change');
                        
                        $('#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);
                    }
                }
            });
        } 
    }
});

Dropzone.autoDiscover = false; 

var previewTemplate, dropzone, dropzonePreviewNode = document.querySelector("#dropzone-preview-list");
inputMultipleElements = (dropzonePreviewNode.id = "", dropzonePreviewNode && (previewTemplate = dropzonePreviewNode.parentNode.innerHTML, dropzonePreviewNode.parentNode.removeChild(dropzonePreviewNode), 
    dropzone = new Dropzone(".dropzone", {
    url: BASEURL + 'doctor/submit',
    method: "post",
    previewTemplate: previewTemplate,
    previewsContainer: "#dropzone-preview", 
    autoProcessQueue: false,
    acceptedFiles: ".jpeg,.jpg,.png",
    maxFilesize: 2, // MB
    paramName: "file",

    init: function () 
    {        
        var myDropzone = this;
        $('#form').submit(function (e) 
        {
            
            if (descriptionEditor) {
                descriptionEditor.updateElement();
            }
            if (specialInterestEditor) {
                specialInterestEditor.updateElement();
            }
            
            $(".dropzone").addClass("dropzone_required");
            if ($('#form').parsley().isValid()) 
            {    
                e.preventDefault();
                var get_id = $('#id').val();
                if (($("ul#dropzone-preview").has("li").length > 0 && get_id == 0) || ($("ul#dropzone-preview").has("li").length == 0 && get_id > 0) || ($("ul#dropzone-preview").has("li").length > 0 && get_id > 0) )
                {
                    $(".dropzone").removeClass("dropzone_required");
                    $('#submit').attr('disabled', true);  
                    myDropzone.processQueue();           
                } 
                else 
                {
                    $('#submit').attr('disabled', false);  
                    $(".dropzone").addClass("dropzone_required");
                }
            }
        }); 
        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) 
        {
            let result = JSON.parse(response);
            if (result.status == 'ok') 
            {
                reload_table(); 
                $('.modal1').modal('hide');
                $('#id').val(''); 
                $('#get_old_doc').val('');     
                $('#form').parsley().reset();
                $('#form')[0].reset();
                
                 
                if (descriptionEditor) {
                    descriptionEditor.setData('');
                }
                if (specialInterestEditor) {
                    specialInterestEditor.setData('');
                }
                
                $('#doc_cat_id').val(null).trigger('change');
                
                $('#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 
            {
                $('.modal1').modal('hide');
                $('#id').val(''); 
                $('#get_old_doc').val('');     
                $('#form').parsley().reset();
                $('#form')[0].reset();
                
              
                if (descriptionEditor) {
                    descriptionEditor.setData('');
                }
                if (specialInterestEditor) {
                    specialInterestEditor.setData('');
                }
                
                $('#doc_cat_id').val(null).trigger('change');
                
                $('#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);
            }
        });
    }
})));