jQuery(document).ready(function ($) {
    $('#registerLicenseBtn').click(function (e) {
        e.preventDefault();

        var email = $('#elEmail').val();
        var domain = window.location.hostname;
        const fetchDomain = document.querySelector('meta[name="license_url"]')?.content;
        $.ajax({
            url: fetchDomain+'/api/register-license',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                email: email,
                domain: domain
            }),
            success: function (response) {
                $('#result').html('<div class="notice notice-success is-dismissible"><p>' + response.message + '</p></div>');
            },
            error: function (xhr) {
                let errorMessages = '';

                if (xhr.responseJSON && xhr.responseJSON.errors) {
                    const errors = xhr.responseJSON.errors;
                    for (let field in errors) {
                        if (errors.hasOwnProperty(field)) {
                            errorMessages += '<div class="notice notice-error is-dismissible"><p>' + errors[field].join('<br>') + '</p></div>';
                        }
                    }
                } else {
                    errorMessages = '<div class="notice notice-error is-dismissible"><p>Có lỗi xảy ra không xác định.</p></div>';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        errorMessages = '<div class="notice notice-error is-dismissible"><p>' + xhr.responseJSON.message + '</p></div>';
                    }
                }

                $('#result').html(errorMessages);
            }
        });
    });

    $('#changeActive').click(function (e) {
        e.preventDefault();
        $('#r1').hide();
        $('#r2').show();
    });
    $('#changeActive2').click(function (e) {
        e.preventDefault();
        $('#r1').show();
        $('#r2').hide();
    });
});