/**
 * Softech Addons for Elementor – Admin Scripts
 *
 * @package Softech_Addons_for_Elementor
 * @since 1.0.0
 */

(function ($) {
    'use strict';

    $(document).ready(function () {

        // ==================================================================
        // TAB NAVIGATION (AJAX LOADING)
        // ==================================================================
        $(document).on('click', '.sits-tab-link', function (e) {
            e.preventDefault();

            var tab    = $(this).data('tab');
            var subtab = $(this).data('subtab') || '';

            // Theme Builder goes to a real URL, no AJAX.
            if (tab === 'theme-builder') {
                var themeBuilderUrl = $(this).data('redirect-url') || '';
                if (themeBuilderUrl) {
                    window.location.href = themeBuilderUrl;
                }
                return;
            }

            $('.sits-tab-link').removeClass('active');
            $(this).addClass('active');
            var newUrl = new URL( window.location.href );
            newUrl.searchParams.set( 'tab', tab );
            if ( subtab ) {
            newUrl.searchParams.set( 'subtab', subtab );
            } else {
            newUrl.searchParams.delete( 'subtab' );
            }
            history.pushState( { tab: tab, subtab: subtab }, '', newUrl.toString() );

            showWave('#sits-tab-content');

            $.ajax({
                url:  sitsAdmin.ajaxurl,
                type: 'POST',
                data: {
                    action:  'sits_load_tab',
                    nonce:   sitsAdmin.nonce,
                    tab:     tab,
                    subtab:  subtab
                },
                success: function (response) {
                    if (response.success) {
                        $('#sits-tab-content').html(response.data.html).addClass('sits-content-fade-in');
                        reattachEventHandlers();
                    } else {
                        $('#sits-tab-content').html(makeError(response.data && response.data.message ? response.data.message : 'Error loading tab'));
                    }
                },
                error: function () {
                    $('#sits-tab-content').html(makeError('Error loading tab'));
                }
            });
        });

        // ==================================================================
        // PAYMENT SUB-TABS (General / Transactions)
        // ==================================================================
        $(document).on('click', '.sits-payment-subtab-link', function (e) {
            e.preventDefault();

            var subtab = $(this).data('subtab') || 'general';

            // Update active styling.
            $('.sits-payment-subtab-link')
                .css('color', '#666')
                .css('border-bottom', '2px solid transparent');
            $(this)
                .css('color', '#0f3d4a')
                .css('border-bottom', '2px solid #0f3d4a');
                var newUrl = new URL( window.location.href );
                newUrl.searchParams.set( 'subtab', subtab );
                history.pushState( { subtab: subtab }, '', newUrl.toString() );

            showWave('#sits-payment-content');

            $.ajax({
                url:  sitsAdmin.ajaxurl,
                type: 'POST',
                data: {
                    action:  'sits_load_payment_tab',
                    nonce:   sitsAdmin.nonce,
                    subtab:  subtab
                },
                success: function (response) {
                    if (response.success) {
                        $('#sits-payment-content').html(response.data.html).addClass('sits-content-fade-in');
                        reattachEventHandlers();
                    } else {
                        $('#sits-payment-content').html(makeError(response.data && response.data.message ? response.data.message : 'Error loading tab'));
                    }
                },
                error: function () {
                    $('#sits-payment-content').html(makeError('Error loading tab'));
                }
            });
        });
        
        $(document).on('click', '#sits-export-csv', function () {
    var data = getFilterData(1);
    var form = $('<form method="POST" action="' + sitsAdmin.ajaxurl + '" style="display:none;">');
    data.action = 'sits_export_transactions_csv';
    $.each(data, function (key, val) {
        form.append($('<input type="hidden">').attr('name', key).val(val));
    });
    $('body').append(form);
    form.submit();
    form.remove();
});

        // ==================================================================
        // FIX 1 – GENERAL SETTINGS FORM: AJAX SAVE (no options.php redirect)
        // ==================================================================
        $(document).on('submit', '#sits-general-settings-form', function (e) {
            e.preventDefault();

            var $form   = $(this);
            var $notice = $('#sits-general-settings-notice');
            var $btn    = $form.find('[type="submit"]');

            $btn.prop('disabled', true).val('Saving...');
            $notice.hide().removeClass('notice-success notice-error');

            // Collect all field values under the sits_elementor_addons_options key.
            var options = {};
            $form.find('[name^="sits_elementor_addons_options["]').each(function () {
                var match = $(this).attr('name').match(/\[([^\]]+)\]$/);
                if (match) {
                    options[match[1]] = $(this).val();
                }
            });

            $.ajax({
                url:  sitsAdmin.ajaxurl,
                type: 'POST',
                data: {
                    action:  'sits_save_payment_general_settings',
                    nonce:   sitsAdmin.nonce,
                    options: options
                },
                success: function (response) {
                    $btn.prop('disabled', false).val('Save Changes');
                    if (response.success) {
                        $notice
                            .addClass('notice-success')
                            .text(response.data.message || 'Settings saved.')
                            .show();
                    } else {
                        $notice
                            .addClass('notice-error')
                            .text(response.data && response.data.message ? response.data.message : 'Error saving settings.')
                            .show();
                    }
                    setTimeout(function () { $notice.fadeOut(); }, 4000);
                },
                error: function () {
                    $btn.prop('disabled', false).val('Save Changes');
                    $notice.addClass('notice-error').text('Request failed. Please try again.').show();
                    setTimeout(function () { $notice.fadeOut(); }, 4000);
                }
            });
        });

        // ==================================================================
        // FIX 2 – TRANSACTION FILTERS & SEARCH (AJAX, targets only results div)
        // ==================================================================

        /**
         * Collect current filter values from the static #sits-filter-area.
         * These inputs are never destroyed by AJAX so they always exist.
         */
        function getFilterData(page) {
            return {
                action:     'sits_filter_transactions',
                nonce:      sitsAdmin.nonce,
                search:     $('#sits-search-input').val()          || '',
                status:     $('#sits-filter-status').val()         || '',
                provider:   $('#sits-filter-provider').val()       || '',
                currency:   $('#sits-filter-currency').val()       || '',
                date_range: $('#sits-filter-date-range').val()     || '',
                date_from:  $('#sits-filter-date-from').val()      || '',
                date_to:    $('#sits-filter-date-to').val()        || '',
                paged:      page || 1
            };
        }

        /**
         * Fire the AJAX filter request and replace only #sits-transaction-results.
         * The filter area (#sits-filter-area) stays untouched.
         */
        function doAjaxFilter(page) {
            showWave('#sits-transaction-results');

            $.ajax({
                url:  sitsAdmin.ajaxurl,
                type: 'POST',
                data: getFilterData(page || 1),
                success: function (response) {
                    if (response.success) {
                        $('#sits-transaction-results').html(response.data.html).addClass('sits-content-fade-in');
                    } else {
                        $('#sits-transaction-results').html(makeError('Error loading transactions'));
                    }
                },
                error: function () {
                    $('#sits-transaction-results').html(makeError('Error loading transactions'));
                }
            });
        }

        

        // Auto-apply when any filter select changes.
        $(document).on('change', '#sits-filter-status, #sits-filter-provider, #sits-filter-currency', function () {
            doAjaxFilter(1);
        });

        // Date range: show/hide custom inputs + auto-apply for non-custom choices.
        $(document).on('change', '#sits-filter-date-range', function () {
            if ($(this).val() === 'custom') {
                $('#sits-custom-date-range').slideDown(300);
                // Do NOT auto-apply; user still needs to pick dates.
            } else {
                $('#sits-custom-date-range').slideUp(300);
                doAjaxFilter(1);
            }
        });

        // Auto-apply when custom date inputs change (both set).
        $(document).on('change', '#sits-filter-date-from, #sits-filter-date-to', function () {
            var from = $('#sits-filter-date-from').val();
            var to   = $('#sits-filter-date-to').val();
            if (from && to) {
                doAjaxFilter(1);
            }
        });

        // Live search with 400 ms debounce (no submit button needed).
        var searchTimer;
        $(document).on('input', '#sits-search-input', function () {
            clearTimeout(searchTimer);
            searchTimer = setTimeout(function () {
                doAjaxFilter(1);
            }, 400);
        });

        // Clear all filters button (lives inside #sits-transaction-results, uses delegation).
        $(document).on('click', '.sits-clear-all-filters', function () {
            // Reset every filter control in the static filter area.
            $('#sits-filter-status').val('');
            $('#sits-filter-provider').val('');
            $('#sits-filter-currency').val('');
            $('#sits-filter-date-range').val('');
            $('#sits-filter-date-from').val('');
            $('#sits-filter-date-to').val('');
            $('#sits-search-input').val('');
            $('#sits-custom-date-range').hide();
            doAjaxFilter(1);
        });

        // Pagination inside results area.
        $(document).on('click', '.sits-pagination-link', function (e) {
            e.preventDefault();
            doAjaxFilter(parseInt($(this).data('page'), 10) || 1);
        });

        // ==================================================================
        // DELETE TRANSACTION
        // ==================================================================
        $(document).on('click', '.sitsel-delete-transaction', function (e) {
            e.preventDefault();

            var $btn           = $(this);
            var transactionId  = $btn.data('id');

            if (!confirm('Are you sure you want to delete this transaction? This action cannot be undone.')) {
                return;
            }

            $btn.prop('disabled', true).html('<span class="dashicons dashicons-update dashicons-spin"></span>');

            $.ajax({
                url:  sitsAdmin.ajaxurl,
                type: 'POST',
                data: {
                    action:         'sits_delete_transaction',
                    nonce:          sitsAdmin.nonce,
                    transaction_id: transactionId
                },
                success: function (response) {
                    if (response.success) {
                        // Reload the results with the same filters to refresh stats too.
                        doAjaxFilter(1);
                    } else {
                        alert(response.data && response.data.message ? response.data.message : 'Failed to delete transaction');
                        $btn.prop('disabled', false).html('<span class="dashicons dashicons-trash"></span>');
                    }
                },
                error: function () {
                    alert('An error occurred. Please try again.');
                    $btn.prop('disabled', false).html('<span class="dashicons dashicons-trash"></span>');
                }
            });
        });

        // ==================================================================
        // WIDGET SEARCH (local, no AJAX)
        // ==================================================================
        $(document).on('keyup', '#sits-widget-search', function () {
            var term = $(this).val().toLowerCase();
            $('.sits-widget-card').each(function () {
                var title = $(this).data('widget-title') ? $(this).data('widget-title').toLowerCase() : '';
                var name  = $(this).data('widget-name')  ? $(this).data('widget-name').toLowerCase()  : '';
                if (title.includes(term) || name.includes(term)) {
                    $(this).fadeIn(200);
                } else {
                    $(this).fadeOut(200);
                }
            });
        });

        // ==================================================================
        // TOGGLE ALL WIDGETS
        // ==================================================================
        $(document).on('change', '#sits-toggle-all', function () {
            var isChecked      = $(this).is(':checked');
            var widgetsToToggle = [];

            $('.sits-widget-checkbox').each(function () {
                if ($(this).is(':checked') !== isChecked) {
                    widgetsToToggle.push($(this).data('widget'));
                }
            });

            if (!widgetsToToggle.length) { return; }

            $('.sits-widget-card').addClass('sits-loading');

            $.ajax({
                url:  sitsAdmin.ajaxurl,
                type: 'POST',
                data: {
                    action:   'sits_toggle_all_widgets',
                    nonce:    sitsAdmin.nonce,
                    widgets:  widgetsToToggle,
                    enabled:  isChecked
                },
                success: function (response) {
                    $('.sits-widget-card').removeClass('sits-loading');
                    if (response.success) {
                        $('.sits-widget-checkbox').each(function () {
                            $(this).prop('checked', isChecked);
                            $(this).closest('.sits-widget-card').toggleClass('sits-widget-disabled', !isChecked);
                        });
                        showNotification('All widgets ' + (isChecked ? 'enabled' : 'disabled') + ' successfully', 'success');
                    } else {
                        $('#sits-toggle-all').prop('checked', !isChecked);
                        showNotification('Failed to update widgets', 'error');
                    }
                },
                error: function () {
                    $('.sits-widget-card').removeClass('sits-loading');
                    $('#sits-toggle-all').prop('checked', !isChecked);
                    showNotification('An error occurred. Please try again.', 'error');
                }
            });
        });

        // ==================================================================
        // INDIVIDUAL WIDGET TOGGLE
        // ==================================================================
        $(document).on('change', '.sits-widget-checkbox', function () {
            var $checkbox  = $(this);
            var widgetName = $checkbox.data('widget');
            var isEnabled  = $checkbox.is(':checked');
            var $card      = $checkbox.closest('.sits-widget-card');

            $card.addClass('sits-loading');
            $card.toggleClass('sits-widget-disabled', !isEnabled);

            $.ajax({
                url:  sitsAdmin.ajaxurl,
                type: 'POST',
                data: {
                    action:  'sits_toggle_widget',
                    nonce:   sitsAdmin.nonce,
                    widget:  widgetName,
                    enabled: isEnabled
                },
                success: function (response) {
                    $card.removeClass('sits-loading');
                    if (response.success) {
                        showNotification('Widget ' + (isEnabled ? 'enabled' : 'disabled') + ' successfully', 'success');
                        updateToggleAllState();
                    } else {
                        $checkbox.prop('checked', !isEnabled);
                        $card.toggleClass('sits-widget-disabled');
                        showNotification('Failed to update widget state', 'error');
                    }
                },
                error: function () {
                    $card.removeClass('sits-loading');
                    $checkbox.prop('checked', !isEnabled);
                    $card.toggleClass('sits-widget-disabled');
                    showNotification('An error occurred. Please try again.', 'error');
                }
            });
        });

        // ==================================================================
        // CLEAR PLUGIN CACHE
        // ==================================================================
        $(document).on('click', '#sits-clear-cache-btn', function () {
            var $btn = $(this);
            var $msg = $('#sits-clear-cache-msg');
            $btn.prop('disabled', true).text(sitsAdmin.strings && sitsAdmin.strings.clearing ? sitsAdmin.strings.clearing : 'Clearing\u2026');
            $msg.hide();
            $.ajax({
                url:  sitsAdmin.ajaxurl,
                type: 'POST',
                data: { action: 'sits_clear_plugin_cache', nonce: sitsAdmin.nonce },
                success: function (response) {
                    $btn.prop('disabled', false).html('<span class="dashicons dashicons-trash" style="vertical-align:middle;margin-top:-2px;margin-right:4px;"></span>Clear Plugin Cache');
                    $msg.text(response.success ? (response.data.message || 'Cache cleared.') : (response.data && response.data.message ? response.data.message : 'Error clearing cache.')).css('color', response.success ? '#46b450' : '#dc2626').show();
                    setTimeout(function () { $msg.fadeOut(); }, 4000);
                },
                error: function () {
                    $btn.prop('disabled', false).html('<span class="dashicons dashicons-trash" style="vertical-align:middle;margin-top:-2px;margin-right:4px;"></span>Clear Plugin Cache');
                    $msg.text('Request failed. Please try again.').css('color', '#dc2626').show();
                    setTimeout(function () { $msg.fadeOut(); }, 4000);
                }
            });
        });

        // ==================================================================
        // PRO BADGE LINKS
        // ==================================================================
        $(document).on('click', '.sits-pro-badge-link', function (e) {
            var href = $(this).attr('href');
            if (href && href.includes('tab=go-pro')) {
                e.preventDefault();
                window.location.href = href;
            }
        });

        // ==================================================================
        // WIDGET CARD HOVER Z-INDEX
        // ==================================================================
        $(document).on('mouseenter', '.sits-widget-card', function () {
            $(this).css('z-index', '10');
        }).on('mouseleave', '.sits-widget-card', function () {
            $(this).css('z-index', '1');
        });

        // ==================================================================
        // LOCKED WIDGET CLICK
        // ==================================================================
        $(document).on('click', '.sits-widget-card.sits-widget-locked', function (e) {
            if (!$(e.target).closest('.sits-pro-badge-link').length) {
                var proTabUrl = $(this).find('.sits-pro-badge-link').attr('href');
                if (proTabUrl) { window.location.href = proTabUrl; }
            }
        });

        // ==================================================================
        // HELPERS
        // ==================================================================

        function updateToggleAllState() {
            var $all     = $('.sits-widget-checkbox');
            var $checked = $('.sits-widget-checkbox:checked');
            if ($all.length === $checked.length) {
                $('#sits-toggle-all').prop('checked', true);
            } else if (!$checked.length) {
                $('#sits-toggle-all').prop('checked', false);
            }
        }

        function reattachEventHandlers() {
            updateToggleAllState();
        }

        function showNotification(message, type) {
            $('.sits-notification').remove();
            var cls = type === 'success' ? 'notice-success' : 'notice-error';
            var $n  = $('<div class="notice ' + cls + ' is-dismissible sits-notification"><p>' + message + '</p></div>');
            $('.sits-widgets-container, .sits-settings-container, .sits-transactions-header').first().prepend($n);
            setTimeout(function () { $n.fadeOut(300, function () { $(this).remove(); }); }, 3000);
            $n.find('.notice-dismiss').on('click', function () { $n.fadeOut(300, function () { $(this).remove(); }); });
        }

        function showShimmer(selector) {
            $(selector).html(
                '<div class="sits-shimmer-loader"><div class="sits-shimmer-content">' +
                '<div class="sits-shimmer-line full"></div>' +
                '<div class="sits-shimmer-line full"></div>' +
                '<div class="sits-shimmer-line half"></div>' +
                '<div style="margin-top:20px;"></div>' +
                '<div class="sits-shimmer-line full"></div>' +
                '<div class="sits-shimmer-line full"></div>' +
                '<div class="sits-shimmer-line short"></div>' +
                '</div></div>'
            );
        }

        function showWave(selector) {
            $(selector).html(
                '<div class="sits-wave-loader">' +
                '<div class="sits-wave-bar"></div>' +
                '<div class="sits-wave-bar"></div>' +
                '<div class="sits-wave-bar"></div>' +
                '<div class="sits-wave-bar"></div>' +
                '<div class="sits-wave-bar"></div>' +
                '</div>'
            );
        }

        function makeError(msg) {
            return '<div class="notice notice-error"><p>' + msg + '</p></div>';
        }


    }); // end document.ready

})(jQuery);
