/**
 * W2PShop Reorder Functionality
 * 
 * Handles reordering of W2PShop products with all custom data preserved
 */

jQuery(document).ready(function($) {
    
    // Handle reorder button clicks
    $(document).on('click', '.w2pshop-reorder-btn', function(e) {
        e.preventDefault();
        
        var $button = $(this);
        var productId = $button.data('product-id');
        var w2pshopData = $button.data('w2pshop-data');
        var itemId = $button.data('item-id');
        var orderId = $button.data('order-id');
        
        // Disable button to prevent double-clicks
        $button.prop('disabled', true).text('Adding to cart...');
        
        // Make AJAX request to reorder
        $.ajax({
            url: w2pshop_reorder_data.ajaxurl,
            type: 'POST',
            data: {
                action: 'w2pshop_reorder_item',
                nonce: w2pshop_reorder_data.nonce,
                product_id: productId,
                w2pshop_data: w2pshopData,
                item_id: itemId,
                order_id: orderId
            },
            // Prevent WooCommerce from intercepting our custom error handling
            beforeSend: function() {
                // Clear any existing WooCommerce error messages
                $('.woocommerce-error, .woocommerce-message').remove();
            },
            success: function(response) {

                
                if (response.success) {
                    // Show success message
                    if (typeof wc_add_to_cart_params !== 'undefined') {
                        // Use WooCommerce's built-in notification if available
                        $(document.body).trigger('added_to_cart', [response.data, response.data.redirect_url]);
                    } else {
                        // Fallback success message
                        alert('Product added to cart successfully!');
                    }
                    
                    // Redirect to cart page
                    if (response.data.redirect_url) {
                        window.location.href = response.data.redirect_url;
                    }
                } else {
                    // Check if this is a product unavailable error
                    if (response.data.type === 'product_unavailable') {

                        // Show SweetAlert with "Go to Shop" button
                        if (typeof Swal !== 'undefined') {

                            Swal.fire({
                                title: 'Product Unavailable',
                                text: response.data.message,
                                icon: 'warning',
                                confirmButtonText: 'Go to Shop',
                                confirmButtonColor: '#3085d6',
                                showCancelButton: true,
                                cancelButtonText: 'Close',
                                cancelButtonColor: '#6c757d'
                            }).then((result) => {
                                if (result.isConfirmed && response.data.shop_url) {
                                    window.location.href = response.data.shop_url;
                                }
                            });
                        } else {

                            // Fallback if SweetAlert is not available
                            if (confirm(response.data.message + '\n\nWould you like to go to the shop page?')) {
                                if (response.data.shop_url) {
                                    window.location.href = response.data.shop_url;
                                }
                            }
                        }
                    } else {
                        // Always show SweetAlert if available for any error
                        if (typeof Swal !== 'undefined') {
                            Swal.fire({
                                title: 'Unable to Reorder',
                                text: response.data && response.data.message ? response.data.message : 'Unable to add to cart.',
                                icon: 'error',
                                confirmButtonText: 'Go to Shop',
                                showCancelButton: true,
                                cancelButtonText: 'Close'
                            }).then((result) => {
                                if (result.isConfirmed && response.data && response.data.shop_url) {
                                    window.location.href = response.data.shop_url;
                                }
                            });
                        } else {
                            alert('Error: ' + (response.data && response.data.message ? response.data.message : 'Unable to add to cart.'));
                        }
                    }
                    
                    // Re-enable button
                    $button.prop('disabled', false).text('Reorder Item');
                }
            },
            error: function(xhr, status, error) {
                // Show error message
                alert('Error occurred while adding to cart. Please try again.');
                
                // Re-enable button
                $button.prop('disabled', false).text('Reorder Item');
            }
        });
    });
    
}); 