// Office 365 One-Click Toggle Logic (jQuery version)
jQuery(function($) {
    var $toggle = $('#office365_oneclick_toggle_switch');
    var originalAuthCellHtml = null;

    // Determine plan (default to business/allowed if not provided to avoid blocking in unknown contexts)
    var isBusinessPlan = true;
    if (typeof window.psp !== 'undefined' && typeof window.psp.isBusinessPlan !== 'undefined') {
        isBusinessPlan = !!window.psp.isBusinessPlan;
    } else if ($toggle.length) {
        var dataIsBusiness = $toggle.data('is-business-plan');
        if (typeof dataIsBusiness !== 'undefined') {
            isBusinessPlan = dataIsBusiness === 1 || dataIsBusiness === '1';
        }
    }

    function getAuthRow() {
        var $row = $();
        $('tr').each(function() {
            var $firstCell = $(this).find('th, td').first();
            if ($firstCell.length && $firstCell.text().trim().toLowerCase().indexOf('microsoft authorization') !== -1) {
                $row = $(this);
                return false;
            }
        });
        return $row;
    }

    function updateAuthSection() {
        var enabled = $toggle.length && $toggle.is(':checked');
        // Hide/show the Microsoft Authorization row (label and buttons) by label text
        var $authRow = getAuthRow();
        if ($authRow.length) {
            $authRow.toggle(enabled);
        }
        // Hide/show all Office 365 Auth Buttons
        $('.ps-office365-auth-buttons').toggle(enabled);
        // Hide/show all manual details
        $('.office365-manual-details').toggle(!enabled);
        // Hide/show manual field rows
        $('tr.office365-manual-field').toggle(!enabled);
    }

    if ($toggle.length) {
        // Initial state
        setTimeout(updateAuthSection, 100);

        // Combined change handler with plan enforcement
        $toggle.on('change', function(e) {
            var enabled = $toggle.is(':checked') ? 1 : 0;

            // If not Business plan and user is trying to enable the toggle, block and show upgrade popup
            if (!isBusinessPlan && enabled === 1) {
                e.preventDefault();
                $toggle.prop('checked', false);

                // Prefer the rich Pro popup from the free plugin if it exists
                var $proPopup = $('.ps-pro-popup-overlay');
                if ($proPopup.length) {
                    $proPopup.fadeIn();
                } else {
                    // Fallback simple browser confirm if popup markup is not available
                    var message = 'Office 365 One-Click Setup is available on the Business plan only.\n\nClick OK to view upgrade options.';
                    if (window.confirm(message)) {
                        window.open('https://postmansmtp.com/pricing/', '_blank');
                    }
                }

                // Ensure UI stays in manual mode
                updateAuthSection();
                return false;
            }

            updateAuthSection();

            // Capture current Microsoft Authorization cell HTML once
            var $authRow = getAuthRow();
            if ($authRow.length && originalAuthCellHtml === null) {
                var $cells = $authRow.find('td');
                if ($cells.length) {
                    originalAuthCellHtml = $cells.last().html();
                }
            }

            // AJAX save on toggle change
            $.post(window.ajaxurl, {
                action: 'save_office365_oneclick_toggle',
                enabled: enabled,
                _ajax_nonce: window.office365_oneclick_toggle ? window.office365_oneclick_toggle.nonce : ''
            }).done(function(resp){
                // On error (e.g., non-business plan attempting enable), just ignore and keep manual UI
                if (!resp || !resp.success) {
                    updateAuthSection();
                    return;
                }

                var data = resp.data || {};
                var $row = getAuthRow();
                if ($row.length) {
                    var $cells = $row.find('td');
                    if ($cells.length) {
                        if (enabled === 1 && data.auth_ui_html) {
                            $cells.last().html(data.auth_ui_html);
                        } else if (enabled === 0 && originalAuthCellHtml !== null) {
                            $cells.last().html(originalAuthCellHtml);
                        }
                    }
                }
                // Re-apply show/hide logic after DOM update
                updateAuthSection();
            });
        });
    }

    // On form submit, if toggle is unchecked, add a hidden input to signal removal
    var $form = $toggle.length ? $toggle.closest('form') : null;
    if ($form && $toggle.length) {
        $form.on('submit', function() {
            var $hidden = $form.find('input[name="post_smtp_pro[extensions][]"][value="remove-microsoft-one-click"]');
            if (!$toggle.is(':checked')) {
                if (!$hidden.length) {
                    $hidden = $('<input>', {
                        type: 'hidden',
                        name: 'post_smtp_pro[extensions][]',
                        value: 'remove-microsoft-one-click'
                    });
                    $form.append($hidden);
                }
            } else if ($hidden.length) {
                $hidden.remove();
            }
        });
    }

    // Ensure Pro popup (from free plugin) can be closed if we opened it
    $(document).on('click', '.ps-pro-popup-overlay .ps-pro-close-popup', function(e) {
        e.preventDefault();
        $('.ps-pro-popup-overlay').fadeOut();
    });

    /**
     * Office 365 Business Plan popup – copy coupon handler
     *
     * We use a dedicated class (`.ps365-click-to-copy`) so we don't conflict with
     * any existing "click‑to‑copy" handlers from the free plugin. This ensures
     * the coupon is copied exactly once and the green "Code Copied" notification
     * is shown for the popup rendered on the settings page.
     */
    $(document).on('click', '.ps365-click-to-copy', function(e) {
        e.preventDefault();

        var $popup  = $(this).closest('.ps-pro-popup-container');
        var $codeEl = $popup.find('.ps-pro-coupon-code');

        if (!$codeEl.length) {
            return;
        }

        var code = $.trim($codeEl.text());
        if (!code) {
            return;
        }

        function showNotification() {
            var $notice = $popup.find('#ps-pro-code-copy-notification');
            if (!$notice.length) {
                return;
            }

            // Use fade in/out so it matches the existing popup look-and-feel.
            $notice.stop(true, true).fadeIn(150, function() {
                setTimeout(function() {
                    $notice.fadeOut(150);
                }, 1500);
            });
        }

        // Prefer modern async clipboard API when available.
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(code)
                .then(showNotification)
                .catch(function() {
                    // Fallback to the legacy execCommand path.
                    var $temp = $('<input type="text" readonly />')
                        .val(code)
                        .appendTo('body');
                    $temp[0].select();
                    try {
                        document.execCommand('copy');
                    } catch (err) {
                        // Silently fail – nothing else to do.
                    }
                    $temp.remove();
                    showNotification();
                });
        } else {
            // Legacy browsers – only execCommand is available.
            var $temp = $('<input type="text" readonly />')
                .val(code)
                .appendTo('body');
            $temp[0].select();
            try {
                document.execCommand('copy');
            } catch (err) {
                // Silently fail – nothing else to do.
            }
            $temp.remove();
            showNotification();
        }
    });

    // Handle hover on toggle label to show GIF
    $('#office365_oneclick_toggle_switch').closest('label').hover(function() {
        if (!isBusinessPlan) {
            $('#office365_oneclick_gif').show();
        }
    }, function() {
        if (!isBusinessPlan) {
            $('#office365_oneclick_gif').hide();
        }
    });

    // Handle click on GIF to show popup
    $('#office365_oneclick_gif').click(function() {
        $('.ps-pro-popup-overlay').fadeIn();
    });
});
jQuery( document ).ready( function() {
	
    var activeSocket = jQuery( '.socket-extensions .enable-extension:checked' ).length;

    if( activeSocket == 0 ) {
        jQuery( '.psp-launch-wizard' ).attr( 'disabled', true );
    }
    else {
        var wizardKey = jQuery( '.socket-extensions .enable-extension:checked' ).data( 'key' );
        // Map Microsoft One Click to Office 365 API socket for the wizard
        if (wizardKey === 'microsoftoneclick_api') {
            wizardKey = 'office365_api';
        }
        jQuery( '.psp-launch-wizard' ).val( `${psp.dashboardURL}&step=2&socket=${wizardKey}` );
    }

    //Socket Extensions
    var clickedCheckbox = ''
    jQuery( document ).on( 'click', '.socket-extensions .enable-extension', function( e ){
        clickedCheckbox = jQuery( this );
        var activeSocket = jQuery( '.socket-extensions .enable-extension:checked' ).length;
        var isChecked = jQuery( this ).is( ':checked' );
        var socketKey = jQuery(this).data('key');
        var isRestricted = jQuery(this).data('restricted');

        // Check if this is a restricted extension (microsoft-one-click for basic/professional plans)
        if (isRestricted === true) {
            // Prevent the checkbox from being checked
            e.preventDefault();
            jQuery(this).prop('checked', false);
            
            // Get the restriction reason from the parent container
            var restrictionReason = jQuery(this).closest('.psp-extension-restricted').data('restriction-reason');
            
            if( restrictionReason === 'plan' ) {
                // Redirect to pricing page for plan upgrade
                window.open('https://postmansmtp.com/pricing/', '_blank');
            } else if( restrictionReason === 'version' ) {
                // Redirect to WordPress plugins page for free plugin update
                window.open(window.location.origin + '/wp-admin/plugins.php', '_blank');
            }
            
            return false;
        }

        // Handle microsoft-365 and microsoft-one-click dependency
        if (socketKey === 'office365_api') {
            // When Office365 is disabled, also disable microsoft-one-click
            var oneClickCheckbox = jQuery('.socket-extensions .enable-extension[data-key="microsoftoneclick_api"]');
            if (!isChecked && oneClickCheckbox.is(':checked')) {
                oneClickCheckbox.prop('checked', false);
                // Update status text for Microsoft One Click
                oneClickCheckbox.closest('.psp-extension-bottom').find('.psp-extension-status').text('Deactivated');
                oneClickCheckbox.closest('.psp-extension-bottom').find('.psp-extension-status').removeClass('active');
                oneClickCheckbox.closest('.psp-extension-bottom').find('.psp-extension-status').addClass('inactive');
            }
        } else if (socketKey === 'microsoftoneclick_api') {
            // When Microsoft One Click is enabled, also enable Office365
            var officeCheckbox = jQuery('.socket-extensions .enable-extension[data-key="office365_api"]');
            if (isChecked && !officeCheckbox.is(':checked')) {
                officeCheckbox.prop('checked', true);
                // Update status text for Office365
                officeCheckbox.closest('.psp-extension-bottom').find('.psp-extension-status').text('Activated');
                officeCheckbox.closest('.psp-extension-bottom').find('.psp-extension-status').removeClass('inactive');
                officeCheckbox.closest('.psp-extension-bottom').find('.psp-extension-status').addClass('active');
                // Recalculate activeSocket count after dependency changes
                activeSocket = jQuery( '.socket-extensions .enable-extension:checked' ).length;
            }
        }

        if( isChecked && activeSocket > 1 ) {
            jQuery( '.psp-popup-overlay' ).fadeIn();
        }
        else {
            if( isChecked ) {
                var wizardKey = jQuery( '.socket-extensions .enable-extension:checked' ).data( 'key' );
                // Map Microsoft One Click to Office 365 API socket for the wizard
                if (wizardKey === 'microsoftoneclick_api') {
                    wizardKey = 'office365_api';
                }
                jQuery( '.psp-launch-wizard' ).val( `${psp.dashboardURL}&step=2&socket=${wizardKey}` );
                
                jQuery( this ).closest( '.psp-extension-bottom' ).find( '.psp-extension-status' ).text( 'Activated' );
                jQuery( this ).closest( '.psp-extension-bottom' ).find( '.psp-extension-status' ).removeClass( 'inactive' );
                jQuery( this ).closest( '.psp-extension-bottom' ).find( '.psp-extension-status' ).addClass( 'active' );
            } else {
                jQuery( this ).closest( '.psp-extension-bottom' ).find( '.psp-extension-status' ).text( 'Deactivated' );
                jQuery( this ).closest( '.psp-extension-bottom' ).find( '.psp-extension-status' ).removeClass( 'active' );
                jQuery( this ).closest( '.psp-extension-bottom' ).find( '.psp-extension-status' ).addClass( 'inactive' );
            }

            if( activeSocket == 0 ) {
                jQuery( '.psp-launch-wizard' ).attr( 'disabled', true );
            } else {
                jQuery( '.psp-launch-wizard' ).attr( 'disabled', false );
            }
        }
    } );

    // Handle clicks on restricted extension boxes
    jQuery( document ).on( 'click', '.psp-extension-restricted', function( e ) {
        // Only handle clicks that aren't on the checkbox itself
        if( !jQuery( e.target ).is('input[type="checkbox"]') && !jQuery( e.target ).is('.ps-switch-slider') ) {
            e.preventDefault();
            
            var restrictionReason = jQuery( this ).data( 'restriction-reason' );
            
            if( restrictionReason === 'plan' ) {
                // Redirect to pricing page for plan upgrade
                window.open('https://postmansmtp.com/pricing/', '_blank');
            } else if( restrictionReason === 'version' ) {
                // Redirect to WordPress plugins page for free plugin update
                window.open(window.location.origin + '/wp-admin/plugins.php', '_blank');
            }
        }
    } );

    //Popup Buttons
    jQuery( document ).on( 'click', '.psp-popup-btns a', function( e ) {
        e.preventDefault();

        var dataID = jQuery( this ).attr( 'data-id' );

        if( dataID == 'cancel' ) {
            var socketKey = jQuery( clickedCheckbox ).data( 'key' );
            
            // Uncheck the clicked checkbox
            jQuery( clickedCheckbox ).prop( 'checked', false );
            jQuery( clickedCheckbox ).closest( '.psp-extension-bottom' ).find( '.psp-extension-status' ).text( 'Deactivated' );
            jQuery( clickedCheckbox ).closest( '.psp-extension-bottom' ).find( '.psp-extension-status' ).removeClass( 'active' );
            jQuery( clickedCheckbox ).closest( '.psp-extension-bottom' ).find( '.psp-extension-status' ).addClass( 'inactive' );
            
            // If Microsoft One Click was being enabled, also turn off Office365
            if( socketKey === 'microsoftoneclick_api' ) {
                var officeCheckbox = jQuery('.socket-extensions .enable-extension[data-key="office365_api"]');
                if( officeCheckbox.is(':checked') ) {
                    officeCheckbox.prop( 'checked', false );
                    officeCheckbox.closest( '.psp-extension-bottom' ).find( '.psp-extension-status' ).text( 'Deactivated' );
                    officeCheckbox.closest( '.psp-extension-bottom' ).find( '.psp-extension-status' ).removeClass( 'active' );
                    officeCheckbox.closest( '.psp-extension-bottom' ).find( '.psp-extension-status' ).addClass( 'inactive' );
                }
            }
            
            jQuery( '.psp-popup-overlay' ).fadeOut();
        }
        if( dataID == 'confirm' ) {

            var wizardKey = jQuery( clickedCheckbox ).data( 'key' );
            // Map Microsoft One Click to Office 365 API socket for the wizard
            if (wizardKey === 'microsoftoneclick_api') {
                wizardKey = 'office365_api';
            }
            jQuery( '.psp-launch-wizard' ).val( `${psp.dashboardURL}&step=2&socket=${wizardKey}` );

            // Deactivate all other extensions
            jQuery('.socket-extensions .psp-extension-status').text('Deactivated');
            jQuery('.socket-extensions .enable-extension').prop('checked', false);
            jQuery('.socket-extensions .psp-extension-status').removeClass('active inactive').addClass('inactive');

            // Activate the selected socket
            jQuery(clickedCheckbox).prop('checked', true);
            jQuery(clickedCheckbox).closest('.psp-extension-bottom').find('.psp-extension-status')
                .text('Activated')
                .removeClass('inactive')
                .addClass('active');
            
                // Handle dependencies for microsoft-365 and microsoft-one-click
            var socketKey = jQuery(clickedCheckbox).data('key');
            if (socketKey === 'microsoftoneclick_api') {
                // Enable microsoft-365 if microsoft-one-click is enabled
                var officeCheckbox = jQuery('.socket-extensions .enable-extension[data-key="office365_api"]');
                if (!officeCheckbox.is(':checked')) {
                    officeCheckbox.prop('checked', true)
                        .closest('.psp-extension-bottom').find('.psp-extension-status')
                        .text('Activated')
                        .removeClass('inactive')
                        .addClass('active');
                }
            }

            // Ensure Launch Setup Wizard button is enabled when at least one socket is active
            var activeSocket = jQuery( '.socket-extensions .enable-extension:checked' ).length;
            if (activeSocket > 0) {
                jQuery( '.psp-launch-wizard' ).attr( 'disabled', false );
            } else {
                jQuery( '.psp-launch-wizard' ).attr( 'disabled', true );
            }
            
            jQuery( '.psp-popup-overlay' ).fadeOut();
        }
    } );

    //Bonus Extensions
    jQuery( document ).on( 'change', '.bonus-extensions .enable-extension', function() {
        if( jQuery( this ).is( ':checked' ) ) {
            jQuery( this ).closest( '.psp-extension-bottom' ).find( '.psp-extension-status' ).text( 'Activated' );
            jQuery( this ).closest( '.psp-extension-bottom' ).find( '.psp-extension-status' ).removeClass( 'inactive' );
            jQuery( this ).closest( '.psp-extension-bottom' ).find( '.psp-extension-status' ).addClass( 'active' );
        } else {
            jQuery( this ).closest( '.psp-extension-bottom' ).find( '.psp-extension-status' ).text( 'Deactivated' );
            jQuery( this ).closest( '.psp-extension-bottom' ).find( '.psp-extension-status' ).removeClass( 'active' );
            jQuery( this ).closest( '.psp-extension-bottom' ).find( '.psp-extension-status' ).addClass( 'inactive' );
        }
    } );

    jQuery( document ).on( 'click', '[disabled=disabled]', function( e ) {
        e.preventDefault();
    } );

    // Dismiss Notice
    jQuery( document ).on( 'click', '.psp-deactivated-extensions .notice-dismiss', function( e ) {
        e.preventDefault();
        
        var redirectURL = jQuery( '.psp-notice-action' ).val();
        window.location.replace( redirectURL );
    } );

    // Hide/ Show submenu
    jQuery( document ).on( 'click', '.psp-menu', function() {
        var dataID = jQuery( this ).data( 'id' );
        var element = `.${dataID}-sub-menu`;
        jQuery( element ).show();

        jQuery( document ).on( 'click', function( e ) {
            if( !jQuery( e.target ).closest( '.psp-sub-menu' ).length ) {
                jQuery( element ).hide();
                element = '';
            }
        } );
    } );
} );