/**
 * UltraGuard Compliance Reports — admin page JS
 *
 * Flow:
 *  1. User clicks Generate (any report card or header button)
 *  2. AJAX POST to ultraguard_compliance_generate
 *  3. On success: show toast, then reload the page
 *     -> Reloaded page shows the new row with "Print / Save PDF" button
 *     -> Print button opens the report in a new tab with auto-print dialog
 *  4. No automatic file download or window.location redirect.
 */
(function ($) {
    'use strict';

    function showToast(message, type) {
        if (window.UltraGuardComponents && typeof window.UltraGuardComponents.showMessage === 'function') {
            window.UltraGuardComponents.showMessage({}, message, type || 'info', 5000);
            return;
        }
        window.alert(message);
    }

    function showGeneratingState($button) {
        $button
            .prop('disabled', true)
            .addClass('is-busy')
            .data('original-text', $button.text())
            .text(ultraguardComplianceReports.i18n.generating);
    }

    function restoreButton($button) {
        var original = $button.data('original-text');
        $button.prop('disabled', false).removeClass('is-busy');
        if (original) { $button.text(original); }
    }

    // Intercept only compliance generate AJAX actions.
    // Delete / other actions are handled by the core UltraGuard AJAX manager.
    $(document).on('click', '.ultraguard-ajax-trigger[data-payload]', function (event) {
        var $button = $(this);
        var payload = $button.data('payload');

        if (!payload || !payload.action) { return; }
        if (payload.action !== 'ultraguard_compliance_generate') { return; }

        event.preventDefault();
        event.stopPropagation();

        showGeneratingState($button);

        payload._ajax_nonce = payload.nonce || ultraguardComplianceReports.nonce;

        $.post(ultraguardComplianceReports.ajaxUrl, payload)
            .done(function (response) {
                if (response && response.success) {
                    showToast(
                        (response.data && response.data.message)
                            ? response.data.message
                            : ultraguardComplianceReports.i18n.generated,
                        'success'
                    );

                    // Reload page so the new report row appears.
                    // The row has a "Print / Save PDF" button - no auto-download here.
                    setTimeout(function () { window.location.reload(); }, 1400);
                    return;
                }

                restoreButton($button);
                showToast(
                    (response && response.data && response.data.message)
                        ? response.data.message
                        : ultraguardComplianceReports.i18n.failed,
                    'error'
                );
            })
            .fail(function (xhr) {
                restoreButton($button);
                var message = ultraguardComplianceReports.i18n.failed;
                try {
                    var json = JSON.parse(xhr.responseText);
                    if (json && json.data && json.data.message) { message = json.data.message; }
                } catch (e) {}
                showToast(message, 'error');
            });
    });

})(jQuery);
