$(document).ready(function () {
    const curr_url = location.href;
    var sub_menu = null, items_pos = 0;
    const erase_form = document.createElement('form');
    if(initial !== null && $.trim(initial) !== ''){
        $('#left_menu li, .top-menu li').removeClass('active');
        let menus = document.querySelectorAll('#left_menu li');
        menus.forEach(_this => {
            if(_this.dataset.url == initial){
                _this.classList.add('active'); 
            };
        });
        menus = document.querySelectorAll('.top-menu li');
        menus.forEach(_this => {
            if(_this.dataset.url == initial){
                _this.classList.add('active');
            };
        });
        $( "#content" ).load(initial, function() {
            setTimeout(() => {
                $("#initial").addClass('hide');
            }, 1000);
        });
    }else{
        setTimeout(() => {
            $("#initial").addClass('hide');
        }, 1000);
    }
    
    setTimeout(function() {
        if($('.editor')){
            $('.editor').trumbowyg({
                btnsDef: {
                    // Define a custom button for upload
                    image: {
                        dropdown: ['insertImage', 'upload'],
                        ico: 'insertImage'
                    }
                },
                btns: [
                    ['viewHTML'],
                    ['undo', 'redo'],
                    ['formatting'],
                    ['strong', 'em', 'del'],
                    ['superscript', 'subscript'],
                    ['link'],
                    ['image'], // Use the custom image button
                    ['justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull'],
                    ['unorderedList', 'orderedList'],
                    ['horizontalRule'],
                    ['removeformat'],
                    ['fullscreen']
                ],
                plugins: {
                    upload: {
                        serverPath: '/upload_image', // Your server-side upload endpoint
                        fileFieldName: 'image'
                    }
                },
                autogrow: true
            });
        }
    }, 500);
    
    $('body').on('click', '#left_menu li, .top-menu li', function () {
        $('#left_menu li, .top-menu li').removeClass('active');
        $(this).addClass('active');
        const url = $(this).data('url');
        let new_url = curr_url;
        new_url = new_url.replace('home', url);
        if(url == 'sign-out'){
            location.href = new_url;
        }
        $( "#content" ).load(new_url, function() {
            console.log('Loaded');
        });
    });

    $('body').on('click','#left_menu li', function(){
        sub_menu = $(this).data('url');
    });

    $('body').on('click', '.dashboard .blocks li', function () {
        const menu = $(this).data('menu');
        $('#left_menu li:nth-child('+menu+')').click();
    });

    $('body').on('click', '.main-menu li', function () {
        const url = $(this).data('url');
        location.href = base_url + url;
    });

    $('body').on('click','.upload, .add, .update, .sent_reply', function(){
        const modal = $(this).data('modal');
        $('#'+modal).removeClass('hide');
    });

    $('body').on('click','.item-update', function(){
        const modal = $(this).data('modal');
        const page = $(this).data('page');
        const new_url = curr_url.replace('home', '');
        $("#edit_modal_content").load(new_url + page, function() {
            setTimeout(function() {
                $('#'+modal).removeClass('hide');
            }, 1000);
            setTimeout(function() {
                if($('.editor')){
                    $('.editor').trumbowyg({
                        btnsDef: {
                            // Define a custom button for upload
                            image: {
                                dropdown: ['insertImage', 'upload'],
                                ico: 'insertImage'
                            }
                        },
                        btns: [
                            ['viewHTML'],
                            ['undo', 'redo'],
                            ['formatting'],
                            ['strong', 'em', 'del'],
                            ['superscript', 'subscript'],
                            ['link'],
                            ['image'], // Use the custom image button
                            ['justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull'],
                            ['unorderedList', 'orderedList'],
                            ['horizontalRule'],
                            ['removeformat'],
                            ['fullscreen']
                        ],
                        plugins: {
                            upload: {
                                serverPath: '/upload_image', // Your server-side upload endpoint
                                fileFieldName: 'image'
                            }
                        },
                        autogrow: true
                    });
                }
            }, 500);
        });
    });

    $('body').on('click','.show-hide', function(){
        const id = $(this).data('id');
        if($('#'+id).attr('type') == 'password'){
            $('#'+id).attr('type','text');
            $(this).html('<i class="fa-solid fa-eye-slash"></i>');
        }else{
            $('#'+id).attr('type','password');
            $(this).html('<i class="fa-solid fa-eye"></i>');
        }
    });

    $('body').on('click', '.close_modal', function(){
        const modal = $(this).data('modal');
        $('#'+modal).addClass('hide');
        if(sub_menu != null){
            $( "#content" ).load(sub_menu, function() {
                console.log('Loaded');
            });
        }
        if($("#edit_modal_content")){
            $("#edit_modal_content").html('');
        }
    });

    $('body').on('click', '.th-con .add', function () {
        const modal = $(this).data('modal');
        $('#' + modal).removeClass('hide');
    });

    $('body').on('click', '.add-element button', function(){
        const container = $(this).data('div') ? $('#element_con_edit') : $('#element_container');
        const type = $(this).data('type');
        var div = ``;
        items_pos += 1;
        switch (type) {
            case 'tiny_image':
                div = `<div class="element-blocks" id="tiny_img_${items_pos}">
                            <div class="form-block">
                                <label for="extra_small_image_${items_pos}">Extra Small Image(Optional)<span data-position="${items_pos}" data-type="tiny_image" class="erase-items"><i class="fa-solid fa-trash"></i></span></label>
                                <input type="hidden" name="position[]" value="${items_pos}"/>
                                <input type="file" name="extra_small_image_${items_pos}" id="extra_small_image_${items_pos}" required>
                                <input type="text" name="extra_small_image_caption_${items_pos}" id="extra_small_image_caption_${items_pos}" placeholder="Enter photo caption">
                                <ul class="hints">
                                    <li>Image size : 190x118 Pixels</li>
                                </ul>
                            </div>
                        </div>`;
                break;
            case 'small_image':
                div = `<div class="element-blocks" id="small_img_${items_pos}">
                            <div class="form-block">
                                <label for="small_image_${items_pos}">Small Image(Optional)<span data-position="${items_pos}" data-type="small_image" class="erase-items"><i class="fa-solid fa-trash"></i></span></label>
                                <input type="hidden" name="position[]" value="${items_pos}"/>
                                <input type="file" name="small_image_${items_pos}" id="small_image_${items_pos}" required>
                                <input type="text" name="small_image_caption_${items_pos}" id="small_image_caption_${items_pos}" placeholder="Enter photo caption">
                                <ul class="hints">
                                    <li>Image size : 255x276 Pixels</li>
                                </ul>
                            </div>
                        </div>`;
                break;
            case 'paragraph':
                div = `<div class="element-blocks" id="div_pos_${items_pos}">
                            <div class="form-block">
                                <label for="small_paragraph_${items_pos}">Paragraph(Optional)<span data-position="${items_pos}" data-type="paragraph" class="erase-items"><i class="fa-solid fa-trash"></i></span></label>
                                <input type="hidden" name="position[]" value="${items_pos}"/>
                                <textarea name="small_paragraph_${items_pos}" id="small_paragraph_${items_pos}" placeholder="Enter text here.." required></textarea>
                            </div>
                        </div>`;
                break;
            default:
                break;
        }
        container.append(div);
    });

    $('body').on('click','.erase-items', function(){
        const type = $(this).data('type');
        const position = $(this).data('position');
        switch (type) {
            case 'tiny_image':
                $('#tiny_img_'+position).remove();
                break;
            case 'small_image':
                $('#small_img_'+position).remove();
                break;
            case 'paragraph':
                $('#div_pos_'+position).remove();
                break;
            default:
                break;
        }
        return;
    });

    $('body').on('click', '.view', function () {
        
    });

    $('body').on('click','.status_update', function(){
        let text_view = '';
        if($(this).data('status') == 1){
            $(this).data('status', 0)
            text_view = 'Hidden';
        }else{
            $(this).data('status', 1)
            text_view = 'Show';
        }
        console.log($(this).data('status'));
        $('#review_status').html(text_view);
    });

    $('body').on('click','.erase, .remove, .item-erase', function(){
        const page = $(this).data('page');
        const serial = $(this).data('serial');
        $('#delete_confirm').removeClass('hide');
        $('body').append(erase_form);
        $(erase_form).attr('id', 'confirm_form');
        $(erase_form).attr('method', 'POST');
        $(erase_form).attr('action', page);
        let inputs = `<input type="hidden" name="action" value="remove"><input type="hidden" name="serial" value="${serial}">`;
        $(erase_form).append(inputs);
    });

    $('body').on('click','.item-remove', function(){
        const page = $(this).data('page');
        const serial = $(this).data('serial');
        $('#delete_confirm').removeClass('hide');
        $('body').append(erase_form);
        $(erase_form).attr('id', 'confirm_form');
        $(erase_form).attr('method', 'POST');
        $(erase_form).attr('action', page);
        let inputs = `<input type="hidden" name="action" value="items-remove"><input type="hidden" name="serial" value="${serial}">`;
        $(erase_form).append(inputs);
    });

    $('body').on('click','#del_cancelled', function(){
        $('#delete_confirm').addClass('hide');
    });

    $('body').on('submit', 'form', function (e) {
        e.preventDefault();
        const alert = "alert_model";
        let formId = $(this).attr('id'), type = $(this).attr('method'), url = $(this).attr('action');
        var form_data = new FormData(document.getElementById(formId));
        let msg = "Processing.. Please wait";
        alert_modal(5, msg);
        const new_url = curr_url.replace('home', url);
        if(!$('#delete_confirm').hasClass('hide')){
            $('#delete_confirm').addClass('hide');
        }
        $.ajax({
            type: type,
            url: new_url,
            data: form_data,
            contentType: false,
            cache: false,
            processData: false,
            beforeSend: function () {
                alert_modal(5, msg);
        console.log(new_url);
            },
            success: function (response) {
                result = JSON.parse(response);
                console.log(result);
                alert_modal(result.status, result.message);
                if(result.status == 1){
                    $('#'+formId)[0].reset();
                }
            },
            error: function (v) {
                let error = JSON.parse(v.responseText);
                alert_text(error.message, 0);
                if($(erase_form)){
                    $(erase_form).html('');
                    $(erase_form).removeAttr('id');
                    $(erase_form).removeAttr('method');
                    $(erase_form).removeAttr('action');
                }
            },
            complete: function () {
                if(result.load == 1){
                    setTimeout(() => {
                        location.reload();
                    }, 1000);
                }else{
                    setTimeout(() => {
                        $('#' + alert + ' .alert-content #alert_msg').html(msg);
                        $('#' + alert).addClass('hide');
                    }, 1500);
                }
                if(result.content){
                    $("#content").load(result.content, function() {
                        if(result.modal && result.modal != 0){
                            $('.upload, .add, .update, .sent_reply').trigger('click');
                        }
                    });
                }
                if($(erase_form)){
                    $(erase_form).html('');
                    $(erase_form).removeAttr('id');
                    $(erase_form).removeAttr('method');
                    $(erase_form).removeAttr('action');
                }
            }
        });
        return false;
    });

    function alert_modal(status, msg) {
        const alert = 'alert_model';
        const img_src = base_url + 'assets/images/icon/';
        if (status == 5) {
            $('#' + alert + ' .alert-head img').attr("src", img_src + 'loading.gif');
        } else if (status == 0) {
            $('#' + alert + ' .alert-head img').attr("src", img_src + 'wrong.gif');
        } else if (status == 1) {
            $('#' + alert + ' .alert-head img').attr("src", img_src + 'success.gif');
        }
        $('#' + alert + ' .alert-content #alert_msg').html(msg);
        $('#' + alert).removeClass('hide');
    }
});