<?php
// If this file is called directly, abort.
if (! defined('ABSPATH')) {
    exit;
}

/**
 * Main render entry point for the Add to Cart widget.
 *
 * @param \GGM_Commerce_Base_Widget $widget The widget instance.
 */
function ggmc_add_to_cart_render( $widget ) {
    // Get product data (includes preview product support)
    $product_data = $widget->get_product_data();

    if (!$product_data) {
        if (ggmc_is_editor_mode()) {
            echo '<p style="color: var(--ggmc-text-light, #6b7280); font-style: italic; font-family: var(--ggmc-font-family, \'Poppins\', sans-serif);">Add to Cart button will appear here when product is selected.</p>';
        }
        return;
    }

    $settings = $widget->get_settings_for_display();
    $button_text = !empty($settings['button_text']) ? $settings['button_text'] : 'Add to Cart';
    $variable_button_text = !empty($settings['variable_button_text']) ? $settings['variable_button_text'] : 'Select Options';
    $variable_behavior = !empty($settings['variable_product_behavior']) ? $settings['variable_product_behavior'] : 'link_to_product';
    $show_quantity = $settings['show_quantity'] === 'yes';
    $show_price = isset($settings['show_price']) && $settings['show_price'] === 'yes';
    $quantity_label = !empty($settings['quantity_label']) ? $settings['quantity_label'] : 'Quantity:';
    $quantity_controls_style = $settings['quantity_controls_style'] ?? 'both';
    $layout = $settings['layout'];

    // Check if product has variations
    $has_variations = !empty($product_data->has_variations) && $product_data->has_variations;

    // Determine button state and text
    $is_variable_product = $has_variations;

    // Build wrapper class
    $wrapper_class = 'ggmc-add-to-cart-wrapper ' . $layout;
    if ($is_variable_product) {
        $wrapper_class .= ' has-variations';
    }

    // Build button attributes
    $button_attrs = array(
        'type' => 'button',
        'class' => 'ggmc-add-to-cart-btn',
        'data-product-id' => $product_data->id,
        'data-quantity-selector' => '.ggmc-quantity-input',
        'data-has-variations' => $is_variable_product ? '1' : '0',
        'data-variable-behavior' => $variable_behavior,
        'data-add-text' => $button_text,
        'data-variable-text' => $variable_button_text,
    );

    // Get product URL for link_to_product behavior
    if ($is_variable_product && $variable_behavior === 'link_to_product') {
        $product_url = GGM_Commerce_Helpers::get_product_details_url($product_data->id);
        $button_attrs['data-product-url'] = $product_url;
    }

    // Determine initial button text
    $display_button_text = $is_variable_product ? $variable_button_text : $button_text;

    // If disabled behavior and has variations, disable the button initially
    if ($is_variable_product && $variable_behavior === 'disabled') {
        $button_attrs['disabled'] = 'disabled';
    }

    ?>
    <div class="<?php echo esc_attr($wrapper_class); ?>">
        <?php if ($show_price) : ?>
            <?php // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- ggmc_add_to_cart_render_price_display() returns pre-escaped HTML ?>
            <?php echo ggmc_add_to_cart_render_price_display($product_data, $settings); ?>
        <?php endif; ?>

        <?php if ($show_quantity) : ?>
            <div class="ggmc-quantity-wrapper">
                <label class="ggmc-quantity-label"><?php echo esc_html($quantity_label); ?></label>
                <div class="ggmc-quantity-controls <?php echo esc_attr($quantity_controls_style); ?>">
                    <?php if ($quantity_controls_style === 'both') : ?>
                        <button type="button" class="ggmc-qty-minus">-</button>
                    <?php endif; ?>
                    <input type="number" class="ggmc-quantity-input" value="1" min="1" max="999" />
                    <?php if ($quantity_controls_style === 'both') : ?>
                        <button type="button" class="ggmc-qty-plus">+</button>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>

        <?php
        // Hidden inputs for variation data (updated by VariationSelector)
        if ($is_variable_product) : ?>
            <input type="hidden" class="ggmc-selected-variation-id" name="variation_id" value="" />
            <input type="hidden" class="ggmc-selected-variation-data" name="variation_data" value="" />
        <?php endif; ?>

        <button <?php
            foreach ($button_attrs as $attr => $value) {
                echo esc_attr($attr) . '="' . esc_attr($value) . '" ';
            }
        ?>>
            <?php echo esc_html($display_button_text); ?>
        </button>
    </div>
    <?php
}

/**
 * Render the price display element.
 *
 * @param object $product_data Product data object.
 * @param array  $settings     Widget settings.
 * @return string Price HTML.
 */
function ggmc_add_to_cart_render_price_display( $product_data, $settings ) {
    $tax = ggm_commerce_tax();
    $product_id = isset($product_data->id) ? (int) $product_data->id : 0;
    $has_variations = !empty($product_data->has_variations) && $product_data->has_variations;

    // Get currency info for JS-side formatting
    $currency_options = get_option('ggm_commerce_currency_options', array());
    $currency_symbol = isset($currency_options['symbol']) ? $currency_options['symbol'] : '£';
    $currency_position = isset($currency_options['position']) ? $currency_options['position'] : 'before';

    // Get tax suffix
    $suffix = '';
    if ($tax->should_show_suffix()) {
        $suffix = ' <span class="ggmc-tax-suffix">' . esc_html($tax->get_suffix_text()) . '</span>';
    }

    // Build the price HTML
    $price_html = '';

    if ($has_variations) {
        // Variable product: show "From $X" using lowest variation price
        $price_range = ggmc_add_to_cart_get_variation_price_range($product_id);

        if ($price_range && $price_range['min'] !== null) {
            $min_display = $tax->get_product_display_price($price_range['min'], $product_id);
            $prefix_text = !empty($settings['price_prefix_text']) ? $settings['price_prefix_text'] : 'From';
            $price_html = '<span class="price-from-label">' . esc_html($prefix_text) . '</span> ' .
                          '<span class="current-price">' . esc_html($tax->format_price($min_display['price'])) . '</span>' . $suffix;
        } else {
            // Fallback to base product price
            $display_price = $tax->get_product_display_price($product_data->price, $product_id);
            $prefix_text = !empty($settings['price_prefix_text']) ? $settings['price_prefix_text'] : 'From';
            $price_html = '<span class="price-from-label">' . esc_html($prefix_text) . '</span> ' .
                          '<span class="current-price">' . esc_html($tax->format_price($display_price['price'])) . '</span>' . $suffix;
        }
    } else {
        // Simple product: show regular or sale price
        $regular_display = $tax->get_product_display_price($product_data->price, $product_id);

        if (empty($product_data->sale_price) || $product_data->sale_price >= $product_data->price) {
            $price_html = '<span class="current-price">' . esc_html($tax->format_price($regular_display['price'])) . '</span>' . $suffix;
        } else {
            $sale_display = $tax->get_product_display_price($product_data->sale_price, $product_id);
            $price_html = '<span class="sale-price">' . esc_html($tax->format_price($sale_display['price'])) . '</span>' . $suffix . ' ' .
                          '<span class="original-price">' . esc_html($tax->format_price($regular_display['price'])) . '</span>';
        }
    }

    // Wrap in container with data attributes for JS updates
    return '<div class="ggmc-cart-price" data-product-id="' . esc_attr($product_id) . '" ' .
           'data-currency-symbol="' . esc_attr($currency_symbol) . '" ' .
           'data-currency-position="' . esc_attr($currency_position) . '" ' .
           'data-original-html="' . esc_attr($price_html) . '">' .
           $price_html . '</div>';
}

/**
 * Get price range for products with variations.
 *
 * @param int $product_id Product ID.
 * @return array|null Array with min, max, has_range or null if no variations.
 */
function ggmc_add_to_cart_get_variation_price_range( $product_id ) {
    if (!class_exists('GGM_Commerce_License') || !GGM_Commerce_License::instance()->is_widget_activated('product-variations')) {
        return null;
    }

    $variations_manager = GGM_Commerce_Variations::instance();

    if (!$variations_manager->product_has_variations($product_id)) {
        return null;
    }

    return $variations_manager->get_display_price_range($product_id);
}
