<?php
/**
 * Single Product Buy Button View
 * 
 * This view renders a form that allows users to buy a single product from Digikala
 */

global $product;

if (!$product || !is_a($product, 'WC_Product')) {
    return;
}

// Hide button for out-of-stock simple products
if ($product->is_type('simple') && (!$product->is_purchasable() || !$product->is_in_stock())) {
    return;
}

// For variable products, still render (JS handles variation selection)
if (!$product->is_purchasable()) {
    return;
}

// Get form action URL
$action_url = home_url('/bwdk-single-buy/');

// Get current quantity from cart form if it exists
$quantity = 1;

// Get product/variation IDs
$product_id = $product->get_id();
$variation_id = 0;

if ($product->is_type('variation')) {
    $variation_id = $product->get_id();
    $product_id = $product->get_parent_id();
}

// Get variation attributes for variable products
$variation_attributes = [];
if ($product->is_type('variable')) {
    // We'll need to capture variation data via JS when user selects
}

?>

<form method="post" action="<?php echo esc_url($action_url); ?>" class="bwdk-single-buy-form" id="bwdk-single-buy-form">
    <?php wp_nonce_field('bwdk_single_buy', 'bwdk_single_buy_nonce'); ?>
    
    <input type="hidden" name="product_id" value="<?php echo esc_attr($product_id); ?>" />
    <input type="hidden" name="variation_id" value="" />
    <input type="hidden" name="quantity" value="" />
    
    <button type="submit" class="bwdk-single-buy-button">
    <img src="<?php echo BWDK_PUBLIC_IMG."digiLogo.svg" ?>" alt="digikala" class="logo-digi">   
    <?php echo esc_html__('خرید با دیجی‌کالا', 'bwdk'); ?>

    </button>
</form>

<script type="text/javascript">
(function($) {
    'use strict';
    
    var $ourForm = $('#bwdk-single-buy-form');
    var $ourButton = $ourForm.find('button[type="submit"]');
    var originalButtonHtml = $ourButton.length ? $ourButton.html() : '';

    function ensureButtonReference() {
        if (!$ourButton || !$ourButton.length) {
            $ourButton = $ourForm.find('button[type="submit"]');
            if ($ourButton.length && !originalButtonHtml) {
                originalButtonHtml = $ourButton.html();
            }
        }
    }

    function setButtonEnabled(enabled) {
        ensureButtonReference();
        if (!$ourButton.length) {
            return;
        }

        if (enabled) {
            $ourButton.prop('disabled', false).removeClass('is-disabled');
            if (originalButtonHtml && $ourButton.html() !== originalButtonHtml) {
                $ourButton.html(originalButtonHtml);
            }
        } else {
            $ourButton.prop('disabled', true).addClass('is-disabled');
        }
    }

    function isTruthy(value) {
        return value === true ||
            value === 'true' ||
            value === 1 ||
            value === '1' ||
            value === 'instock' ||
            value === 'yes';
    }

    function removeVariationError() {
        var $wrapper = $('.woocommerce-notices-wrapper').first();
        if (!$wrapper.length) {
            $wrapper = $('.woocommerce').first();
        }
        if ($wrapper.length) {
            $wrapper.find('.bwdk-variation-error').remove();
        }
    }

    function applyVariationState(variation) {
        if (!variation) {
            setButtonEnabled(true);
            return;
        }

        var available = variation.is_in_stock === undefined ? true : isTruthy(variation.is_in_stock);
        var purchasable = variation.is_purchasable === undefined ? true : isTruthy(variation.is_purchasable);

        if (available && purchasable) {
            setButtonEnabled(true);
            removeVariationError();
        } else {
            setButtonEnabled(false);
        }
    }

    setButtonEnabled(true);
    
    // Handle form submission - copy fields from WooCommerce form
    $ourForm.on('submit', function(e) {
        var $form = $(this);
        var $cartForm = $form.closest('form.cart');
        var $variationsForm = $form.closest('form.variations_form');

        if (!$variationsForm.length && $cartForm.length) {
            if ($cartForm.hasClass('variations_form')) {
                $variationsForm = $cartForm;
            } else {
                $variationsForm = $cartForm.find('form.variations_form').first();
            }
        }

        if (!$variationsForm.length) {
            $variationsForm = $('form.variations_form').first();
        }

        var $sourceForm = $variationsForm.length ? $variationsForm : $cartForm;
        if (!$sourceForm || !$sourceForm.length) {
            $sourceForm = $('form.cart').first();
        }
        if (!$sourceForm.length) {
            $sourceForm = $('.variations_form').first();
        }

        // Pull quantity
        var qty = $sourceForm.find('input.qty').val() || 1;
        $form.find('input[name="quantity"]').val(qty);

        // Pull variation_id (Woo sets it when variation is chosen)
        var variationId = '';
        if ($variationsForm.length) {
            variationId = $variationsForm.find('input[name="variation_id"]').val() || '';
        }
        $form.find('input[name="variation_id"]').val(variationId);

        // Pull all attribute_* fields (global & custom)
        $sourceForm.find('select[name^="attribute_"], input[name^="attribute_"]').each(function() {
            var $f = $(this);
            var name = $f.attr('name');
            var val = $f.val();
            if (val == null || val === '') {
                val = '';
            }

            // Check if this field already exists in our form
            var $dest = $ourForm.find('[name="' + name + '"]');
            if ($dest.length === 0) {
                $('<input type="hidden">').attr('name', name).val(val).appendTo($ourForm);
            } else {
                $dest.val(val);
            }
        });

        var isVariable = $variationsForm.length > 0;

        // If variable product but no variation selected, block submit with native Woo message
        if (isVariable && (!variationId || variationId === '0')) {
            e.preventDefault();

            var msg = (window.wc_add_to_cart_variation_params &&
                (wc_add_to_cart_variation_params.i18n_make_a_selection_text ||
                 wc_add_to_cart_variation_params.i18n_choose_options ||
                 wc_add_to_cart_variation_params.i18n_no_matching_variations_text)) ||
                'لطفاً گزینه‌های محصول را انتخاب کنید.';

            var $wrapper = $('.woocommerce-notices-wrapper').first();
            if (!$wrapper.length) {
                $wrapper = $('.woocommerce').first();
            }

            if ($wrapper.length) {
                $wrapper.find('.bwdk-variation-error').remove();
                $wrapper.prepend(
                    '<ul class="woocommerce-error bwdk-variation-error" role="alert"><li>' +
                        msg +
                    '</li></ul>'
                );
                $('html, body').animate({ scrollTop: $wrapper.offset().top - 50 }, 200);
            } else {
                alert(msg);
            }

            return false;
        }

        setButtonEnabled(false);
        ensureButtonReference();
        if ($ourButton.length) {
            $ourButton.text('در حال انتقال...');
        }
    });
    
    // Store current variation data
    var currentVariationData = null;

    // Function to update button state based on variation selection
    function updateButtonState() {
        var $wooForm = $('form.variations_form').first();

        if (!$wooForm.length) {
            setButtonEnabled(true);
            return;
        }

        var variationId = $wooForm.find('input[name="variation_id"]').val() || '';
        if (!variationId || variationId === '0') {
            setButtonEnabled(true);
            return;
        }

        var isAvailable = true;
        var isPurchasable = true;

        if (currentVariationData) {
            if (currentVariationData.is_in_stock !== undefined) {
                isAvailable = isTruthy(currentVariationData.is_in_stock);
            }
            if (currentVariationData.is_purchasable !== undefined) {
                isPurchasable = isTruthy(currentVariationData.is_purchasable);
            }
        } else {
            var $availability = $wooForm.find('.woocommerce-variation-availability');
            if ($availability.length) {
                var availabilityText = $availability.text().toLowerCase();
                if (availabilityText.indexOf('ناموجود') !== -1 ||
                    availabilityText.indexOf('out of stock') !== -1 ||
                    availabilityText.indexOf('موجود نیست') !== -1 ||
                    $availability.hasClass('out-of-stock')) {
                    isAvailable = false;
                }
            }

            var $addToCartBtn = $wooForm.find('button.single_add_to_cart_button');
            if ($addToCartBtn.length && $addToCartBtn.prop('disabled')) {
                isAvailable = false;
            }
        }

        if (isAvailable && isPurchasable) {
            setButtonEnabled(true);
            removeVariationError();
        } else {
            setButtonEnabled(false);
        }
    }

    // Improve reliability: listen to Woo events to keep a cached variation_id
    // Use document.body to catch events even if form is loaded dynamically
    $(document.body).on('found_variation', 'form.variations_form', function(event, variation) {
        var $form = $(this);
        var variationId = '';

        currentVariationData = variation || null;

        if (variation && variation.variation_id) {
            variationId = variation.variation_id;
        }

        var $variationInput = $form.find('input[name="variation_id"]');
        if ($variationInput.length && !$variationInput.val()) {
            $variationInput.val(variationId);
        }

        applyVariationState(variation);
        updateButtonState();
    });

    // Also listen to show_variation event (alternative WooCommerce event)
    $(document.body).on('show_variation', 'form.variations_form', function(event, variation) {
        currentVariationData = variation || null;
        applyVariationState(variation);
        updateButtonState();
    });

    // Listen to reset_data event
    $(document.body).on('reset_data', 'form.variations_form', function() {
        currentVariationData = null;
        setButtonEnabled(true);
        removeVariationError();
    });

    // Also monitor changes to variation_id input directly as a fallback
    $(document.body).on('change input', 'form.variations_form input[name="variation_id"]', function() {
        updateButtonState();
    });

    // Monitor attribute changes as well (when user selects variation attributes)
    $(document.body).on('change', 'form.variations_form select[name^="attribute_"], form.variations_form input[name^="attribute_"]', function() {
        currentVariationData = null;
        setTimeout(function() {
            updateButtonState();
        }, 100);
    });

    updateButtonState();
    
})(jQuery);
</script>



