/**
 * Order Role Manager settings scripts.
 */
jQuery(function ($) {
    'use strict';

    $('.wosr_select2, .wosr-select2').selectWoo({
        placeholder: 'Select an option',
        allowClear: true
    });

    $('.payment-methods, .screen-elements, .statuses').on('change', function () {
        const $select = $(this);
        const selected = $select.val() || [];
        if (selected.includes('select_all')) {
            $select.find('option').prop('selected', true);
            $select.find('option[value="select_all"]').prop('selected', false);
            $select.trigger('change');
        }
    });

    $('.delete-rule-btn').on('click', function (event) {
        event.preventDefault();
        if (window.confirm('Are you sure you want to delete this rule?')) {
            $(this).closest('form').trigger('submit');
        }
    });

    function bindRuleToggle(selector, action) {
        $(selector).on('change', function () {
            const $checkbox = $(this);
            if ($checkbox.data('wosrBusy')) {
                return;
            }

            const requestedState = $checkbox.prop('checked');
            let $message = $checkbox.closest('td').find('.status-message').first();
            if (!$message.length) {
                $message = $('<p class="status-message" style="display:none;"></p>');
                $checkbox.closest('td').append($message);
            }

            $checkbox.data('wosrBusy', true).prop('disabled', true);
            $.ajax({
                url: wosr_vars.ajax_url,
                method: 'POST',
                data: {
                    action: action,
                    rule_id: $checkbox.data('rule-id'),
                    status: requestedState,
                    nonce: wosr_vars.nonce
                },
                beforeSend: function () {
                    $message.stop(true, true).text('Updating...').show();
                },
                success: function (response) {
                    if (response.success) {
                        $message.text('Updated successfully').delay(1200).fadeOut(400);
                    } else {
                        $message.text((response.data && response.data.message) || 'Update failed').delay(1600).fadeOut(400);
                        $checkbox.prop('checked', !requestedState);
                    }
                },
                error: function () {
                    $message.text('An error occurred').delay(1600).fadeOut(400);
                    $checkbox.prop('checked', !requestedState);
                },
                complete: function () {
                    $checkbox.data('wosrBusy', false).prop('disabled', false);
                }
            });
        });
    }

    bindRuleToggle('.wosr-payment-rule-toggle', 'wosr_toggle_rule_status');
    bindRuleToggle('.wosr-payment-rule-toggle-overview', 'wosr_toggle_rule_status_overview');

    $('.wosr-select2[data-max-selection]').on('change', function () {
        const $select = $(this);
        const maxAllowed = parseInt($select.data('max-selection'), 10) || 1;
        const selected = $select.val() || [];
        if (selected.length > maxAllowed) {
            $('#wosr-upgrade-modal').find('.wosr-upgrade-message').text('Upgrade to select multiple User Roles.');
            $('#wosr-upgrade-modal').fadeIn();
            selected.pop();
            $select.val(selected).trigger('change');
        }
    });

    $('.wosr-upgrade-close, .wosr-modal-overlay').on('click', function () {
        $('#wosr-upgrade-modal').fadeOut();
    });
});
