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

$(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 + 'admin_email_format/ajax_list',
            "type": "POST"
        },
        
        "columnDefs": [{
            "targets": [0, 3, 5], 
            "orderable": false,        
        }],

        "fnInitComplete": function () 
        { 
           
        },
    });
});

// Initialize CKEditor for Top Description
function initializeTopDescriptionEditor() {
    if (topDescriptionEditor) {
        topDescriptionEditor.destroy();
    }

    topDescriptionEditor = CKEDITOR.replace('top_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
    });
}

// Initialize CKEditor for Bottom Description
function initializeBottomDescriptionEditor() {
    if (bottomDescriptionEditor) {
        bottomDescriptionEditor.destroy();
    }

    bottomDescriptionEditor = CKEDITOR.replace('bottom_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() {
        initializeTopDescriptionEditor();
        initializeBottomDescriptionEditor();
    }, 100);
});

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

function edit_data(id) 
{
    $('#form').parsley().reset();
    $('#form')[0].reset();
    $(".modal-title").html('Edit Admin Email Format');
    $("#submit").html('Update');
    $('#submit').attr('disabled', false);
    $('.modal1').modal('show');    

    $.ajax({
        url: BASEURL + 'admin_email_format/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="subject"]').val(data.subject);

            // Set data in CKEditor instances
            if (topDescriptionEditor) {
                topDescriptionEditor.setData(data.top_description || '');
            } else {
                setTimeout(function() {
                    if (topDescriptionEditor) {
                        topDescriptionEditor.setData(data.top_description || '');
                    }
                }, 500);
            }

            if (bottomDescriptionEditor) {
                bottomDescriptionEditor.setData(data.bottom_description || '');
            } else {
                setTimeout(function() {
                    if (bottomDescriptionEditor) {
                        bottomDescriptionEditor.setData(data.bottom_description || '');
                    }
                }, 500);
            }

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

$('#form').submit(function (e) {
    e.preventDefault();
    
    // Update CKEditor content to textareas
    if (topDescriptionEditor) {
        topDescriptionEditor.updateElement();
    }
    if (bottomDescriptionEditor) {
        bottomDescriptionEditor.updateElement();
    }
    
    if ($('#form').parsley().isValid()) 
    { 
        $('#submit').attr('disabled', true);
        $("#submit").html('<i class="mdi mdi-loading mdi-spin"></i> Processing...');
        
        var formData = $(this).serialize();
        
        console.log('Form Data:');
        console.log(formData);
        
        $.ajax({
            url: BASEURL + 'admin_email_format/update_data',
            type: "POST",
            data: formData,
            dataType: "JSON",
            success: function (result) 
            {
                console.log('Response:', result);
                
                if (result.status == 'ok' || result == 'ok') 
                {
                    $('.modal1').modal('hide');
                    reload_table(); 
                    
                    $('#id').val(''); 
                    $('#form').parsley().reset();
                    $('#form')[0].reset();
                    
                    if (topDescriptionEditor) {
                        topDescriptionEditor.setData('');
                    }
                    if (bottomDescriptionEditor) {
                        bottomDescriptionEditor.setData('');
                    }
                    
                    $('#submit').html('Update');
                    $('#submit').attr('disabled', false);
                    
                    $(".alert-danger").hide();
                    $(".alert-success").show();
                    $(".alert-success-msg").html('Admin Email Format Updated Successfully.');                        
                    setTimeout(function () {
                        $(".alert-success").fadeOut(500);
                    }, 5000);
                } 
                else 
                {
                    $('.modal1').modal('hide');
                    
                    $('#submit').html('Update');
                    $('#submit').attr('disabled', false);
                    
                    $(".alert-success").hide();
                    $(".alert-danger").show();
                    $(".alert-danger-msg").html('Failed to update email format.');
                    setTimeout(function () {
                        $(".alert-danger").fadeOut(500);
                    }, 5000);
                }
            },
            error: function(xhr, status, error) {
                console.log('AJAX Error:', xhr.responseText);
                
                if (xhr.status === 200 || xhr.status === 302) {
                    $('.modal1').modal('hide');
                    reload_table(); 
                    
                    $('#id').val(''); 
                    $('#form').parsley().reset();
                    $('#form')[0].reset();
                    
                    if (topDescriptionEditor) {
                        topDescriptionEditor.setData('');
                    }
                    if (bottomDescriptionEditor) {
                        bottomDescriptionEditor.setData('');
                    }
                    
                    $('#submit').html('Update');
                    $('#submit').attr('disabled', false);
                    
                    $(".alert-danger").hide();
                    $(".alert-success").show();
                    $(".alert-success-msg").html('Admin Email Format Updated Successfully.');                        
                    setTimeout(function () {
                        $(".alert-success").fadeOut(500);
                    }, 5000);
                } else {
                    $('#submit').html('Update');
                    $('#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 = 'Failed to update email format';
                        }
                    }
                    
                    $(".alert-success").hide();
                    $(".alert-danger").show();
                    $(".alert-danger-msg").html(errorMsg);
                    setTimeout(function () {
                        $(".alert-danger").fadeOut(500);
                    }, 5000);
                }
            }
        });
    }
    
    return false;
});