/**
 * PB UAE VAT Invoicing System — Admin JS
 * PluginsBuy | https://pluginsbuy.com
 */
/* global PBUAIV, wp, jQuery */
(function ($) {
    'use strict';

    /* ────────────────────────────────────────────────────────────────
       AJAX HELPER
    ──────────────────────────────────────────────────────────────── */
    function ajax(action, data, $btn) {
        if ($btn && $btn.length) {
            $btn.addClass('loading').prop('disabled', true);
            $btn.data('orig', $btn.html());
            $btn.html('<span class="pbuaiv-spinner"></span>');
        }
        return $.ajax({
            url:  PBUAIV.ajax_url,
            type: 'POST',
            data: $.extend({ action: action, nonce: PBUAIV.nonce }, data)
        }).always(function () {
            if ($btn && $btn.length) {
                $btn.removeClass('loading').prop('disabled', false);
                $btn.html($btn.data('orig'));
            }
        });
    }

    function showNotice($el, type, msg) {
        $el.removeClass('info--notice success--notice warning--notice error--notice')
           .addClass('pbuaiv-notice pbuaiv-notice--' + type)
           .html(msg)
           .show();
        setTimeout(function () { $el.fadeOut(400, function () { $(this).hide(); }); }, 5000);
    }

    /* ────────────────────────────────────────────────────────────────
       TABS (Settings page)
    ──────────────────────────────────────────────────────────────── */
    $(document).on('click', '.pbuaiv-tab', function () {
        var $tab   = $(this);
        var target = $tab.data('tab');

        // Update tab active state
        $tab.closest('.pbuaiv-tabs').find('.pbuaiv-tab').removeClass('pbuaiv-tab--active');
        $tab.addClass('pbuaiv-tab--active');

        // Show corresponding panel
        $tab.closest('.pbuaiv-wrap').find('.pbuaiv-tab-panel').removeClass('is-active').hide();
        $('#pbuaiv-tab-' + target).addClass('is-active').show();

        // Persist in URL (no page reload)
        if (history && history.replaceState) {
            var url = new URL(window.location.href);
            url.searchParams.set('tab', target);
            history.replaceState(null, '', url.toString());
        }
    });

    // Restore tab from URL on page load
    (function () {
        var url = new URL(window.location.href);
        var tab = url.searchParams.get('tab');
        if (tab) {
            var $btn = $('.pbuaiv-tab[data-tab="' + tab + '"]');
            if ($btn.length) { $btn.trigger('click'); return; }
        }
        // Default: show first panel
        $('.pbuaiv-tab-panel').hide();
        var $first = $('.pbuaiv-tab-panel:first');
        if ($first.length) { $first.addClass('is-active').show(); }
        $('.pbuaiv-tab:first').addClass('pbuaiv-tab--active');
    })();

    /* ────────────────────────────────────────────────────────────────
       SETUP WIZARD
    ──────────────────────────────────────────────────────────────── */
    var currentStep = 1;
    var totalSteps  = 5;

    function goToStep(n) {
        if (n < 1 || n > totalSteps) return;
        currentStep = n;

        // Show/hide panels
        $('.pbuaiv-setup-panel').hide();
        $('#pbuaiv-step-' + currentStep).show();

        // Update step indicators
        $('.pbuaiv-setup-step').each(function () {
            var s = parseInt($(this).data('step'), 10);
            $(this)
                .removeClass('pbuaiv-setup-step--active pbuaiv-setup-step--done')
                .toggleClass('pbuaiv-setup-step--active', s === currentStep)
                .toggleClass('pbuaiv-setup-step--done',   s < currentStep);
        });

        $('html, body').animate({ scrollTop: $('.pbuaiv-setup-wrap').offset().top - 40 }, 200);
    }

    // Next button
    $(document).on('click', '.pbuaiv-next-step', function () {
        var next = parseInt($(this).data('next'), 10);
        // On last real step (step 4 → 5): save settings first
        if ($(this).attr('id') === 'pbuaiv-save-finish') {
            saveWizardSettings(function () { goToStep(5); });
        } else {
            goToStep(next);
        }
    });

    // Prev button
    $(document).on('click', '.pbuaiv-prev-step', function () {
        var prev = parseInt($(this).data('prev'), 10);
        goToStep(prev);
    });

    // Clickable step indicators
    $(document).on('click', '.pbuaiv-setup-step[data-step]', function () {
        var s = parseInt($(this).data('step'), 10);
        if (!isNaN(s) && s <= currentStep) { goToStep(s); }
    });

    function saveWizardSettings(cb) {
        var settings = {};
        $('#pbuaiv-onboarding').find('[name]').each(function () {
            var el   = this;
            var name = el.name.replace(/\[\]$/, '');
            var val  = $(el).val();

            if (el.type === 'checkbox' && !el.checked) return;
            if (el.type === 'radio'    && !el.checked) return;

            if (el.type === 'checkbox') {
                if (!settings[name]) settings[name] = [];
                settings[name].push(val);
            } else {
                settings[name] = val;
            }
        });

        ajax('pbuaiv_save_settings', { settings: settings })
            .done(function (res) {
                if (res.success) {
                    // Notify the checklist to refresh based on what was just saved
                    document.dispatchEvent(new CustomEvent('pbuaiv:wizard_saved'));
                    if (cb) cb();
                } else {
                    if (cb) cb();
                }
            })
            .fail(function () {
                if (cb) cb(); // still proceed
            });
    }

    /* ────────────────────────────────────────────────────────────────
       SETTINGS PAGE — SAVE ALL
    ──────────────────────────────────────────────────────────────── */
    $(document).on('click', '#pbuaiv-save-all', function () {
        var $btn      = $(this);
        var settings  = {};
        var $wrap     = $btn.closest('.pbuaiv-wrap');

        $wrap.find('[name]').each(function () {
            var el   = this;
            var name = el.name.replace(/\[\]$/, '');
            var val  = $(el).val();

            if (el.type === 'checkbox' && !el.checked) return;
            if (el.type === 'radio'    && !el.checked) return;

            if (el.type === 'checkbox') {
                if (!settings[name]) settings[name] = [];
                settings[name].push(val);
            } else {
                settings[name] = val;
            }
        });

        ajax('pbuaiv_save_settings', { settings: settings }, $btn)
            .done(function (res) {
                var $notice = $('#pbuaiv-save-notice');
                if (res.success) {
                    showNotice($notice, 'success', '✓ ' + (res.data.message || 'Settings saved.'));
                } else {
                    showNotice($notice, 'error', '✗ ' + (res.data.message || 'Error saving settings.'));
                }
            })
            .fail(function () {
                showNotice($('#pbuaiv-save-notice'), 'error', '✗ Request failed. Please try again.');
            });
    });

    /* ────────────────────────────────────────────────────────────────
       TRN LIVE VALIDATION
    ──────────────────────────────────────────────────────────────── */
    function validateTRN(trn, $status) {
        if (!trn) {
            $status.removeClass('valid invalid').addClass('empty')
                   .html('<span>Enter your 15-digit TRN</span>');
            return;
        }
        var clean = trn.replace(/\s/g, '');
        if (/^\d{15}$/.test(clean) && (clean[0] === '1' || clean[0] === '3')) {
            $status.removeClass('empty invalid').addClass('valid')
                   .html('<span>✓ Valid UAE TRN format</span>');
        } else {
            $status.removeClass('empty valid').addClass('invalid')
                   .html('<span>✗ Must be 15 digits, starting with 1 or 3</span>');
        }
    }

    $(document).on('input', '.pbuaiv-trn-input', function () {
        var $field  = $(this).closest('.pbuaiv-field, .pbuaiv-form-grid > div, .pbuaiv-setup-panel');
        var $status = $field.find('.pbuaiv-trn-status');
        if (!$status.length) $status = $(this).siblings('.pbuaiv-trn-status');
        validateTRN($(this).val(), $status);
    });

    // Init TRN on load
    $('.pbuaiv-trn-input').each(function () {
        var $status = $(this).closest('.pbuaiv-field, .pbuaiv-form-grid > div, .pbuaiv-setup-panel')
                             .find('.pbuaiv-trn-status');
        if (!$status.length) $status = $(this).siblings('.pbuaiv-trn-status');
        validateTRN($(this).val(), $status);
    });

    /* ────────────────────────────────────────────────────────────────
       LOGO MEDIA UPLOAD
    ──────────────────────────────────────────────────────────────── */
    var logoFrame;

    // Clicking the placeholder image area also opens the media picker
    $(document).on('click', '#pbuaiv-logo-placeholder, #pbuaiv-logo-preview', function (e) {
        e.preventDefault();
        $('#pbuaiv-upload-logo').trigger('click');
    });

    $(document).on('click', '#pbuaiv-upload-logo', function (e) {
        e.preventDefault();
        if (typeof wp === 'undefined' || !wp.media) return;

        if (!logoFrame) {
            logoFrame = wp.media({
                title:   PBUAIV.i18n ? PBUAIV.i18n.select_logo || 'Select Company Logo' : 'Select Company Logo',
                button:  { text: 'Use This Image' },
                library: { type: 'image' },
                multiple: false
            });
            logoFrame.on('select', function () {
                var att = logoFrame.state().get('selection').first().toJSON();
                var $wrap = $('#pbuaiv-logo-wrap');
                $wrap.html('<img src="' + att.url + '" class="pbuaiv-logo-preview" id="pbuaiv-logo-preview" />');
                $('#pbuaiv-logo-id').val(att.id);
                // Show remove button
                if (!$('#pbuaiv-remove-logo').length) {
                    $('<button type="button" class="pbuaiv-btn pbuaiv-btn--danger pbuaiv-btn--sm" id="pbuaiv-remove-logo" style="margin-left:6px;"><?php esc_html_e( "Remove", "pb-invoicing-system" ); ?></button>')
                        .insertAfter('#pbuaiv-upload-logo');
                }
            });
        }
        logoFrame.open();
    });

    $(document).on('click', '#pbuaiv-remove-logo', function (e) {
        e.preventDefault();
        $('#pbuaiv-logo-wrap').html(
            '<div class="pbuaiv-logo-placeholder" id="pbuaiv-logo-placeholder">' +
            '<span class="dashicons dashicons-format-image"></span>' +
            '<span>No logo uploaded</span></div>'
        );
        $('#pbuaiv-logo-id').val('');
        $(this).remove();
    });

    /* ────────────────────────────────────────────────────────────────
       COLOR PICKERS
    ──────────────────────────────────────────────────────────────── */
    if ($.fn.wpColorPicker) {
        $('.pbuaiv-color-picker').wpColorPicker({
            change: function (event, ui) {
                $(this).val(ui.color.toString());
            }
        });
    }

    /* ────────────────────────────────────────────────────────────────
       TEMPLATE OPTION SELECTOR (wizard step 3 — .pbuaiv-template-option)
    ──────────────────────────────────────────────────────────────── */
    $(document).on('change', '.pbuaiv-template-option input[type="radio"]', function () {
        $('.pbuaiv-template-option').removeClass('pbuaiv-template-option--selected');
        $(this).closest('.pbuaiv-template-option').addClass('pbuaiv-template-option--selected');
    });

    // Init on load
    $('.pbuaiv-template-option input[type="radio"]:checked').each(function () {
        $(this).closest('.pbuaiv-template-option').addClass('pbuaiv-template-option--selected');
    });

    /* ────────────────────────────────────────────────────────────────
       TEMPLATES PAGE — compact picker (.pbuaiv-template-opt)
    ──────────────────────────────────────────────────────────────── */
    // Radio selection → toggle active state
    $(document).on('change', '.pbuaiv-template-opt input[type="radio"]', function () {
        $('.pbuaiv-template-opt').removeClass('pbuaiv-template-opt--active');
        $(this).closest('.pbuaiv-template-opt').addClass('pbuaiv-template-opt--active');
    });

    // Click on the label itself also selects the radio
    $(document).on('click', '.pbuaiv-template-opt', function () {
        $(this).find('input[type="radio"]').prop('checked', true).trigger('change');
    });

    // Init active state on page load
    (function () {
        var $checked = $('.pbuaiv-template-opt input[type="radio"]:checked');
        if ($checked.length) {
            $checked.closest('.pbuaiv-template-opt').addClass('pbuaiv-template-opt--active');
        } else {
            $('.pbuaiv-template-opt:first').addClass('pbuaiv-template-opt--active')
                .find('input[type="radio"]').prop('checked', true);
        }
    })();

    // Preview button
    $(document).on('click', '#pbuaiv-preview-btn', function () {
        var $btn     = $(this);
        var template = $('input[name="pbuaiv_default_template"]:checked').val() || 'modern';
        var docType  = $('#pbuaiv-preview-doc-type').val() || 'invoice';
        var $iframe  = $('#pbuaiv-preview-iframe');
        var $loading = $('#pbuaiv-preview-loading');

        $loading.show();
        $iframe.hide();
        $('#pbuaiv-preview-placeholder').hide();

        ajax('pbuaiv_preview_template', { template: template, doc_type: docType }, $btn)
            .done(function (res) {
                if (res.success && res.data.html) {
                    $iframe.attr('srcdoc', res.data.html);
                    $iframe.show();
                } else {
                    var msg = (res.data && res.data.message) ? res.data.message : 'No orders found. Create a test order to preview.';
                    $iframe.attr('srcdoc',
                        '<html><body style="font-family:sans-serif;padding:40px;color:#64748b;text-align:center;">' +
                        '<p style="font-size:14px;">⚠ ' + msg + '</p></body></html>'
                    ).show();
                }
            })
            .fail(function () {
                $iframe.attr('srcdoc',
                    '<html><body style="font-family:sans-serif;padding:40px;color:#ef4444;text-align:center;">' +
                    '<p>Preview request failed. Please try again.</p></body></html>'
                ).show();
            })
            .always(function () { $loading.hide(); });
    });

    // Save template as default
    $(document).on('click', '#pbuaiv-save-template', function () {
        var $btn     = $(this);
        var template = $('input[name="pbuaiv_default_template"]:checked').val() || 'modern';
        var origText = $btn.text();

        ajax('pbuaiv_save_settings', { settings: { pbuaiv_default_template: template } }, $btn)
            .done(function (res) {
                if (res.success) {
                    $btn.text('✓ Saved!');
                    setTimeout(function () { $btn.text(origText); }, 2000);
                }
            });
    });

    /* ────────────────────────────────────────────────────────────────
       METABOX — ISSUE DOCUMENT
    ──────────────────────────────────────────────────────────────── */
    $(document).on('click', '.pbuaiv-action-issue', function (e) {
        e.preventDefault();
        if (!confirm(PBUAIV.i18n ? PBUAIV.i18n.confirm_issue : 'Issue this document? This will assign a permanent number.')) return;

        var $btn    = $(this);
        var type    = $btn.data('type');
        var orderId = $btn.data('order');

        ajax('pbuaiv_issue', { doc_type: type, order_id: orderId }, $btn)
            .done(function (res) {
                if (res.success) {
                    var d   = res.data;
                    var $row = $btn.closest('.pbuaiv-doc-row');
                    // Update badge
                    $row.find('.pbuaiv-badge').removeClass('pbuaiv-badge--pending')
                        .addClass('pbuaiv-badge--issued').text(d.doc_number);
                    // Replace action area
                    var actions =
                        '<a href="' + d.download_url + '" target="_blank" class="pbuaiv-btn pbuaiv-btn--secondary pbuaiv-btn--sm">' +
                        '<span class="dashicons dashicons-download"></span> Download</a>' +
                        '<a href="' + d.view_url + '" target="_blank" class="pbuaiv-btn pbuaiv-btn--ghost pbuaiv-btn--sm">' +
                        '<span class="dashicons dashicons-visibility"></span> View</a>' +
                        '<button class="pbuaiv-btn pbuaiv-btn--ghost pbuaiv-btn--sm pbuaiv-action-send" data-type="' + type + '" data-order="' + orderId + '">' +
                        '<span class="dashicons dashicons-email-alt"></span></button>' +
                        '<button class="pbuaiv-btn pbuaiv-btn--danger pbuaiv-btn--sm pbuaiv-action-void" data-type="' + type + '" data-order="' + orderId + '">' +
                        '<span class="dashicons dashicons-trash"></span></button>';
                    $row.find('.pbuaiv-doc-row__actions').html(actions);
                    showNotice($('#pbuaiv-metabox-notice'), 'success', '✓ ' + d.message);
                } else {
                    showNotice($('#pbuaiv-metabox-notice'), 'error', res.data ? res.data.message : 'Error issuing document.');
                }
            })
            .fail(function () {
                showNotice($('#pbuaiv-metabox-notice'), 'error', 'Request failed.');
            });
    });

    /* ────────────────────────────────────────────────────────────────
       METABOX — SEND EMAIL
    ──────────────────────────────────────────────────────────────── */
    $(document).on('click', '.pbuaiv-action-send', function (e) {
        e.preventDefault();
        var $btn    = $(this);
        var type    = $btn.data('type');
        var orderId = $btn.data('order');

        ajax('pbuaiv_send', { doc_type: type, order_id: orderId }, $btn)
            .done(function (res) {
                var msg = res.data ? res.data.message : '';
                showNotice($('#pbuaiv-metabox-notice'), res.success ? 'success' : 'error',
                    (res.success ? '✓ ' : '✗ ') + msg);
            });
    });

    /* ────────────────────────────────────────────────────────────────
       METABOX — VOID DOCUMENT
    ──────────────────────────────────────────────────────────────── */
    $(document).on('click', '.pbuaiv-action-void', function (e) {
        e.preventDefault();
        if (!confirm(PBUAIV.i18n ? PBUAIV.i18n.confirm_void : 'Void this document? This cannot be undone.')) return;

        var $btn    = $(this);
        var type    = $btn.data('type');
        var orderId = $btn.data('order');

        ajax('pbuaiv_void', { doc_type: type, order_id: orderId }, $btn)
            .done(function (res) {
                if (res.success) {
                    var $row = $btn.closest('.pbuaiv-doc-row');
                    $row.find('.pbuaiv-badge').removeClass('pbuaiv-badge--issued').addClass('pbuaiv-badge--void').text('Voided');
                    $row.find('.pbuaiv-doc-row__actions').html('');
                }
                showNotice($('#pbuaiv-metabox-notice'), res.success ? 'success' : 'error',
                    (res.success ? '✓ ' : '✗ ') + (res.data ? res.data.message : ''));
            });
    });

    /* ────────────────────────────────────────────────────────────────
       METABOX — REGENERATE PDF
    ──────────────────────────────────────────────────────────────── */
    $(document).on('click', '.pbuaiv-action-regenerate', function (e) {
        e.preventDefault();
        var $btn    = $(this);
        var type    = $btn.data('type');
        var orderId = $btn.data('order');

        ajax('pbuaiv_regenerate', { doc_type: type, order_id: orderId }, $btn)
            .done(function (res) {
                showNotice($('#pbuaiv-metabox-notice'), res.success ? 'success' : 'error',
                    (res.success ? '✓ ' : '✗ ') + (res.data ? res.data.message : ''));
            });
    });

    /* ────────────────────────────────────────────────────────────────
       NUMBERING — SET NEXT NUMBER
    ──────────────────────────────────────────────────────────────── */
    $(document).on('click', '.pbuaiv-reset-sequence', function (e) {
        e.preventDefault();
        var $btn    = $(this);
        var type    = $btn.data('type');
        var inputId = $btn.data('input');
        var next    = parseInt($('#' + inputId).val(), 10);

        if (isNaN(next) || next < 1) {
            alert('Please enter a valid number (1 or higher).');
            return;
        }

        ajax('pbuaiv_reset_sequence', { doc_type: type, next_number: next }, $btn)
            .done(function (res) {
                if (res.success) {
                    // Update the "Next: X" badge in card head
                    $btn.closest('.pbuaiv-card').find('.pbuaiv-card__head-sub')
                        .text('Next: ' + (res.data.preview || next));
                    // Flash confirmation
                    $('<span>')
                        .addClass('pbuaiv-notice pbuaiv-notice--success')
                        .css({ display:'inline-flex', padding:'4px 10px', 'font-size':'11px', 'margin-left':'8px', 'border-radius':'4px' })
                        .text('✓ Saved')
                        .insertAfter($btn)
                        .delay(2500).fadeOut(400, function () { $(this).remove(); });
                }
            });
    });

    /* ────────────────────────────────────────────────────────────────
       DOCUMENTS LIST — BULK DOWNLOAD & CHECK-ALL
    ──────────────────────────────────────────────────────────────── */
    $(document).on('click', '#pbuaiv-bulk-download', function (e) {
        e.preventDefault();
        var ids = [];
        $('.pbuaiv-doc-check:checked').each(function () { ids.push($(this).val()); });
        if (!ids.length) { alert('Select at least one document.'); return; }

        ajax('pbuaiv_bulk_download', { doc_ids: ids }, $(this))
            .done(function (res) {
                if (res.success && res.data.zip_url) {
                    window.location.href = res.data.zip_url;
                } else {
                    alert((res.data && res.data.message) || 'Failed to create ZIP.');
                }
            });
    });

    $(document).on('change', '#pbuaiv-check-all', function () {
        $('.pbuaiv-doc-check').prop('checked', $(this).is(':checked'));
    });

    /* ────────────────────────────────────────────────────────────────
       INIT: show first wizard step if on onboarding page
    ──────────────────────────────────────────────────────────────── */


    /* ────────────────────────────────────────────────────────────────
       ONBOARDING — FTA CHECKLIST REFRESH
    ──────────────────────────────────────────────────────────────── */
    function pbuaivRefreshChecklist() {
        var form = document.getElementById('pbuaiv-onboarding');
        if (!form) {
            return;
        }

        function updateCheck(id, pass) {
            var el = document.getElementById('pbuaiv-check-' + id);
            if (!el) {
                return;
            }
            el.className = 'pbuaiv-check-item ' + (pass ? 'pbuaiv-check--pass' : 'pbuaiv-check--warn');
            el.textContent = (pass ? '✅' : '⚠️') + ' ' + el.textContent.replace(/^[✅⚠️]+ ?/, '');
        }

        var trnField = form.querySelector('[name="pbuaiv_trn"]');
        var nameField = form.querySelector('[name="pbuaiv_company_name"]');
        var addressField = form.querySelector('[name="pbuaiv_company_address"]');
        var trn = trnField ? trnField.value : '';
        var companyName = nameField ? nameField.value : '';
        var address = addressField ? addressField.value : '';
        var trnClean = trn.replace(/\s/g, '');
        var trnValid = /^\d{15}$/.test(trnClean) && (trnClean.charAt(0) === '1' || trnClean.charAt(0) === '3');

        updateCheck('trn', trnValid);
        updateCheck('name', companyName.trim().length > 0);
        updateCheck('address', address.trim().length > 0);
        updateCheck('qr', trnValid);
    }

    document.addEventListener('pbuaiv:wizard_saved', pbuaivRefreshChecklist);

    if ($('#pbuaiv-onboarding').length) {
        goToStep(1);
        pbuaivRefreshChecklist();
    }

})(jQuery);
