/**
 * =============================================================================
 * @package         Blue Raven (Free Version)
 * @Plugin URI      https://enterrahost.com/plugins/blue-raven
 * 
 * @Author          EnterraHost
 * @Author URI      https://enterrahost.com
 * @License         GPL-2.0-or-later
 *  
 * @Copyright       (c) 2025 EnterraHost
 * @Contents        Javascript for the Tools Page
 *
 * =============================================================================
 * 
 * || INDEX:
 * ||   - SIDE BAR
 * ||   - LOAD SIDE BAR PAGES
 * ||   - TOOLS AJAX
 * ||   
 * =============================================================================
 */
 
(function ($) {
    $(document)
    
/*
============================================================
    SIDE BAR
============================================================
*/
    
    /* =========== Mail =========== */
    
        .on('click', '#tools-sb-mail', function (e) {
            $(".inner-side-bar").addClass('hidden');
            const tool = $(this).data('tool');
            BlueRaven_loadTool(tool);
        })
        
    /* =========== searchability =========== */
    
        .on('click', '#tools-sb-searchability', function (e) {
            $(".inner-side-bar").addClass('hidden');
            $("#sb-dd-searchability").toggleClass('hidden');
        })
    /* =========== Cookie Management =========== */
    
        .on('click', '#tools-sb-cookie', function (e) {
            $(".inner-side-bar").addClass('hidden');
            const tool = $(this).data('tool');
            BlueRaven_loadTool(tool);
        })

    /* =========== Alt Management =========== */
    
        .on('click', '#tools-sb-alt', function (e) {
            $(".inner-side-bar").addClass('hidden');
            const tool = $(this).data('tool');
            BlueRaven_loadTool(tool);
        })        
        
    /* =========== Sub Items =========== */
        
        .on('click', '.inner-tool-item', function (e) {
            const tool = $(this).data('tool');
            BlueRaven_loadTool(tool);
        })
        
/*
============================================================
    LOAD SIDE BAR PAGES
============================================================
*/

        function BlueRaven_loadTool(pageName) {
            $.ajax({
                url: blueRavenTools.ajaxurl,
                type: 'POST',
                data: {
                    action: 'blue_raven_load_tools_sub_container',
                    page: pageName,
                    nonce: blueRavenTools.load_nonce
                },
                beforeSend: BlueRaven_showLoadingState,
                success: BlueRaven_showToolContent,
                error: BlueRaven_showErrorState
            });
        }
        
        function BlueRaven_showLoadingState() { $('#tools-sub-container').html('<p>Loading...</p>');}
        function BlueRaven_showToolContent(response) { $('#tools-sub-container').html(response);}
        function BlueRaven_showErrorState() { $('#tools-sub-container').html('<p class="error">Error loading tool</p>');}    
        
})(jQuery);

/*
============================================================
    TOOLS AJAX
============================================================
*/ 
    
let currentTool = '';
        
function BlueRaven_toolOperation(content, subaction, toolButton, returnCode = false) {
    currentTool = toolButton;
    content = Array.isArray(content) ? content : [content];
    
    return fetch(blueRavenTools.ajaxurl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        },
        body: new URLSearchParams([
            ['action', 'blue_raven_tools'],
            ['subaction', subaction],
            ...content.map((item, index) => [`content[${index}]`, item]),
            ['nonce', blueRavenTools.tools_nonce]
        ])
    })
    .then(response => response.ok ? response.text() : Promise.reject('Network error'))
    .then(data => {
        if(returnCode === true){
            return data;
        }else{
            alert(data);
            return true;
        }
    })
    .catch(() => {
        alert("There was an error. Please contact Support.");
        return false;
    });
}

/*
============================================================
    TOOLS
============================================================
*/

(function ($) {
    $(document)
                
    /* =========== Save Alt Text =========== */               
    
                
        .on('click', '.save-alt-text-tools', function(e) { 
            e.preventDefault();
            
            const $wrapper = $(this).closest('.image-alt-item');
            const imageId = $wrapper.data('image-id');
            const altText = $wrapper.find('input[name="alt-text"]').val();
        
            let content = [imageId, altText]
            
            BlueRaven_toolOperation(content, 'save alt text', '')
                .then(() => {
                    $wrapper.remove();
                })
                .catch(() => {
                    console.error('Alt text save failed.');
                });
        })

    /* =========== ANALYTICS TAG =========== */       

        .on('click', 
            '#enable-site-analytics, ' +
            '#enable-google-analytics, ' +
            '#enable-meta-analytics, ' +
            '#enable-microsoft-analytics, ' +
            '#enable-ahref-analytics', 
            function (e) {
                            
            let code = null; 

            const $checkbox = $(this);
            const isChecked = $checkbox.prop('checked');
            const toolId = $checkbox.attr('id');
            const codeInputId = toolId.replace('enable-', '') + '-key';
            if (typeof codeInputId === 'string' && $('#' + codeInputId).length) {code = $('#' + codeInputId).val()?.trim() ?? null;}
            const errorElementId = toolId.replace('enable-', '') + '-error-message';
            const $error = $('#' + errorElementId);
            const content = [isChecked, code];
                            
    /* =========== Map tool IDs to their validation rules and error messages =========== */                      
    
            const validationRules = {
                'enable-google-analytics': {
                    pattern: /^[a-z0-9/+ -]+$/i,
                    emptyError: 'Error: You need a Google G4A Analytics Code to enable this.',
                    formatError: 'Error: The Google G4A Analytics Code has an incorrect format.'
                },
                'enable-meta-analytics': {
                    pattern: /^[a-z0-9/+ -]+$/i,
                    emptyError: 'Error: You need a Meta Pixel Analytics Code to enable this.',
                    formatError: 'Error: The Meta Pixel Analytics Code has an incorrect format.'
                },
                'enable-microsoft-analytics': {
                    pattern: /^[a-z0-9/+ -]+$/i,
                    emptyError: 'Error: You need a Microsoft Clarity Analytics Code to enable this.',
                    formatError: 'Error: The Microsoft Clarity Analytics Code has an incorrect format.'
                },
                'enable-ahref-analytics': {
                    pattern: /^[a-z0-9/+ -]+$/i,
                    emptyError: 'Error: You need an AHREF Analytics Code to enable this.',
                    formatError: 'Error: The AHREF Analytics Code has an incorrect format.'
                }
            };
                            
    /* =========== Special case for site analytics which doesn't need validation =========== */    

            if (toolId === 'enable-site-analytics') return BlueRaven_toolOperation(content, 'enable site analytics', '');
                            
    /* =========== Validation for other tools =========== */                           
    
            if (isChecked) {
                if (code === '') { $error.text(validationRules[toolId].emptyError); $checkbox.prop('checked', false).trigger('change'); return;}
                if (!validationRules[toolId].pattern.test(code)) {  $error.text(validationRules[toolId].formatError); $checkbox.prop('checked', false).trigger('change'); return; }
            }
                                
    /* =========== If validation passed or checkbox was unchecked =========== */
    
            $error.text('');
            const operationName = 'enable ' + toolId.replace('enable-', '').replace('-analytics', '') + ' analytics';
            BlueRaven_toolOperation(content, operationName, '');
        }
    )

    /* =========== Meta Description =========== */                
                
    .on('input', '.meta-description', function () {
        const $input = $(this);
        const length = $input.val().length;
        const $charCount = $input.closest('.page-meta').find('.char-count span');
        $charCount.text(length);
    
        if (length > 160) { $charCount.parent().addClass('br-error'); } else { $charCount.parent().removeClass('br-error'); }
    })

    /* =========== Meta Save =========== */   

    .on('click', '.save-meta', function(e) { 
        const $wrapper = $(this).closest('.page-meta');
        const pageId = $wrapper.data('page-id');
        const metaDesc = $wrapper.find('.meta-description').val();
        const metaKeywords = $wrapper.find('.meta-tags').val();
        
        if (metaDesc.length > 160) { alert('Meta description exceeds recommended length'); return;}
        
        let content = JSON.stringify({ pageId: pageId, metaDesc: metaDesc,metaKeywords: metaKeywords });
        
        BlueRaven_toolOperation(content, 'save meta for page', '')
            .then(() => {
                const tagsVal = $wrapper.find('input[name="meta-tags"]').val()?.trim();
                const descVal = $wrapper.find('input[name="meta-description"]').val()?.trim();
                const $badge = $wrapper.find('.br-badge');
            
                const bothFilled = tagsVal && descVal;
            
                if (bothFilled && $badge.hasClass('warning')) { $badge .removeClass('warning').addClass('success').html('✓ Set');} else if (!bothFilled && $badge.hasClass('success')) { $badge .removeClass('success').addClass('warning').html('✗ Missing'); }
            })
            .catch(() => { console.error('Meta text save failed.'); });
    }) 

    /* =========== Meta Enable =========== */   

    .on('input', '#enable-site-meta', function () {
        const isChecked = $('#enable-site-meta').prop('checked');
        let content = isChecked;
        BlueRaven_toolOperation(content, 'enable site meta', '')
    }) 

    /* =========== Save robots txt =========== */                
                
    .on('click', '#save-robots-txt', function (e) {
        const content = $('#robots-text-area').val();
        BlueRaven_toolOperation(content, 'create save robots file', '#tools-sb-sub-robots')
    })

    /* =========== OverAll Site Analytics =========== */

    .on('click', '#enable-site-map', function (e) {
        const isChecked = $('#enable-site-map').prop('checked');
        let content = isChecked;
        BlueRaven_toolOperation(content, 'enable site map', '');
    })

    /* =========== Enable Index Now =========== */

    .on('click', '#enable-indexnow-site-map', function (e) {
                        
        const isChecked = $('#enable-indexnow-site-map').prop('checked');
        const code = $('#bing-key').val().trim();
        const $error = $('#bing-verification-error-message');
        let content = [isChecked, code]
        
        if (isChecked) {
            if (code === '') {
                $error.text('Error: You need a Bing Verification Code to enable this.');
                $('#enable-indexnow-site-map').prop('checked', false);
                $('#enable-indexnow-site-map').trigger('change');
            } else if (!/^[a-z0-9]+$/i.test(code)) {
                $error.text('Error: The Bing Verification Code has an incorrect format.');
                $('#enable-indexnow-site-map').prop('checked', false);
                $('#enable-indexnow-site-map').trigger('change');
            } else {
                $error.text(''); 
                BlueRaven_toolOperation(content, 'enable bing site map', '');
            }
        } else {
            $error.text('');
            BlueRaven_toolOperation(content, 'enable bing site map', '');
        }
        
    })


    /* =========== OverAll Site Verification =========== */

    .on('click', '#enable-site-verification', function (e) {
    
        const isChecked = $('#enable-site-verification').prop('checked');
        const code = ""; 
        let content = [isChecked, code];
        BlueRaven_toolOperation(content, 'enable site verification', '');
    
    })
                    
    /* =========== Bing =========== */
    
    .on('click', '#enable-bing-verification', function (e) {
        BlueRaven_handleVerificationToggle(
            '#enable-bing-verification',
            '#bing-key',
            '#bing-verification-error-message',
            'enable bing verification',
            /^[a-z0-9]+$/i
        );
    })
                    
    /* =========== Google =========== */
    
    .on('click', '#enable-google-verification', function (e) {
        BlueRaven_handleVerificationToggle(
            '#enable-google-verification',
            '#google-key',
            '#google-verification-error-message',
            'enable google verification',
            /^[a-z0-9\-_]+$/i 
        );
    })
                    
   /* =========== Facebook =========== */
   
    .on('click', '#enable-facebook-verification', function (e) {
        BlueRaven_handleVerificationToggle(
            '#enable-facebook-verification',
            '#facebook-key',
            '#facebook-verification-error-message',
            'enable facebook verification',
            /^[a-z0-9\-_]+$/i 
        );
    })
                    
    /* =========== AHREF =========== */
    
    .on('click', '#enable-ahref-verification', function (e) {
        BlueRaven_handleVerificationToggle(
            '#enable-ahref-verification',
            '#ahref-key',
            '#ahref-verification-error-message',
            'enable ahref verification',
            /^[a-z0-9\-_]+$/i 
        );
    });
                    
    /* =========== Reusable function for site verification toggles =========== */        
    
    function BlueRaven_handleVerificationToggle(checkboxId, keyInputId, errorMessageId, actionType, regexPattern) {
        const isChecked = $(checkboxId).prop('checked');
        const code = $(keyInputId).val().trim();
        const $error = $(errorMessageId);
        let content = [isChecked, code];

        if (isChecked) {
            if (code === '') {
                $error.text(blueRavenTools.errorEmpty);
                $(checkboxId).prop('checked', false).trigger('change');
            } else if (regexPattern && !regexPattern.test(code)) {
                $error.text(blueRavenTools.errorFormat);
                $(checkboxId).prop('checked', false).trigger('change');
            } else {
                $error.text('');
                BlueRaven_toolOperation(content, actionType, '');
            }
        } else {
            $error.text('');
            BlueRaven_toolOperation(content, actionType, '');
        }
    }

})(jQuery); 

(function ($) {
    $(document)

        .on('click', '#tools-sb-sub-schema', function (e) { e.preventDefault(); 

            const selected1 = $('#top-level-organization-dropdown').data('selected');
            const selected2 = $('#middle-level-organization-dropdown').data('selected');
            const selected3 = $('#bottom-level-organization-dropdown').data('selected');

            $('#top-level-organization-dropdown').val(selected1).trigger('change');

            if (selected2) setTimeout(() => { $('#middle-level-organization-dropdown').val(selected2).trigger('change');}, 200);
            if (selected3) setTimeout(() => { $('#bottom-level-organization-dropdown').val(selected3).trigger('change');}, 400); 
        })

                
    /* =========== Top Level Dropdown =========== */
    
        .on('change', '#top-level-organization-dropdown', function (e) {
            
            const selectedOption = $(this).find('option:selected');
            const $middleDropdown = $('#middle-level-organization-dropdown');
            const $bottomDropdown = $('#bottom-level-organization-dropdown');
            
            $middleDropdown.empty().addClass('hidden');
            $bottomDropdown.empty().addClass('hidden');
    
            if (selectedOption.hasClass('subset')) {
                const childrenData = selectedOption.data('children');
                if (childrenData) {
            
                    $middleDropdown.append('<option value="">Select an option</option>');
    
                    $.each(childrenData, function(childLabel, childData) {
                        let option = $('<option>', {
                            value: childData.value,
                            text: childLabel
                        });
    
                        if (childData.children) { option.addClass('subset'); option.attr('data-children', JSON.stringify(childData.children)); }
    
                        $middleDropdown.append(option);
                    });
    
                    $middleDropdown.removeClass('hidden');
                }
            }
        })
        
    /* =========== Mid Level Dropdown =========== */                    
        
        .on('change', '#middle-level-organization-dropdown', function (e) {
            const selectedOption = $(this).find('option:selected');
    
            const $bottomDropdown = $('#bottom-level-organization-dropdown');
            $bottomDropdown.empty().addClass('hidden');
    
            if (selectedOption.hasClass('subset')) {
                const childrenData = selectedOption.data('children');
    
                if (childrenData) {
                    $bottomDropdown.append('<option value="">Select an option</option>');
    
                    $.each(childrenData, function(childLabel, childData) { let option = $('<option>', { value: childData.value,text: childLabel});$bottomDropdown.append(option);});
    
                    $bottomDropdown.removeClass('hidden');
                }
            }
        })

    /* =========== New Link =========== */   

        .on('click', '#add-new-link', function(e) {
            e.preventDefault();
            
            $("#link-fields input[name='socials']").each(function() { if (!$(this).val().trim()) { $(this).remove(); }});
    
            const lastInput = $("#link-fields input[name='socials']:last");
            const lastId = lastInput.length ? parseInt(lastInput.attr('data-link-id')) || 1 : 1;
            const newId = lastId + 1;
    
            const newInput = document.createElement('input');
            newInput.type = 'text';
            newInput.name = 'socials[]';
            newInput.placeholder = 'https://...';
            newInput.className = 'br-input';
            newInput.id = 'schema-name-' + newId;
            newInput.setAttribute('data-link-id', newId);
            newInput.style.cssText = 'width:30rem; max-width: 100%; margin-top:0.5rem; display:block;';
            document.getElementById('link-fields').appendChild(newInput);
            newInput.focus();
        })

    /* =========== New Contact =========== */    

        .on('click', '#add-new-contact', function(e) {
            e.preventDefault();
            
            var linkid = (parseInt($('#contact-points .contact-block').last().data('contact-id')) || 0) + 1;
            
            BlueRaven_toolOperation(linkid, "get contact block", '', true)
                .then((newContact) => { $('#contact-points').append(newContact);})
                .catch((error) => { console.error("Failed to get contact block:", error);});
            
        })

        .on('click', '.remove-contact', function(e) { e.preventDefault(); $(this).closest('.contact-block').remove();}) 

    /* =========== New Area =========== */

        .on('click', '#add-new-area', function(e) { e.preventDefault();var areaId = (parseInt($('#areas-served .area-block').last().data('area-serviced-id')) || 0) + 1;BlueRaven_toolOperation(areaId, "get area block", '', true) .then((newArea) => { $('#areas-served').append(newArea);}) .catch((error) => { console.error("Failed to get contact block:", error); });})
        .on('click', '.remove-area', function(e) {  e.preventDefault();$(this).closest('.area-block').remove();}) 

    /* =========== Save Schema =========== */        

        .on('click', '#save-schema', function (e) { e.preventDefault(); const content = $('#schema-form').serialize();console.log(content);BlueRaven_toolOperation(content, 'save schema', '#tools-sb-sub-schema');})

    /* =========== Enable Schema =========== */       

        .on('click', '#enable-site-schema', function(e) { const isChecked = $('#enable-site-schema').prop('checked');let content = isChecked; BlueRaven_toolOperation(content, 'enable site schema', '')});
})(jQuery);  