<?php
/**
 * Compare 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_Compare {
	/**
	 * 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_add_to_compare', array( $this, 'add_to_compare' ));
		add_action('wp_ajax_nopriv_proddisp_add_to_compare', array( $this, 'add_to_compare' ));
		add_action('wp_ajax_proddisp_remove_from_compare', array( $this, 'remove_from_compare' ));
		add_action('wp_ajax_nopriv_proddisp_remove_from_compare', array( $this, 'remove_from_compare' ));
		add_action('wp_ajax_proddisp_get_compare_table', array( $this, 'get_compare_table' ));
		add_action('wp_ajax_nopriv_proddisp_get_compare_table', array( $this, 'get_compare_table' ));

		add_action('wp_ajax_proddisp_toggle_compare', array( $this, 'toggle_compare' ));
		add_action('wp_ajax_nopriv_proddisp_toggle_compare', array( $this, 'toggle_compare' ));
		add_action('wp_ajax_proddisp_clear_compare', array( $this, 'clear_compare' ));
		add_action('wp_ajax_nopriv_proddisp_clear_compare', array( $this, 'clear_compare' ));
		
		// Enhanced AJAX handlers for compare modal
		add_action('wp_ajax_proddisp_compare_add_to_cart', array( $this, 'ajax_add_to_cart' ));
		add_action('wp_ajax_nopriv_proddisp_compare_add_to_cart', array( $this, 'ajax_add_to_cart' ));
		
		// Ensure assets are loaded when compare functionality is used
		add_action('wp_enqueue_scripts', array( $this, 'maybe_enqueue_assets' ));
	}

	/**
	 * Maybe enqueue assets if compare functionality might be used.
	 */
	public function maybe_enqueue_assets() {
		// Only load on frontend
		if ( is_admin() ) {
			return;
		}

		// Only load if compare items exist (user has products in compare)
		// This is more efficient than loading on all shop/product pages
		if ( ! empty( $this->get_compare_items() ) ) {
			// Ensure FontAwesome and feature assets are loaded
			PRODDISP_Assets::get_instance()->enqueue_feature_assets();
		}
	}


	/**
	 * Render the compare button for a product.
	 *
	 * @param Product_Display $product Product object.
	 * @return string HTML for the compare button.
	 */
	public function render_compare_button( $product ) {
		$product_id = $product->get_id();
		$in_compare = $this->is_in_compare($product_id);

		// Update class to match JS selector (.wcps-compare instead of .wcps-compare-button).
		$button_class = $in_compare ? 'wcps-compare in-compare' : 'wcps-compare';
		$button_text = $in_compare ? __('Remove Compare', 'product-display') : __('Compare', 'product-display');

		// Update data attribute to use hyphen instead of underscore (data-product-id vs data-product_id).
		$output = '<a href="#" class="' . esc_attr($button_class) . '" data-product-id="' . esc_attr($product_id) . '">';
		$output .= '<span class="wcps-icon wcps-icon-compare"></span>';
		$output .= '<span class="wcps-button-text">' . esc_html($button_text) . '</span>';
		$output .= '</a>';

		return $output;
	}

	/**
	 * Check if a product is in compare list.
	 *
	 * @param int $product_id Product ID.
	 * @return bool True if in compare list.
	 */
	public function is_in_compare( $product_id ) {
		$compare_items = $this->get_compare_items();
		return in_array($product_id, $compare_items);
	}

	/**
	 * Get compare items from cookie.
	 *
	 * @return array Array of product IDs.
	 */
	public function get_compare_items() {
		$compare_items = array();

		if ( isset($_COOKIE['proddisp_compare_items']) ) {
			$compare_items = explode(',', sanitize_text_field(wp_unslash($_COOKIE['proddisp_compare_items'])));
			$compare_items = array_map('absint', $compare_items);
			$compare_items = array_filter($compare_items);
		}

		return $compare_items;
	}

	/**
	 * Add product to compare list via AJAX.
	 */
	public function add_to_compare() {
		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') ));
		}

		$compare_items = $this->get_compare_items();

		if ( ! in_array($product_id, $compare_items) ) {
			$compare_items[] = $product_id;

			// Limit to 4 products.
			if ( count($compare_items) > 4 ) {
				array_shift($compare_items);
			}

			$this->set_compare_cookie($compare_items);
		}

		wp_send_json_success(array(
			'message' => __('Product added to compare', 'product-display'),
			'count' => count($compare_items),
			'products' => $this->get_compare_products_data($compare_items),
		));
	}

	 /**
	  * Toggle product in compare list (add or remove).
	  * This is needed for the JS functionality.
	  */
	public function toggle_compare() {
		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') ));
		}

		$compare_items = $this->get_compare_items();
		$in_compare = in_array($product_id, $compare_items);

		if ( $in_compare ) {
			// Remove from compare.
			$compare_items = array_diff($compare_items, array( $product_id ));
			$message = __('Product removed from compare', 'product-display');
		} else {
			// Add to compare.
			$compare_items[] = $product_id;

			// Limit to 4 products.
			if ( count($compare_items) > 4 ) {
				array_shift($compare_items);
			}

			$message = __('Product added to compare', 'product-display');
		}

		$this->set_compare_cookie($compare_items);

		wp_send_json_success(array(
			'message' => $message,
			'count' => count($compare_items),
			'in_compare' => ! $in_compare,
			'products' => $this->get_compare_products_data($compare_items),
		));
	}

	/**
	 * Clear all compare items.
	 */
	public function clear_compare() {
		check_ajax_referer('wcps-nonce', 'nonce');

		$this->set_compare_cookie(array());

		wp_send_json_success(array(
			'message' => __('Compare list cleared', 'product-display'),
			'count' => 0,
		));
	}

	/**
	 * Remove product from compare list via AJAX.
	 */
	public function remove_from_compare() {
		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') ));
		}

		$compare_items = $this->get_compare_items();

		if ( in_array($product_id, $compare_items) ) {
			$compare_items = array_diff($compare_items, array( $product_id ));
			$this->set_compare_cookie($compare_items);
		}

		wp_send_json_success(array(
			'message' => __('Product removed from compare', 'product-display'),
			'count' => count($compare_items),
			'products' => $this->get_compare_products_data($compare_items),
		));
	}

	/**
	 * Get product data for compare bar.
	 */
	public function get_compare_products_data( $product_ids ) {
		$products = array();

		foreach ( $product_ids as $product_id ) {
			$product = wc_get_product($product_id);

			if ( $product ) {
				$products[] = array(
					'id' => $product_id,
					'name' => $product->get_name(),
					'image' => wp_get_attachment_image_url($product->get_image_id(), 'thumbnail') ?: wc_placeholder_img_src('thumbnail'),
				);
			}
		}

		return $products;
	}

	/**
	 * Set compare cookie.
	 *
	 * @param array $items Array of product IDs.
	 */
	private function set_compare_cookie( $items ) {
		$items = array_map('absint', $items);
		$items = array_filter($items);

		setcookie(
			'proddisp_compare_items',
			implode(',', $items),
			time() + ( 86400 * 30 ), // 30 days.
			COOKIEPATH,
			COOKIE_DOMAIN,
			is_ssl(),
			true
		);

		// Also set the cookie in $_COOKIE for immediate use.
		$_COOKIE['proddisp_compare_items'] = implode(',', $items);
	}

	/**
	 * Get compare table via AJAX.
	 */
	public function get_compare_table() {
		check_ajax_referer('wcps-nonce', 'nonce');

		$compare_items = $this->get_compare_items();

		ob_start();
		$this->render_compare_table($compare_items);
		$table_html = ob_get_clean();

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

	/**
	 * Render the compare table.
	 *
	 * @param array $product_ids Array of product IDs.
	 */
	public function render_compare_table( $product_ids ) {
		if ( empty( $product_ids ) ) {
			echo '<div style="padding:48px;text-align:center;color:#6b7280;">';
			echo '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" style="width:48px;height:48px;margin:0 auto 12px;display:block;opacity:.3;">';
			echo '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M8 7h12M8 12h12M8 17h12M3 7h.01M3 12h.01M3 17h.01"/>';
			echo '</svg>';
			echo '<p style="font-size:15px;font-weight:500;">' . esc_html__( 'No products added to compare', 'product-display' ) . '</p>';
			echo '</div>';
			return;
		}

		$products = array();
		foreach ( $product_ids as $product_id ) {
			$product = wc_get_product($product_id);
			if ( $product ) {
				$products[] = $product;
			}
		}

		if ( empty( $products ) ) {
			echo '<p style="padding:30px;text-align:center;">' . esc_html__( 'No valid products to compare', 'product-display' ) . '</p>';
			return;
		}

		$icon_cart   = '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2 9m5-9v9m4-9v9m5-9l2 9"/></svg>';
		$icon_heart  = '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"/></svg>';
		
		?>
		<table class="wcps-compare-table">
			<thead>
				<tr>
					<th><?php esc_html_e('Product', 'product-display'); ?></th>
					<?php foreach ( $products as $product ) { ?>
						<th>
							<a href="<?php echo esc_url(get_permalink($product->get_id())); ?>" class="wcps-compare-product-title">
								<?php echo esc_html($product->get_name()); ?>
							</a>
							<a href="#" class="wcps-compare-remove" data-product-id="<?php echo esc_attr($product->get_id()); ?>">
								<span class="wcps-icon wcps-icon-close"></span>
							</a>
						</th>
					<?php } ?>
				</tr>
			</thead>
			<tbody>

				<!-- Image -->
				<tr>
					<td><?php esc_html_e( 'Image', 'product-display' ); ?></td>
					<?php foreach ( $products as $product ) :
						$full_src = wp_get_attachment_image_url( $product->get_image_id(), 'full' ) ?: wc_placeholder_img_src();
						$thumb_src = wp_get_attachment_image_url( $product->get_image_id(), 'woocommerce_single' ) ?: wc_placeholder_img_src();
					?>
						<td>
							<img class="wcps-compare-product-img wcps-compare-img-lightbox"
								 src="<?php echo esc_url( $thumb_src ); ?>"
								 alt="<?php echo esc_attr( $product->get_name() ); ?>"
								 data-full="<?php echo esc_url( $full_src ); ?>"
								 style="cursor:zoom-in;">
						</td>
					<?php endforeach; ?>
				</tr>

				<!-- Price -->
				<tr>
					<td><?php esc_html_e( 'Price', 'product-display' ); ?></td>
					<?php foreach ( $products as $product ) : ?>
						<td><?php echo wp_kses_post( $product->get_price_html() ); ?></td>
					<?php endforeach; ?>
				</tr>

				<!-- Availability -->
				<tr>
					<td><?php esc_html_e( 'Availability', 'product-display' ); ?></td>
					<?php foreach ( $products as $product ) : ?>
						<td>
							<?php if ( $product->is_in_stock() ) : ?>
								<span class="wcps-badge wcps-badge-in-stock">
									<?php esc_html_e( 'In Stock', 'product-display' ); ?>
								</span>
							<?php else : ?>
								<span class="wcps-badge wcps-badge-out-stock">
									<?php esc_html_e( 'Out of Stock', 'product-display' ); ?>
								</span>
							<?php endif; ?>
						</td>
					<?php endforeach; ?>
				</tr>

				<!-- Rating -->
				<tr>
					<td><?php esc_html_e( 'Rating', 'product-display' ); ?></td>
					<?php foreach ( $products as $product ) : ?>
						<td>
							<?php
							$rating = $product->get_average_rating();
							$count  = $product->get_review_count();
							if ( $rating > 0 ) {
								echo wp_kses_post( wc_get_rating_html( $rating ) );
								echo '<span style="font-size:12px;color:#9ca3af;margin-left:4px;">(' . absint( $count ) . ')</span>';
							} else {
								echo '<span style="color:#d1d5db;">&mdash;</span>';
							}
							?>
						</td>
					<?php endforeach; ?>
				</tr>

				<!-- Actions -->
				<tr>
					<td><?php esc_html_e( 'Actions', 'product-display' ); ?></td>
					<?php foreach ( $products as $product ) : ?>
						<td>
							<div class="wcps-compare-actions">
								<!-- Add to Cart -->
								<button type="button"
										class="button wcps-ajax-add-to-cart"
										data-product-id="<?php echo esc_attr( $product->get_id() ); ?>"
										<?php echo ( $product->is_purchasable() && $product->is_in_stock() ) ? '' : 'disabled'; ?>>
									<?php echo wp_kses_post( $icon_cart ); ?>
									<span class="wcps-button-text"><?php echo esc_html( $product->add_to_cart_text() ); ?></span>
								</button>

								<!-- Wishlist -->
								<?php if ( class_exists( 'PRODDISP_Wishlist' ) ) : ?>
									<?php
									$wishlist    = PRODDISP_Wishlist::get_instance();
									$in_wishlist = $wishlist->is_in_wishlist( $product->get_id() );
									$wl_class    = $in_wishlist ? 'wcps-compare-wishlist in-wishlist' : 'wcps-compare-wishlist';
									$wl_text     = $in_wishlist
										? __( 'Remove from Wishlist', 'product-display' )
										: __( 'Add to Wishlist', 'product-display' );
									?>
									<button type="button"
											class="button <?php echo esc_attr( $wl_class ); ?>"
											data-product-id="<?php echo esc_attr( $product->get_id() ); ?>">
										<?php echo wp_kses_post( $icon_heart ); ?>
										<span class="wcps-button-text"><?php echo esc_html( $wl_text ); ?></span>
									</button>
								<?php endif; ?>
							</div>
						</td>
					<?php endforeach; ?>
				</tr>

				<!-- Description -->
				<tr class="wcps-compare-description">
					<td><?php esc_html_e( 'Description', 'product-display' ); ?></td>
					<?php foreach ( $products as $product ) : ?>
						<td>
							<?php
							$excerpt = $product->get_short_description();
							echo $excerpt
								? wp_kses_post( $excerpt )
								: '<span style="color:#d1d5db;">&mdash;</span>';
							?>
						</td>
					<?php endforeach; ?>
				</tr>

				<!-- SKU -->
				<tr>
					<td><?php esc_html_e( 'SKU', 'product-display' ); ?></td>
					<?php foreach ( $products as $product ) : ?>
						<td>
							<code style="background:#f1f3f8;padding:2px 6px;border-radius:4px;font-size:12px;">
								<?php echo $product->get_sku() ? esc_html( $product->get_sku() ) : '&mdash;'; ?>
							</code>
						</td>
					<?php endforeach; ?>
				</tr>

				<!-- Weight -->
				<tr>
					<td><?php esc_html_e( 'Weight', 'product-display' ); ?></td>
					<?php foreach ( $products as $product ) : ?>
						<td>
							<?php
							if ( $product->get_weight() ) {
								echo esc_html( $product->get_weight() . ' ' . get_option( 'woocommerce_weight_unit' ) );
							} else {
								echo '<span style="color:#d1d5db;">&mdash;</span>';
							}
							?>
						</td>
					<?php endforeach; ?>
				</tr>

				<!-- Dimensions -->
				<tr>
					<td><?php esc_html_e( 'Dimensions', 'product-display' ); ?></td>
					<?php foreach ( $products as $product ) : ?>
						<td>
							<?php
							if ( $product->has_dimensions() ) {
								echo esc_html( wc_format_dimensions( $product->get_dimensions( false ) ) );
							} else {
								echo '<span style="color:#d1d5db;">&mdash;</span>';
							}
							?>
						</td>
					<?php endforeach; ?>
				</tr>

				<!-- Product Type -->
				<tr>
					<td><?php esc_html_e( 'Type', 'product-display' ); ?></td>
					<?php foreach ( $products as $product ) : ?>
						<td>
							<span style="text-transform:capitalize;">
								<?php echo esc_html( $product->get_type() ); ?>
							</span>
						</td>
					<?php endforeach; ?>
				</tr>

				<!-- Categories -->
				<tr>
					<td><?php esc_html_e( 'Categories', 'product-display' ); ?></td>
					<?php foreach ( $products as $product ) : ?>
						<td>
							<?php
							$terms = get_the_terms( $product->get_id(), 'product_cat' );
							if ( $terms && ! is_wp_error( $terms ) ) {
								$cat_links = array();
								foreach ( $terms as $term ) {
									$cat_links[] = '<a href="' . esc_url( get_term_link( $term ) ) . '" style="color:#0f3460;text-decoration:none;" target="_blank" rel="noopener noreferrer">' . esc_html( $term->name ) . '</a>';
								}
								echo implode( ', ', $cat_links ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- links are esc'd above
							} else {
								echo '<span style="color:#d1d5db;">&mdash;</span>';
							}
							?>
						</td>
					<?php endforeach; ?>
				</tr>

				<!-- Tags -->
				<tr>
					<td><?php esc_html_e( 'Tags', 'product-display' ); ?></td>
					<?php foreach ( $products as $product ) : ?>
						<td>
							<?php
							$tags = get_the_terms( $product->get_id(), 'product_tag' );
							if ( $tags && ! is_wp_error( $tags ) ) {
								$tag_names = wp_list_pluck( $tags, 'name' );
								echo esc_html( implode( ', ', $tag_names ) );
							} else {
								echo '<span style="color:#d1d5db;">&mdash;</span>';
							}
							?>
						</td>
					<?php endforeach; ?>
				</tr>

			</tbody>
		</table>
		<?php
	}

	/**
	 * AJAX Add to Cart from Compare Modal
	 */
	public function ajax_add_to_cart() {
		check_ajax_referer('wcps-nonce', 'nonce');

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

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

		$product = wc_get_product($product_id);

		if ( ! $product ) {
			wp_send_json_error(array( 'message' => __('Product not found', 'product-display') ));
		}

		if ( ! $product->is_purchasable() ) {
			wp_send_json_error(array( 'message' => __('This product cannot be purchased', 'product-display') ));
		}

		if ( ! $product->is_in_stock() ) {
			wp_send_json_error(array( 'message' => __('This product is out of stock', 'product-display') ));
		}

		// Add to cart
		$cart_item_key = WC()->cart->add_to_cart($product_id, $quantity);

		if ( $cart_item_key ) {
			// Get cart fragments for updating cart count
			WC_AJAX::get_refreshed_fragments();
			
			wp_send_json_success(array(
				'message' => sprintf(__('%s has been added to your cart', 'product-display'), $product->get_name()),
				'cart_count' => WC()->cart->get_cart_contents_count(),
				'cart_total' => WC()->cart->get_cart_total(),
				'fragments' => WC_AJAX::get_refreshed_fragments()
			));
		} else {
			wp_send_json_error(array( 'message' => __('Failed to add product to cart', 'product-display') ));
		}
	}
}
