<?php
/**
 * FoodOrd Product Modal Template
 *
 * This template is used to display product information in a modal popup.
 *
 * @package FoodOrd
 * @version 1.2
 */

if (!defined('ABSPATH')) {
	exit;
}


/**
 * Template for FoodOrd product modal display.
 *
 * @var WC_Product $product WooCommerce product object
 * @var array      $images  Product images array
 * @var array      $attributes Product attributes array
 */

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

$foodord_product_id = $product->get_id();
$foodord_product_name = $product->get_name();
$foodord_modal_context = isset($foodord_modal_context) ? sanitize_key((string) $foodord_modal_context) : '';
$foodord_is_reservation_preorder = 'reservation_preorder' === $foodord_modal_context;
$foodord_product_labels_html = class_exists('Foodord_Product_Labels') ? Foodord_Product_Labels::get_product_labels_html($foodord_product_id, 'modal') : '';

// Price HTML with "from" prefix support on variable products.
$foodord_product_price = $product->get_price_html();
if ($product->is_type('variable')) {
	$foodord_variation_prices = method_exists($product, 'get_variation_prices') ? $product->get_variation_prices() : array();
	$foodord_min_variation = null;
	$foodord_min_variation_id = 0;

	if (isset($foodord_variation_prices['price']) && is_array($foodord_variation_prices['price'])) {
		foreach ($foodord_variation_prices['price'] as $foodord_variation_id => $foodord_variation_price) {
			if ('' === $foodord_variation_price) {
				continue;
			}

			$foodord_variation_price_value = (float) $foodord_variation_price;
			if ($foodord_variation_price_value <= 0) {
				continue;
			}

			if (null === $foodord_min_variation || $foodord_variation_price_value < $foodord_min_variation) {
				$foodord_min_variation = $foodord_variation_price_value;
				$foodord_min_variation_id = (int) $foodord_variation_id;
			}
		}
	}

	if ($foodord_min_variation_id > 0) {
		$foodord_min_variation_product = wc_get_product($foodord_min_variation_id);
		if ($foodord_min_variation_product instanceof WC_Product) {
			$foodord_variation_price_html = $foodord_min_variation_product->get_price_html();
			if ('' !== $foodord_variation_price_html) {
				$foodord_product_price = '<span class="foodord-price-prefix">' . esc_html__('from: ', 'foodord') . '</span>' . $foodord_variation_price_html;
			}
		}
	}
}

$foodord_product_description = $product->get_short_description();
$foodord_product_url = $product->get_permalink();
$foodord_add_to_cart_url = wc_get_cart_url() . '?add-to-cart=' . $foodord_product_id;
$foodord_gallery_image_ids = $product->get_gallery_image_ids();
$foodord_main_image_id = $product->get_image_id();

// Prepare images array.
$foodord_all_images = array();

// Check for product-specific allergens first, then fall back to global allergy info.
$foodord_has_product_allergens = class_exists('Foodord_Product_Data_Allergens') ? Foodord_Product_Data_Allergens::has_product_allergens($foodord_product_id) : false;
$foodord_has_global_allergy = class_exists('Foodord_Allergy_Info') ? (Foodord_Allergy_Info::is_enabled() && Foodord_Allergy_Info::has_content()) : false;
$foodord_has_allergy_info = $foodord_has_product_allergens || $foodord_has_global_allergy;

if ($foodord_main_image_id) {
	$foodord_main_url = wp_get_attachment_image_url($foodord_main_image_id, 'large');
	$foodord_main_thumb = wp_get_attachment_image_url($foodord_main_image_id, 'thumbnail');
	if (!$foodord_main_thumb) {
		$foodord_main_thumb = $foodord_main_url;
	}
	$foodord_all_images[] = array(
		'id' => $foodord_main_image_id,
		'url' => $foodord_main_url,
		'thumb' => $foodord_main_thumb,
		'alt' => get_post_meta($foodord_main_image_id, '_wp_attachment_image_alt', true),
		'is_main' => true,
	);
}

foreach ($foodord_gallery_image_ids as $foodord_image_id) {
	$foodord_gallery_url = wp_get_attachment_image_url($foodord_image_id, 'large');
	$foodord_gallery_thumb = wp_get_attachment_image_url($foodord_image_id, 'thumbnail');
	if (!$foodord_gallery_thumb) {
		$foodord_gallery_thumb = $foodord_gallery_url;
	}
	$foodord_all_images[] = array(
		'id' => $foodord_image_id,
		'url' => $foodord_gallery_url,
		'thumb' => $foodord_gallery_thumb,
		'alt' => get_post_meta($foodord_image_id, '_wp_attachment_image_alt', true),
		'is_main' => false,
	);
}

// Get product stock status.
$foodord_stock_status = $product->get_stock_status();
$foodord_is_in_stock = $product->is_in_stock();

// Respect tweaks setting: show images?
$foodord_has_images = !empty($foodord_all_images);
$foodord_show_images = get_option('foodord_show_product_card_images', 'yes') === 'yes' && $foodord_has_images;
$foodord_modal_wrapper_classes = array('foodord-product-modal-wrapper');
if (!$foodord_show_images) {
	$foodord_modal_wrapper_classes[] = 'foodord-product-modal-wrapper--no-image';
}

$foodord_allowed_lazy_image_html = array(
	'img' => array(
		'id' => true,
		'class' => true,
		'src' => true,
		'alt' => true,
		'width' => true,
		'height' => true,
		'loading' => true,
		'decoding' => true,
		'data-foodord-lazy-src' => true,
		'data-foodord-lazy-srcset' => true,
		'data-foodord-lazy-sizes' => true,
	),
);
?>

<div class="<?php echo esc_attr(implode(' ', $foodord_modal_wrapper_classes)); ?>">
	<?php if ($foodord_show_images): ?>
		<div class="foodord-product-images">
			<!-- Main Product Image -->
			<div class="foodord-product-main-image foodord-product-main-image--loading">
				<span class="foodord-product-main-image__skeleton foodord-skeleton" aria-hidden="true"></span>
				<?php
				$foodord_main_alt = !empty($foodord_all_images[0]['alt']) ? $foodord_all_images[0]['alt'] : $foodord_product_name;
				echo wp_kses(
					foodord_get_lazy_image_html(
						array(
							'id' => 0,
							'src' => $foodord_all_images[0]['url'],
							'size' => 'large',
							'alt' => $foodord_main_alt,
							'class' => 'foodord-main-image',
							'loading' => 'eager',
							'attributes' => array(
								'id' => 'foodord-main-image',
							),
						)
					),
					$foodord_allowed_lazy_image_html
				);
				?>
			</div>

		<?php if (count($foodord_all_images) > 1): ?>
			<!-- Product Thumbnails -->
			<div class="foodord-product-thumbnails-shell" data-foodord-thumbnails-shell>
				<button type="button" class="foodord-product-thumbnails-arrow foodord-product-thumbnails-arrow--prev"
					data-foodord-thumbnail-scroll="prev"
					aria-label="<?php esc_attr_e('Previous product image', 'foodord'); ?>" hidden>
					<span aria-hidden="true">&lsaquo;</span>
				</button>

				<div class="foodord-product-thumbnails" data-foodord-thumbnails-track>
					<?php foreach ($foodord_all_images as $foodord_index => $foodord_image): ?>
						<div class="foodord-product-thumbnail <?php echo esc_attr(0 === $foodord_index ? 'active' : ''); ?>"
							data-image-url="<?php echo esc_url($foodord_image['url']); ?>"
							data-image-alt="<?php echo esc_attr(!empty($foodord_image['alt']) ? $foodord_image['alt'] : $foodord_product_name); ?>">
							<?php
							echo wp_kses(
								foodord_get_lazy_image_html(
									array(
										'id' => (int) $foodord_image['id'],
										'src' => $foodord_image['thumb'],
										'size' => 'thumbnail',
										'alt' => !empty($foodord_image['alt']) ? $foodord_image['alt'] : $foodord_product_name,
										'class' => 'foodord-product-thumbnail-image',
									)
								),
								$foodord_allowed_lazy_image_html
							);
							?>
						</div>
					<?php endforeach; ?>
				</div>

				<button type="button" class="foodord-product-thumbnails-arrow foodord-product-thumbnails-arrow--next"
					data-foodord-thumbnail-scroll="next"
					aria-label="<?php esc_attr_e('Next product image', 'foodord'); ?>" hidden>
					<span aria-hidden="true">&rsaquo;</span>
				</button>
			</div>
		<?php endif; ?>
		</div>
	<?php endif; ?>

	<div class="foodord-product-details">
		<!-- Product Title -->
		<div class="<?php echo esc_attr( 'foodord-product-title-row' . ( $foodord_is_reservation_preorder ? ' foodord-product-title-row--reservation-preorder' : '' ) ); ?>">
			<h2 class="foodord-product-title"><?php echo esc_html($foodord_product_name); ?></h2>
			<?php if ($foodord_has_allergy_info): ?>
				<button type="button" class="foodord-allergy-trigger"
					aria-label="<?php esc_attr_e('Open Allergy Info', 'foodord'); ?>" data-allergy-trigger="true"
					data-product-id="<?php echo esc_attr($foodord_product_id); ?>"
					data-has-product-allergens="<?php echo esc_attr($foodord_has_product_allergens ? '1' : '0'); ?>">
					<span class="foodord-allergy-trigger__icon" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none"
							stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
							<circle cx="12" cy="12" r="10"></circle>
							<line x1="12" y1="16" x2="12" y2="12"></line>
							<line x1="12" y1="8" x2="12.01" y2="8"></line>
						</svg></span>
				</button>
			<?php endif; ?>
		</div>

		<!-- Product Price -->
		<div class="foodord-product-price">
			<?php
			$foodord_allowed_price_html = array(
				'span' => array(
					'class' => array(),
				),
				'bdi' => array(),
				'del' => array(
					'aria-hidden' => array(),
					'class' => array(),
				),
				'ins' => array(
					'aria-hidden' => array(),
					'class' => array(),
				),
				'button' => array(
					'type' => array(),
					'class' => array(),
					'aria-label' => array(),
					'data-foodord-open-campaigns' => array(),
				),
			);
			echo wp_kses($foodord_product_price, $foodord_allowed_price_html);
			?>
		</div>
		<?php
		if ('' !== $foodord_product_labels_html && class_exists('Foodord_Product_Labels')) {
			echo wp_kses($foodord_product_labels_html, Foodord_Product_Labels::get_allowed_html());
		}
		?>

		<!-- Product Description -->
		<?php if (!empty($foodord_product_description)): ?>
			<div class="foodord-product-description">
				<?php echo wp_kses_post($foodord_product_description); ?>
			</div>
		<?php endif; ?>

		<?php if ($product->is_type('variable')): ?>
			<!-- Variable Product: WooCommerce Variation Form -->
			<div class="foodord-product-purchase">
				<?php
				// Render the native WooCommerce variation form inside the modal.
				// Ensure WooCommerce template has expected global context without breaking local $product.
				// Setup WooCommerce product data for template context without violating coding standards.
				$foodord_prev_global_product = isset($GLOBALS['product']) ? $GLOBALS['product'] : null;
				wc_setup_product_data($foodord_product_id);
				// Previous global $post not required when using wc_setup_product_data().
			
				// Temporarily remove dynamic variation price output (second price) via PHP hooks.
				$foodord_removed_single_variation_hook = false;
				if (has_action('woocommerce_single_variation', 'woocommerce_single_variation')) {
					remove_action('woocommerce_single_variation', 'woocommerce_single_variation', 10);
					$foodord_removed_single_variation_hook = true;
				}

				wc_get_template(
					'single-product/add-to-cart/variable.php',
					array(
						'available_variations' => $product->get_available_variations(),
						'attributes' => $product->get_variation_attributes(),
						'selected_attributes' => $product->get_default_attributes(),
					)
				);

				// Re-add hook after rendering to avoid global side effects.
				if ($foodord_removed_single_variation_hook) {
					add_action('woocommerce_single_variation', 'woocommerce_single_variation', 10);
				}

				// Restore previous product global without directly assigning globals to satisfy coding standards.
				if ($foodord_prev_global_product instanceof WC_Product) {
					wc_setup_product_data($foodord_prev_global_product->get_id());
				} else {
					unset($GLOBALS['product']);
				}
				?>
			</div>
		<?php endif; ?>

		<?php
		$foodord_toppings_partial = FOODORD_DIR . 'templates/frontend/product-modal-toppings.php';
		if (!empty($foodord_topping_sets) && file_exists($foodord_toppings_partial)) {
			include $foodord_toppings_partial;
		}

		$foodord_upsells_partial = FOODORD_DIR . 'templates/frontend/product-modal-upsells.php';
		if ( ! empty( $foodord_modal_upsells ) && file_exists( $foodord_upsells_partial ) ) {
			include $foodord_upsells_partial;
		}
		?>


	</div>
</div>

<!-- Modal Footer with Actions -->
<div class="foodord-modal-footer">
	<div class="foodord-product-actions">
		<?php if ($foodord_is_in_stock && $product->is_purchasable()): ?>
			<!-- Quantity Controls -->
			<div class="foodord-quantity-controls">
				<button type="button" class="foodord-quantity-btn" id="foodord-quantity-minus"
					aria-label="<?php esc_attr_e('Decrease quantity', 'foodord'); ?>">
					−
				</button>
				<input type="number" id="foodord-quantity-input" class="foodord-quantity-input" value="1" min="1" max="99"
					aria-label="<?php esc_attr_e('Quantity', 'foodord'); ?>">
				<button type="button" class="foodord-quantity-btn" id="foodord-quantity-plus"
					aria-label="<?php esc_attr_e('Increase quantity', 'foodord'); ?>">
					+
				</button>
			</div>



			<?php
			// Determine a numeric unit price for dynamic total calculation.
			$foodord_unit_price = 0;
			if ($product->is_type('variable')) {
				// For variable products, start at zero until a variation is chosen.
				$foodord_unit_price = 0.0;
			} else {
				$foodord_unit_price = (float) wc_get_price_to_display($product);
			}
			?>

			<!-- Add to Cart Button (with dynamic quantity and total like card CTA) -->
			<button type="button" class="foodord-add-to-cart-btn"
				data-product-id="<?php echo esc_attr((string) (int) $foodord_product_id); ?>"
				data-foodord-product-context="<?php echo esc_attr($foodord_modal_context); ?>"
				data-unit-price="<?php echo esc_attr((string) $foodord_unit_price); ?>"
				data-unit-price-initial="<?php echo esc_attr((string) $foodord_unit_price); ?>" data-toppings-extra="0"
				aria-live="polite">
				<span class="foodord-add-to-cart-left">
					<span class="foodord-add-to-cart-count">1</span>
					<span class="foodord-add-to-cart-label"><?php echo esc_html($foodord_is_reservation_preorder ? __('Add to pre-order', 'foodord') : __('Add to Cart', 'foodord')); ?></span>
				</span>
				<span class="foodord-add-to-cart-total"></span>
			</button>
		<?php endif; ?>
	</div>
</div>
