/**
 * WC Licensed Product - Order Licenses Admin
 *
 * @package Jeremias\WcLicensedProduct
 */

(function($) {
    'use strict';

    var WCLPOrderLicenses = {
        init: function() {
            this.bindEvents();
        },

        bindEvents: function() {
            // Order domain save
            $('#wclp-save-order-domain').on('click', this.saveOrderDomain.bind(this));

            // Generate licenses button
            $(document).on('click', '#wclp-generate-licenses', this.generateLicenses.bind(this));

            // License domain edit/save/cancel
            $(document).on('click', '.wclp-edit-domain-btn', this.startEditDomain);
            $(document).on('click', '.wclp-save-domain-btn', this.saveLicenseDomain.bind(this));
            $(document).on('click', '.wclp-cancel-domain-btn', this.cancelEditDomain);

            // Enter key on domain inputs
            $('#wclp-order-domain').on('keypress', function(e) {
                if (e.which === 13) {
                    e.preventDefault();
                    $('#wclp-save-order-domain').click();
                }
            });

            $(document).on('keypress', '.wclp-domain-input', function(e) {
                if (e.which === 13) {
                    e.preventDefault();
                    $(this).closest('.wclp-license-domain-edit').find('.wclp-save-domain-btn').click();
                }
            });
        },

        /**
         * Save order domain
         */
        saveOrderDomain: function(e) {
            e.preventDefault();

            var $btn = $('#wclp-save-order-domain');
            var $input = $('#wclp-order-domain');
            var $spinner = $btn.siblings('.spinner');
            var $message = $btn.siblings('.wclp-status-message');

            var orderId = $input.data('order-id');
            var domain = $input.val().trim();

            $btn.prop('disabled', true);
            $spinner.addClass('is-active');
            $message.text('').removeClass('success error');

            $.ajax({
                url: wclpOrderLicenses.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'wclp_update_order_domain',
                    nonce: wclpOrderLicenses.nonce,
                    order_id: orderId,
                    domain: domain
                },
                success: function(response) {
                    if (response.success) {
                        $input.val(response.data.domain);
                        $message.text(wclpOrderLicenses.strings.saved).addClass('success');
                    } else {
                        $message.text(response.data.message || wclpOrderLicenses.strings.error).addClass('error');
                    }
                },
                error: function() {
                    $message.text(wclpOrderLicenses.strings.error).addClass('error');
                },
                complete: function() {
                    $btn.prop('disabled', false);
                    $spinner.removeClass('is-active');

                    // Clear message after 3 seconds
                    setTimeout(function() {
                        $message.text('').removeClass('success error');
                    }, 3000);
                }
            });
        },

        /**
         * Start editing license domain
         */
        startEditDomain: function(e) {
            e.preventDefault();

            var $container = $(this).closest('.wclp-license-domain-edit');
            var $display = $container.find('.wclp-domain-display');
            var $input = $container.find('.wclp-domain-input');
            var $editBtn = $container.find('.wclp-edit-domain-btn');
            var $saveBtn = $container.find('.wclp-save-domain-btn');
            var $cancelBtn = $container.find('.wclp-cancel-domain-btn');

            // Store original value
            $input.data('original', $display.text());

            // Toggle visibility
            $display.hide();
            $editBtn.hide();
            $input.show().focus().select();
            $saveBtn.show();
            $cancelBtn.show();
        },

        /**
         * Cancel editing license domain
         */
        cancelEditDomain: function(e) {
            e.preventDefault();

            var $container = $(this).closest('.wclp-license-domain-edit');
            var $display = $container.find('.wclp-domain-display');
            var $input = $container.find('.wclp-domain-input');
            var $editBtn = $container.find('.wclp-edit-domain-btn');
            var $saveBtn = $container.find('.wclp-save-domain-btn');
            var $cancelBtn = $container.find('.wclp-cancel-domain-btn');

            // Restore original value
            $input.val($input.data('original'));

            // Toggle visibility
            $input.hide();
            $saveBtn.hide();
            $cancelBtn.hide();
            $display.show();
            $editBtn.show();
        },

        /**
         * Generate licenses for order
         */
        generateLicenses: function(e) {
            e.preventDefault();

            var $btn = $(e.currentTarget);
            var $spinner = $btn.siblings('.spinner');
            var $status = $btn.siblings('.wclp-generate-status');

            var orderId = $btn.data('order-id');

            $btn.prop('disabled', true);
            $spinner.addClass('is-active');
            $status.text('').removeClass('success error');

            $.ajax({
                url: wclpOrderLicenses.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'wclp_generate_order_licenses',
                    nonce: wclpOrderLicenses.nonce,
                    order_id: orderId
                },
                success: function(response) {
                    if (response.success) {
                        $status.text(response.data.message).addClass('success');
                        if (response.data.reload) {
                            // Reload the page after a short delay to show the new licenses
                            setTimeout(function() {
                                window.location.reload();
                            }, 1500);
                        }
                    } else {
                        $status.text(response.data.message || wclpOrderLicenses.strings.error).addClass('error');
                        $btn.prop('disabled', false);
                    }
                },
                error: function() {
                    $status.text(wclpOrderLicenses.strings.error).addClass('error');
                    $btn.prop('disabled', false);
                },
                complete: function() {
                    $spinner.removeClass('is-active');
                }
            });
        },

        /**
         * Save license domain
         */
        saveLicenseDomain: function(e) {
            e.preventDefault();

            var $btn = $(e.currentTarget);
            var $container = $btn.closest('.wclp-license-domain-edit');
            var $row = $btn.closest('tr');
            var $input = $container.find('.wclp-domain-input');
            var $display = $container.find('.wclp-domain-display');
            var $spinner = $container.find('.spinner');
            var $editBtn = $container.find('.wclp-edit-domain-btn');
            var $cancelBtn = $container.find('.wclp-cancel-domain-btn');

            var licenseId = $row.data('license-id');
            var domain = $input.val().trim();

            if (!domain) {
                alert(wclpOrderLicenses.strings.invalidDomain);
                return;
            }

            $btn.prop('disabled', true);
            $cancelBtn.prop('disabled', true);
            $spinner.addClass('is-active');

            $.ajax({
                url: wclpOrderLicenses.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'wclp_update_license_domain',
                    nonce: wclpOrderLicenses.nonce,
                    license_id: licenseId,
                    domain: domain
                },
                success: function(response) {
                    if (response.success) {
                        // Update display
                        $display.text(response.data.domain);
                        $input.val(response.data.domain);

                        // Switch back to display mode
                        $input.hide();
                        $btn.hide();
                        $cancelBtn.hide();
                        $display.show();
                        $editBtn.show();
                    } else {
                        alert(response.data.message || wclpOrderLicenses.strings.error);
                    }
                },
                error: function() {
                    alert(wclpOrderLicenses.strings.error);
                },
                complete: function() {
                    $btn.prop('disabled', false);
                    $cancelBtn.prop('disabled', false);
                    $spinner.removeClass('is-active');
                }
            });
        }
    };

    $(document).ready(function() {
        WCLPOrderLicenses.init();
    });

})(jQuery);
