<?php
/**
 * Quickview Feature for Product Display.
 *
 * @package Product_Display.
 */

// Exit if accessed directly.
if ( ! defined('ABSPATH') ) {
	exit;
}

/**
 * Class PRODDISP_Compare.
 *
 * This class handles the compare functionality for product display.
 */
class PRODDISP_Quickview {
	/**
	 * The single instance of the class.
	 */
	protected static $_instance = null;

	/**
	 * Main Instance.
	 */
	public static function get_instance() {
		if ( is_null(self::$_instance) ) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action('wp_ajax_proddisp_quickview', array( $this, 'load_quickview' ));
		add_action('wp_ajax_nopriv_proddisp_quickview', array( $this, 'load_quickview' ));
	}

	/**
	 * Load quickview content via AJAX.
	 */
	public function load_quickview() {
		check_ajax_referer('wcps-nonce', 'nonce');

		$product_id = isset($_POST['product_id']) ? absint($_POST['product_id']) : 0;

		if ( ! $product_id ) {
			wp_send_json_error(array( 'message' => __('Invalid product ID', 'product-display') ));
		}

		global $post, $product;

		$post = get_post($product_id);
		setup_postdata($post);
		$product = wc_get_product($product_id);

		ob_start();
		$this->quickview_template($product);
		$html = ob_get_clean();

		wp_reset_postdata();

		wp_send_json_success(array( 'html' => $html ));
	}

	/**
	 * Build custom image gallery HTML (no WC lightbox, no WC JS init).
	 *
	 * @param WC_Product $product Product object.
	 */
	private function render_gallery( $product ) {
		$main_image_id    = $product->get_image_id();
		$gallery_ids      = $product->get_gallery_image_ids();
		$all_image_ids    = array_merge( array( $main_image_id ), $gallery_ids );
		$all_image_ids    = array_filter( $all_image_ids );

		if ( empty( $all_image_ids ) ) {
			echo wc_placeholder_img( 'woocommerce_single' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			return;
		}

		$first_id  = reset( $all_image_ids );
		$first_src = wp_get_attachment_image_src( $first_id, 'woocommerce_single' );
		$first_url = $first_src ? esc_url( $first_src[0] ) : '';
		$first_alt = esc_attr( get_post_meta( $first_id, '_wp_attachment_image_alt', true ) ?: $product->get_name() );

		// Build JSON image list for the lightbox.
		$lightbox_images = array();
		foreach ( $all_image_ids as $img_id ) {
			$full = wp_get_attachment_image_src( $img_id, 'full' );
			if ( ! $full ) continue;
			$lightbox_images[] = array(
				'src' => esc_url( $full[0] ),
				'alt' => esc_attr( get_post_meta( $img_id, '_wp_attachment_image_alt', true ) ?: $product->get_name() ),
			);
		}
		$lightbox_json = wp_json_encode( $lightbox_images );
		?>
		<div class="wcps-qv-gallery" data-current="0" data-lightbox="<?php echo esc_attr( $lightbox_json ); ?>">
			<div class="wcps-qv-main-wrap">
				<button class="wcps-qv-nav wcps-qv-prev" aria-label="<?php esc_attr_e( 'Previous image', 'product-display' ); ?>">&#8249;</button>
				<div class="wcps-qv-main-image">
					<img src="<?php echo esc_url( $first_url ); ?>" alt="<?php echo esc_attr( $first_alt ); ?>" class="wcps-qv-active-img" />
				</div>
				<button class="wcps-qv-nav wcps-qv-next" aria-label="<?php esc_attr_e( 'Next image', 'product-display' ); ?>">&#8250;</button>
				
			</div>
			<?php if ( count( $all_image_ids ) > 1 ) : ?>
			<div class="wcps-qv-thumbs">
				<?php foreach ( $all_image_ids as $index => $img_id ) :
					$thumb_src = wp_get_attachment_image_src( $img_id, 'thumbnail' );
					$full_src  = wp_get_attachment_image_src( $img_id, 'woocommerce_single' );
					if ( ! $thumb_src || ! $full_src ) continue;
					$alt = esc_attr( get_post_meta( $img_id, '_wp_attachment_image_alt', true ) ?: $product->get_name() );
				?>
					<button class="wcps-qv-thumb <?php echo 0 === $index ? 'wcps-qv-thumb-active' : ''; ?>"
						data-index="<?php echo esc_attr( $index ); ?>"
						data-full="<?php echo esc_url( $full_src[0] ); ?>"
						data-alt="<?php echo esc_attr( $alt ); ?>"
						aria-label="<?php echo esc_attr( sprintf( __( 'View image %d', 'product-display' ), $index + 1 ) ); ?>">
						<img src="<?php echo esc_url( $thumb_src[0] ); ?>" alt="<?php echo esc_attr( $alt ); ?>" loading="lazy" />
					</button>
				<?php endforeach; ?>
			</div>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Quickview template.
	 *
	 * @param WC_Product $product Product object.
	 */
	private function quickview_template( $product ) {
		$product_type = $product->get_type();
		?>
		<div class="wcps-quickview-content woocommerce">
			<div id="product-<?php echo esc_attr( $product->get_id() ); ?>" <?php wc_product_class( '', $product ); ?>>
				<div class="wcps-quickview-wrapper">

					<!-- Gallery -->
					<div class="wcps-quickview-images">
						<?php $this->render_gallery( $product ); ?>
					</div>

					<!-- Summary -->
					<div class="wcps-quickview-summary">

						<?php /* Title */ ?>
						<h2 class="wcps-qv-title product_title">
							<a href="<?php echo esc_url( $product->get_permalink() ); ?>"><?php echo esc_html( $product->get_name() ); ?></a>
						</h2>

						<?php /* Rating */ ?>
						<?php if ( wc_review_ratings_enabled() ) : ?>
						<div class="wcps-qv-rating">
							<?php
							$rating_count = $product->get_rating_count();
							$average      = $product->get_average_rating();
							echo wp_kses_post( wc_get_rating_html( $average, $rating_count ) );
							if ( $rating_count > 0 ) {
								echo '<span class="wcps-qv-review-count">(' . esc_html( $rating_count ) . ' ' . esc_html( _n( 'review', 'reviews', $rating_count, 'product-display' ) ) . ')</span>';
							}
							?>
						</div>
						<?php endif; ?>

						<?php /* Price */ ?>
						<div class="wcps-qv-price price">
							<?php echo wp_kses_post( $product->get_price_html() ); ?>
						</div>

						<?php /* Stock */ ?>
						<?php
						$stock_status = $product->get_stock_status();
						$stock_qty    = $product->get_stock_quantity();
						$manage_stock = $product->managing_stock();
						?>
						<div class="wcps-qv-stock wcps-qv-stock-<?php echo esc_attr( $stock_status ); ?>">
							<?php if ( 'instock' === $stock_status ) : ?>
								<span class="wcps-qv-stock-icon">&#10003;</span>
								<?php if ( $manage_stock && null !== $stock_qty ) : ?>
									<span><?php echo esc_html( sprintf( __( 'In Stock (%d available)', 'product-display' ), $stock_qty ) ); ?></span>
								<?php else : ?>
									<span><?php esc_html_e( 'In Stock', 'product-display' ); ?></span>
								<?php endif; ?>
							<?php elseif ( 'onbackorder' === $stock_status ) : ?>
								<span class="wcps-qv-stock-icon">&#9676;</span>
								<span><?php esc_html_e( 'Available on backorder', 'product-display' ); ?></span>
							<?php else : ?>
								<span class="wcps-qv-stock-icon">&#10007;</span>
								<span><?php esc_html_e( 'Out of Stock', 'product-display' ); ?></span>
							<?php endif; ?>
						</div>

						<?php /* Short description */ ?>
						<?php if ( $product->get_short_description() ) : ?>
						<div class="wcps-qv-description woocommerce-product-details__short-description">
							<?php echo wpautop( wp_kses_post( $product->get_short_description() ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
						</div>
						<?php endif; ?>

						<?php /* Add to cart form — uses WC native template (handles simple + variable) */ ?>
						<div class="wcps-qv-add-to-cart">
							<?php woocommerce_template_single_add_to_cart(); ?>
						</div>

						<?php /* Meta: SKU, categories, tags */ ?>
						<div class="wcps-qv-meta product_meta">
							<?php if ( wc_product_sku_enabled() && ( $product->get_sku() || $product->is_type( 'variable' ) ) ) : ?>
							<div class="wcps-qv-meta-row">
								<span class="wcps-qv-meta-label"><?php esc_html_e( 'SKU:', 'product-display' ); ?></span>
								<span class="wcps-qv-meta-value sku"><?php echo esc_html( $product->get_sku() ? $product->get_sku() : __( 'N/A', 'product-display' ) ); ?></span>
							</div>
							<?php endif; ?>

							<?php $categories = wc_get_product_category_list( $product->get_id(), ', ' ); ?>
							<?php if ( $categories ) : ?>
							<div class="wcps-qv-meta-row">
								<span class="wcps-qv-meta-label"><?php esc_html_e( 'Category:', 'product-display' ); ?></span>
								<span class="wcps-qv-meta-value"><?php echo wp_kses_post( $categories ); ?></span>
							</div>
							<?php endif; ?>

							<?php $tags = wc_get_product_tag_list( $product->get_id(), ', ' ); ?>
							<?php if ( $tags ) : ?>
							<div class="wcps-qv-meta-row">
								<span class="wcps-qv-meta-label"><?php esc_html_e( 'Tags:', 'product-display' ); ?></span>
								<span class="wcps-qv-meta-value"><?php echo wp_kses_post( $tags ); ?></span>
							</div>
							<?php endif; ?>
						</div>

						<a href="<?php echo esc_url( $product->get_permalink() ); ?>" class="wcps-qv-view-full">
							<?php esc_html_e( 'View full details', 'product-display' ); ?> &#8594;
						</a>

					</div><!-- .wcps-quickview-summary -->
				</div><!-- .wcps-quickview-wrapper -->
			</div>
		</div>
		<?php
	}
}

// Initialize the class.
function proddisp_quickview() {
	return PRODDISP_Quickview::get_instance();
}

// Start the quickview functionality.
proddisp_quickview();
