/**
 * Admin JavaScript for WooCommerce Tier and Package Prices
 */

(function($) {
    'use strict';

    $(document).ready(function() {
        // Initialize indexes for simple products
        let tierIndex = $('.wc-tpp-tier-pricing .wc-tpp-tier-row').length;
        let packageIndex = $('.wc-tpp-package-pricing .wc-tpp-package-row').length;

        // Function to update table header visibility
        function updateTableHeaders() {
            // Check all tier tables
            $('.wc-tpp-tiers-table').each(function() {
                const $table = $(this);
                const $tbody = $table.find('.wc-tpp-tiers-container');
                const hasRows = $tbody.find('tr').length > 0;
                $table.toggleClass('has-rows', hasRows);
            });

            // Check all package tables
            $('.wc-tpp-packages-table').each(function() {
                const $table = $(this);
                const $tbody = $table.find('.wc-tpp-packages-container');
                const hasRows = $tbody.find('tr').length > 0;
                $table.toggleClass('has-rows', hasRows);
            });
        }

        // Initialize table headers on page load
        updateTableHeaders();

        // ========================================
        // Simple Product Handlers
        // ========================================

        // Add tier (simple products)
        $('.wc-tpp-tier-pricing .wc-tpp-add-tier').on('click', function(e) {
            e.preventDefault();
            const template = $('#wc-tpp-tier-row-template').html();
            const newRow = template.replace(/\{\{INDEX\}\}/g, tierIndex);
            $('.wc-tpp-tier-pricing .wc-tpp-tiers-container').append(newRow);
            tierIndex++;
            updateTableHeaders();
        });

        // Add package (simple products)
        $('.wc-tpp-package-pricing .wc-tpp-add-package').on('click', function(e) {
            e.preventDefault();
            const template = $('#wc-tpp-package-row-template').html();
            const newRow = template.replace(/\{\{INDEX\}\}/g, packageIndex);
            $('.wc-tpp-package-pricing .wc-tpp-packages-container').append(newRow);
            packageIndex++;
            updateTableHeaders();
        });

        // ========================================
        // Variable Product Parent Handlers
        // ========================================

        // Add tier (variable product parent default pricing)
        $('.wc-tpp-variable-parent-pricing .wc-tpp-add-tier').on('click', function(e) {
            e.preventDefault();
            const template = $('#wc-tpp-tier-row-template').html();
            const newRow = template.replace(/\{\{INDEX\}\}/g, tierIndex);
            $('.wc-tpp-variable-parent-pricing .wc-tpp-tiers-container').append(newRow);
            tierIndex++;
            updateTableHeaders();
        });

        // Add package (variable product parent default pricing)
        $('.wc-tpp-variable-parent-pricing .wc-tpp-add-package').on('click', function(e) {
            e.preventDefault();
            const template = $('#wc-tpp-package-row-template').html();
            const newRow = template.replace(/\{\{INDEX\}\}/g, packageIndex);
            $('.wc-tpp-variable-parent-pricing .wc-tpp-packages-container').append(newRow);
            packageIndex++;
            updateTableHeaders();
        });

        // ========================================
        // Variable Product Variation Handlers
        // ========================================

        // Add tier (variations)
        $(document).on('click', '.wc-tpp-variation-pricing .wc-tpp-add-tier', function(e) {
            e.preventDefault();
            const $button = $(this);
            const loop = $button.data('loop');
            const $container = $button.closest('.wc-tpp-variation-pricing');
            const $tbody = $container.find('.wc-tpp-variation-tiers .wc-tpp-tiers-container');
            const template = $('#wc-tpp-variation-tier-row-template-' + loop).html();

            // Count existing rows to get next index
            const currentIndex = $tbody.find('tr').length;
            const newRow = template.replace(/\{\{INDEX\}\}/g, currentIndex);

            $tbody.append(newRow);
            updateTableHeaders();
        });

        // Add package (variations)
        $(document).on('click', '.wc-tpp-variation-pricing .wc-tpp-add-package', function(e) {
            e.preventDefault();
            const $button = $(this);
            const loop = $button.data('loop');
            const $container = $button.closest('.wc-tpp-variation-pricing');
            const $tbody = $container.find('.wc-tpp-variation-packages .wc-tpp-packages-container');
            const template = $('#wc-tpp-variation-package-row-template-' + loop).html();

            // Count existing rows to get next index
            const currentIndex = $tbody.find('tr').length;
            const newRow = template.replace(/\{\{INDEX\}\}/g, currentIndex);

            $tbody.append(newRow);
            updateTableHeaders();
        });

        // ========================================
        // Common Handlers (both simple and variations)
        // ========================================

        // Remove tier
        $(document).on('click', '.wc-tpp-remove-tier', function(e) {
            e.preventDefault();
            if (confirm('Are you sure you want to remove this tier?')) {
                $(this).closest('.wc-tpp-tier-row').remove();
                updateTableHeaders();
            }
        });

        // Remove package
        $(document).on('click', '.wc-tpp-remove-package', function(e) {
            e.preventDefault();
            if (confirm('Are you sure you want to remove this package?')) {
                $(this).closest('.wc-tpp-package-row').remove();
                updateTableHeaders();
            }
        });

        // Validate quantity inputs
        $(document).on('input', 'input[name*="[min_qty]"], input[name*="[qty]"]', function() {
            const value = parseInt($(this).val());
            if (value < 1) {
                $(this).val(1);
            }
        });

        // Validate price inputs
        $(document).on('input', 'input[name*="[price]"]', function() {
            const value = parseFloat($(this).val());
            if (value < 0) {
                $(this).val(0);
            }
        });
    });

})(jQuery);
