/** =============================================================
 * LT CMS allows users to create block posts, this makes it easy for users
 * with specific post or blog needs that can have a rythm and flow in reading
 * LT CMS is a product of LWEGATECH under MIT LICENSE
 * So this js will have all POST BLOCK Activity
 *=================================================================*/
// Auto expand the Text Area as content increases   
$("textarea").each(function () {
  this.setAttribute("style", "height:" + (this.scrollHeight) + "px;overflow-y:hidden;border:0px");
}).on("input", function () {
  this.style.height = "auto";
  this.style.height = (this.scrollHeight) + "px";
}).on("click", function () {
  // Display the entire content when clicked to edit
  this.style.height = (this.scrollHeight) + "px";
});
 

/**
 *  UNIFIED BLOCK JS 
 *  This matches with new DB table where all blocks are originating
 *  from
*/
$(document).ready(function() {
    // Handle block type selection
    $('.dropdown-menu a').on('click', function(e) {
        e.preventDefault();
        let blockType = $(this).data('block');

        // Reset form
        $('#block-form-fields')[0];
        $('[name="block_type"]').val(blockType); 
        $('[name="id"]').val('');

        // Hide all fields
        $('.block-field').hide();

        // Show relevant field
        $('.block-' + blockType).show();

        $('.block-element').show();
    });

    // Handle block submission
    $("#save-block-btn").click(function(e) {
        e.preventDefault();
        
        // Get all the block form fields
        const blockFields = $('#block-form-fields').find('input, select, textarea, [contenteditable]');
        
        // Prepare the hidden block form
        const blockForm = $('#block-form');
        blockForm.empty(); // Clear previous fields
        
        // Add CSRF token
        blockForm.append($('<input>').attr({
            type: 'hidden',
            name: 'csrf_test_name',
            value: $('[name="csrf_test_name"]').val()
        }));
        
        // Clone all fields to the hidden form
        blockFields.each(function() {
            const originalField = $(this);
            
            // Handle select elements specially
            if (originalField.is('select')) {
                const clonedSelect = originalField.clone();
                // Preserve the selected value
                clonedSelect.val(originalField.val());
                blockForm.append(clonedSelect);
            } 
            // Handle file inputs specially
            else if (originalField.attr('type') === 'file') {
                const clonedFileInput = originalField.clone();
                // For file inputs, we need to transfer the files
                const files = originalField[0].files;
                if (files && files.length > 0) {
                    const dataTransfer = new DataTransfer();
                    for (let i = 0; i < files.length; i++) {
                        dataTransfer.items.add(files[i]);
                    }
                    clonedFileInput[0].files = dataTransfer.files;
                }
                blockForm.append(clonedFileInput);
            }
            // Handle all other input types
            else {
                const clonedField = originalField.clone();
                blockForm.append(clonedField);
            }
        });
        
        // Submit the hidden form via AJAX
        const formData = new FormData(blockForm[0]);
        
        $.ajax({
            type: 'POST',
            url: blockForm.attr('action'),
            data: formData,
            processData: false,
            contentType: false,
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            beforeSend: function() {
                $('#save-block-btn').attr("disabled", "disabled");
                $('#save-block-btn').text('Please wait...');
            },
            success: function(response) {
                const newToken = response.csrfHash;
                $('meta[name="X-CSRF-TOKEN"]').attr('content', newToken);
                $('[name="csrf_test_name"]').val(newToken);

                if (response.success == true) {
                    toastr.success(response.msg);
                    window.location.reload();
                } else {
                    toastr.error(response.msg);
                }
                $('#save-block-btn').removeAttr("disabled");
                $('#save-block-btn').text('Save Block');
            },
            error: function(xhr, status, error) {
                console.error(xhr, status, error);
                $('#save-block-btn').removeAttr("disabled");
                $('#save-block-btn').text('Save Block');
                toastr.error('An error occurred. Please try again.');
            }
        });
    });
});


function editBlock(id) {
    $.ajax({
        url: base_url + "administrator/posts/block/get-block/" + id,
        type: "GET",
        dataType: "JSON",
        success: function (response) {
            if (response.success) {
                let data = response.data;

                // Reset all fields
                $('#edit-block-form')[0].reset();
                $('.block-field').hide();

                // Fill hidden fields
                $('[name="id"]').val(data.id);
                $('[name="block_type"]').val(data.block_type);

                // Show correct block fields and populate values
                switch (data.block_type) {
                    case 'text':
                        $('.block-text').show();
                        $('[name="description"]').val(data.content);
                        break;

                    case 'image':
                        $('.block-image').show();
                        $('#preview-image').attr('src', data.photo).removeClass('d-none');
                        $('[name="caption"]').val(data.caption);
                        break;

                    case 'heading':
                        $('.block-heading').show();
                        $('[name="heading"]').val(data.heading);
                        $('[name="heading_type"]').val(data.heading_type);
                        $('[name="color"]').val(data.color);
                        break;

                    case 'list':
                        $('.block-list').show();
                        $('[name="list_content"]').val(data.content);
                        $('[name="list_type"]').val(data.list_type);
                        break;
                    
                    case 'cards':
                        $('.block-cards').show();
                        $('[name="card_name"]').val(data.heading);
                        break;
                        
                    case 'stats':
                        $('.block-stats').show();
                        $('[name="stats_title"]').val(data.heading);
                        break;
                    
                    case 'gallery':
                        $('.block-gallery').show();
                        $('[name="gallery_title"]').val(data.heading);
                        $('[name="gallery_description"]').val(data.content);
                        break;

                    case 'code':
                        $('.block-code').show();
                        $('[name="code"]').val(data.code);
                        break;

                    case 'advert':
                        $('.block-advert').show();
                        $('[name="advert_code"]').val(data.advert_code);
                        break;
                }

                $('#editBlockModal').modal('show');
            } else {
                toastr.error(response.msg);
            }
        }
    });
}
//DELETE
function deleteBlock(id) {
    if (confirm('Are you sure you want to delete this block?')) {
        window.location.href = base_url + "administrator/posts/block/delete/" + id;
    }
}

/** =====================================================
 *  CHILD BLOCKS
 *=======================================================*/
    function openChildItemModal(type, blockId) {
        $('#child-item-form')[0];
        $('[name="item_type"]').val(type);
        $('[name="block_id"]').val(blockId);

        $('.stats-field').toggle(type === 'stats');
        $('.gallery-field').toggle(type === 'gallery');
        $('.cards-field').toggle(type === 'cards');
        $('.cards-gallery-field').toggle(type !== 'stats');
        $('.cards-stats-field').toggle(type !== 'gallery');

        $('#childItemModal').modal('show');
        $('.modal-title').text('Manage Item '+ type);
        $('.sbtn').text('Save Item');

    }
    function editChildItem(id, type) {
        $.get(base_url + 'administrator/posts/block/items/get-block/' + id, function (response) {
            if (response.success) {
                let data = response.data;
                openChildItemModal(type, data.block_id);

                $('[name="id"]').val(data.id);
                $('[name="block_id"]').val(data.block_id);
                $('[name="item_type"]').val(data.item_type);
                $('[name="title"]').val(data.title);
                $('[name="value"]').val(data.value || '');
                $('[name="caption"]').val(data.caption || '');
                $('[name="icon"]').val(data.icon);
                $('[name="link"]').val(data.link || '');
                $('[name="description"]').val(data.description || '');

                if(data.photo !== Null){
                    $("#display-image").html("<img src="+data.photo+" style='width:40px;height:40px;object-fit:cover'>");
                }
            }
        });
    }

    function deleteChildItem(id, type) {
        var confirmation = confirm('Are you sure want to delete this '+type +' Item');
        if(confirmation == true){
        window.location.href = base_url + ('administrator/posts/block/items/delete/')+ id;
        }
    }

    // Save child item
    $('#child-item-form').on('submit', function (e) {
        e.preventDefault();
        $.ajax({
            url: base_url + 'administrator/posts/block/items/save',
            type: 'POST',
            data: new FormData(this),
            processData: false,
            contentType: false,
            success: function (response) {
                if (response.success) {
                    toastr.success(response.msg);
                    $('#childItemModal').modal('hide');
                    location.reload();
                }
            }
        });
    });









