<?php
/**
 * Table Layout for Product Display.
 *
 * @package Product_Display.
 */

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

/**
 * Class PRODDISP_Table.
 *
 * This class handles the rendering of the table layout for product display.
 */
class PRODDISP_Table extends PRODDISP_Layout_Base {
	/**
	 * Render the table layout.
	 *
	 * @param array $products WooCommerce product objects.
	 * @return string HTML output.
	 */
	public function render( $products ) {
		// Enqueue table-specific assets
		PRODDISP_Assets::get_instance()->enqueue_table_style_assets();

		// Handle pro layout modes
		$pro_result = $this->handle_pro_layout_mode('table-2', 'PRODDISP_PRO_Table', 'table-2-locked-style-2.gif', $products);
		if ( $pro_result !== false ) {
			return $pro_result;
		}

		$pro_result = $this->handle_pro_layout_mode('table-3', 'PRODDISP_PRO_Table', 'table-3-locked-style-3.gif', $products);
		if ( $pro_result !== false ) {
			return $pro_result;
		}

		$table_id = 'wcps-table-' . wp_rand(1000, 9999);

		$output = '<div id="' . esc_attr($table_id) . '" class="wcps-table-container">';

		// Table search and sorting controls.
		$output .= $this->render_table_controls();

		// Start table.
		$output .= '<table class="wcps-table">';

		// Table header.
		$output .= $this->render_table_header();

		// Table body.
		$output .= '<tbody>';

		foreach ( $products as $product ) {
			$output .= $this->render_product_row($product);
		}

		$output .= '</tbody>';
		$output .= '</table>';

		// Pagination if needed.
		if ( count($products) > 10 ) {
			$output .= $this->render_pagination();
		}

		$output .= '</div>'; // End .wcps-table-container.

		 // Initialize the table via wp_add_inline_script.
		 $this->initialize_table($table_id, $products);

		return $output;
	}

	/**
	 * Initialize the table with simple jQuery functionality.
	 *
	 * @param string $table_id The ID of the table.
	 * @param array  $products The products to display.
	 * @return string HTML for the initialization script.
	 */
	private function initialize_table( $table_id, $products ) {
		// Generate a unique handle.
		$handle = 'wcps-table-init-' . $table_id;

		// Register and enqueue the script with only jQuery dependency.
		wp_register_script($handle, '', array( 'jquery' ), PRODDISP_VERSION, true);
		wp_enqueue_script($handle);

		// Add the inline initialization script for basic table functionality.
		$script_code = '
			jQuery(document).ready(function($) {
				var $container = $("#' . esc_js($table_id) . '");
				var isDown = false;
				var startX;
				var scrollLeft;

				// Mouse drag scrolling
				$container.on("mousedown", function(e) {
					// Only enable drag on the container, not on interactive elements
					if ($(e.target).is("a, button, input, select, textarea") || $(e.target).closest("a, button, input, select, textarea").length) {
						return;
					}
					isDown = true;
					$container.addClass("active-drag");
					startX = e.pageX - $container.offset().left;
					scrollLeft = $container.scrollLeft();
					e.preventDefault();
				});

				$container.on("mouseleave mouseup", function() {
					isDown = false;
					$container.removeClass("active-drag");
				});

				$container.on("mousemove", function(e) {
					if (!isDown) return;
					e.preventDefault();
					var x = e.pageX - $container.offset().left;
					var walk = (x - startX) * 2; // Scroll speed multiplier
					$container.scrollLeft(scrollLeft - walk);
				});

				// Handle action button events
				$container.on("click", ".wcps-action-btn", function(e) {
					var $btn = $(this);
					
					if ($btn.hasClass("wcps-compare-btn")) {
						e.preventDefault();
						var productId = $btn.data("product-id");
						// Trigger compare action
						$(document.body).trigger("proddisp_compare_product", [productId]);
					}
					
					if ($btn.hasClass("wcps-wishlist-btn")) {
						e.preventDefault();
						var productId = $btn.data("product-id");
						// Trigger wishlist action
						$(document.body).trigger("proddisp_add_to_wishlist", [productId]);
					}
					
					if ($btn.hasClass("wcps-quickview-btn")) {
						e.preventDefault();
						var productId = $btn.data("product-id");
						// Trigger quickview action
						$(document.body).trigger("proddisp_quickview_product", [productId]);
					}
				});
			});
		';

		wp_add_inline_script($handle, $script_code);

		return '';
	}

	/**
	 * Render table controls (search, filters, etc.).
	 *
	 * @return string HTML for table controls.
	 */
	private function render_table_controls() {
		$output = '<div class="wcps-table-controls">';

		// Simple controls can be added here if needed in the future.

		$output .= '</div>';

		return $output;
	}

	/**
	 * Render table header.
	 *
	 * @return string HTML for table header.
	 */
	private function render_table_header() {
		$output = '<thead><tr>';

		// Image column.
		$output .= '<th class="wcps-product-image-col">' . esc_html__('Image', 'product-display') . '</th>';

		// Product title.
		if ( isset($this->settings['show_title']) && $this->settings['show_title'] === 'yes' ) {
			$output .= '<th class="wcps-product-title-col">' . esc_html__('Product', 'product-display') . '</th>';
		}

		// Price.
		if ( 'yes' === $this->settings['show_price'] ) {
			$output .= '<th class="wcps-product-price-col">' . esc_html__('Price', 'product-display') . '</th>';
		}

		// Rating.
		if ( 'yes' === $this->settings['show_rating'] ) {
			$output .= '<th class="wcps-product-rating-col">' . esc_html__('Rating', 'product-display') . '</th>';
		}

		// Stock.
		$output .= '<th class="wcps-product-stock-col">' . esc_html__('Stock', 'product-display') . '</th>';

		// Quantity.
		$output .= '<th class="wcps-product-qty-col">' . esc_html__('Quantity', 'product-display') . '</th>';

		// Actions.
		$output .= '<th class="wcps-product-actions-col">' . esc_html__('Actions', 'product-display') . '</th>';

		$output .= '</tr></thead>';

		return $output;
	}

	/**
	 * Render a product row.
	 *
	 * @param Product_Display $product The product object.
	 * @return string HTML for the product row.
	 */
	private function render_product_row( $product ) {
		$output = '<tr class="wcps-product-row" data-product-id="' . esc_attr($product->get_id()) . '" itemscope itemtype="https://schema.org/Product">';

		// Add structured data
		$output .= '<meta itemprop="name" content="' . esc_attr($product->get_name()) . '">';
		$output .= '<meta itemprop="url" content="' . esc_url(get_permalink($product->get_id())) . '">';
		if ( $product->get_sku() ) {
			$output .= '<meta itemprop="sku" content="' . esc_attr($product->get_sku()) . '">';
		}

		// Product image.
		$output .= '<td class="wcps-product-image-col">';
		$output .= '<a href="' . esc_url(get_permalink($product->get_id())) . '">';

		if ( $product->get_image_id() ) {
			$alt_text = get_post_meta($product->get_image_id(), '_wp_attachment_image_alt', true);
			if ( empty($alt_text) ) {
				$alt_text = $product->get_name();
			}
			$output .= wp_get_attachment_image($product->get_image_id(), 'thumbnail', false, array(
				'alt' => esc_attr($alt_text),
				'loading' => 'lazy',
			));
		} else {
			$output .= wc_placeholder_img('thumbnail', array(
				'alt' => esc_attr($product->get_name() . ' - ' . __('Product Image', 'product-display')),
			));
		}

		$output .= '</a>';
		$output .= '</td>';

		// Product title.
		if ( isset($this->settings['show_title']) && $this->settings['show_title'] === 'yes' ) {
			$output .= '<td class="wcps-product-title-col">';
			$output .= '<h2 class="wcps-product-title" itemprop="name"><a href="' . esc_url(get_permalink($product->get_id())) . '">' . esc_html($product->get_name()) . '</a></h2>';
			// Description (optional)
			if ( isset($this->settings['show_description']) && $this->settings['show_description'] === 'yes' ) {
				$short_description = $product->get_short_description();
				if ( ! empty($short_description) ) {
					$excerpt = wp_trim_words($short_description, $this->settings['excerpt_length'], '...');
					$output .= '<div class="wcps-product-excerpt" itemprop="description">' . wp_kses_post($excerpt) . '</div>';
				}
			}
			$output .= '</td>';
		}

		// Price.
		if ( 'yes' === $this->settings['show_price'] ) {
			$output .= '<td class="wcps-product-price-col" itemprop="offers" itemscope itemtype="https://schema.org/Offer">';
			$output .= '<meta itemprop="price" content="' . esc_attr($product->get_price()) . '">';
			$output .= '<meta itemprop="priceCurrency" content="' . esc_attr(get_woocommerce_currency()) . '">';
			$output .= '<meta itemprop="availability" content="' . ( $product->is_in_stock() ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock' ) . '">';
			$output .= $product->get_price_html();
			$output .= '</td>';
		}

		// Rating.
		if ( 'yes' === $this->settings['show_rating'] ) {
			$output .= '<td class="wcps-product-rating-col">';
			$rating = $product->get_average_rating();

			if ( $rating > 0 ) {
				$output .= '<div itemprop="aggregateRating" itemscope itemtype="https://schema.org/AggregateRating">';
				$output .= '<meta itemprop="ratingValue" content="' . esc_attr($rating) . '">';
				$output .= '<meta itemprop="reviewCount" content="' . esc_attr($product->get_rating_count()) . '">';
				$output .= '<meta itemprop="bestRating" content="5">';
				$output .= '<meta itemprop="worstRating" content="1">';
				$output .= wc_get_rating_html($rating);
				$output .= '</div>';
			} else {
				$output .= '<div class="star-rating">' . esc_html__(' ☆ ☆ ☆ ☆ ☆', 'product-display') . '</div>';
			}

			$output .= '</td>';
		}

		// Stock.
		$output .= '<td class="wcps-product-stock-col">';
		if ( $product->is_in_stock() ) {
			$output .= '<span class="wcps-in-stock">' . esc_html__('In Stock', 'product-display') . '</span>';
		} else {
			$output .= '<span class="wcps-out-of-stock">' . esc_html__('Out of Stock', 'product-display') . '</span>';
		}
		$output .= '</td>';

		// Quantity input
		$output .= '<td class="wcps-product-qty-col">';
		$output .= '<input type="number" class="wcps-qty-input" name="wcps_qty_' . esc_attr($product->get_id()) . '" value="1" min="1" style="width:60px;">';
		$output .= '</td>';

		// Actions.
		$output .= '<td class="wcps-product-actions-col">';
		$output .= $this->render_product_actions($product, 'button');
		$output .= '</td>';

		$output .= '</tr>';

		return $output;
	}

	/**
	 * Render pagination for the table.
	 *
	 * @return string HTML for pagination.
	 */
	private function render_pagination() {
		// Simple pagination can be added here if needed in the future.
		return '';
	}
}
