<?php
/**
 * Category Tabs Layout for Product Showcase
 *
 * @package Product_Display
 */

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

/**
 * Class PRODDISP_Category_Tabs
 *
 * This class handles the rendering of product categories in tabbed layout.
 * It extends the base layout class and provides methods to group products by category,
 * render tabs navigation, and display products in grid or slider format.
 */
class PRODDISP_Category_Tabs extends PRODDISP_Layout_Base {
	/**
	 * Render the category tabs layout
	 *
	 * @param array $products WooCommerce product objects
	 * @return string HTML output
	 */
	public function render( $products ) {
		// Enqueue category tabs-specific assets
		PRODDISP_Assets::get_instance()->enqueue_category_tabs_style_assets();

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

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

		// Group products by category
		$categories = $this->group_products_by_category($products);

		if ( empty($categories) ) {
			return '<p>' . __('No categories found for the selected products.', 'product-display') . '</p>';
		}

		$tabs_id = 'wcps-tabs-' . rand(1000, 9999);

		$output = '<div id="' . esc_attr($tabs_id) . '" class="wcps-category-tabs">';

		// Tabs navigation
		$output .= $this->render_tabs_nav($categories, $tabs_id);

		// Tabs content
		$output .= $this->render_tabs_content($categories, $tabs_id);

		$output .= '</div>'; // End .wcps-category-tabs

		// Add initialization script
		$output .= '<script>
            jQuery(document).ready(function($) {
                // Initialize tabs
                $("#' . esc_js($tabs_id) . ' .wcps-tab-nav li:first-child a").addClass("active");
                $("#' . esc_js($tabs_id) . ' .wcps-tab-content:first-child").addClass("active");
                
                // Tab click event
                $("#' . esc_js($tabs_id) . ' .wcps-tab-nav a").on("click", function(e) {
                    e.preventDefault();
                    
                    var target = $(this).attr("href");
                    
                    // Remove active class from all tabs and content
                    $("#' . esc_js($tabs_id) . ' .wcps-tab-nav a").removeClass("active");
                    $("#' . esc_js($tabs_id) . ' .wcps-tab-content").removeClass("active");
                    
                    // Add active class to current tab and content
                    $(this).addClass("active");
                    $(target).addClass("active");
                    
                    // Initialize sliders if any
                    if ($(target).find(".wcps-slider").length) {
                        $(target).find(".wcps-slider").slick("refresh");
                    }
                    
                    return false;
                });
            });
        </script>';

		return $output;
	}

	/**
	 * Group products by category
	 *
	 * @param array $products WooCommerce product objects
	 * @return array Products grouped by category
	 */
	private function group_products_by_category( $products ) {
		$categories = array();

		foreach ( $products as $product ) {
			$product_cats = get_the_terms($product->get_id(), 'product_cat');

			if ( is_array($product_cats) && ! empty($product_cats) ) {
				foreach ( $product_cats as $cat ) {
					if ( ! isset($categories[ $cat->term_id ]) ) {
						$categories[ $cat->term_id ] = array(
							'name' => $cat->name,
							'slug' => $cat->slug,
							'products' => array(),
						);
					}

					$categories[ $cat->term_id ]['products'][] = $product;
				}
			} else {
				// Products without category go to "Uncategorized"
				if ( ! isset($categories['uncategorized']) ) {
					$categories['uncategorized'] = array(
						'name' => __('Uncategorized', 'product-display'),
						'slug' => 'uncategorized',
						'products' => array(),
					);
				}

				$categories['uncategorized']['products'][] = $product;
			}
		}

		// Sort categories by name
		uasort($categories, function ( $a, $b ) {
			return strcmp($a['name'], $b['name']);
		});

		return $categories;
	}

	/**
	 * Render tabs navigation
	 *
	 * @param array  $categories Categories with products
	 * @param string $tabs_id Unique ID for the tabs
	 * @return string HTML for tabs navigation
	 */
	private function render_tabs_nav( $categories, $tabs_id ) {
		$output = '<ul class="wcps-tab-nav">';

		$is_first = true;
		foreach ( $categories as $cat_id => $category ) {
			$tab_id = is_numeric($cat_id) ? 'category-' . $cat_id : $cat_id;
			$active_class = $is_first ? ' active' : '';

			$output .= '<li>';
			$output .= '<a href="#' . esc_attr($tabs_id . '-' . $tab_id) . '" class="wcps-tab-link' . $active_class . '">';
			$output .= esc_html($category['name']);
			$output .= ' <span class="wcps-product-count">(' . count($category['products']) . ')</span>';
			$output .= '</a>';
			$output .= '</li>';

			$is_first = false;
		}

		$output .= '</ul>';

		return $output;
	}

	/**
	 * Render tabs content
	 *
	 * @param array  $categories Categories with products
	 * @param string $tabs_id Unique ID for the tabs
	 * @return string HTML for tabs content
	 */
	private function render_tabs_content( $categories, $tabs_id ) {
		$output = '';
		$columns = absint($this->settings['columns'] ?? 4);

		if ( $columns < 1 ) {
			$columns = 4;
		}

		$is_first = true;
		foreach ( $categories as $cat_id => $category ) {
			$tab_id = is_numeric($cat_id) ? 'category-' . $cat_id : $cat_id;
			$active_class = $is_first ? ' active' : '';

			$output .= '<div id="' . esc_attr($tabs_id . '-' . $tab_id) . '" class="wcps-tab-content' . $active_class . '">';

			// Decide how to display products within the tab
			if ( $this->settings['layout'] === 'slider' ) {
				// Display as slider
				$output .= $this->render_category_slider($category['products']);
			} else {
				// Display as grid
				$output .= '<div class="wcps-products-grid wcps-columns-' . esc_attr($columns) . '">';

				foreach ( $category['products'] as $product ) {
					$output .= $this->render_product_grid_item($product);
				}

				$output .= '</div>'; // End .wcps-products-grid
			}

			$output .= '</div>'; // End .wcps-tab-content

			$is_first = false;
		}

		return $output;
	}

	/**
	 * Render products as a slider inside category tab
	 *
	 * @param array $products Products for this category
	 * @return string HTML for product slider
	 */
	private function render_category_slider( $products ) {
		// Enqueue slider assets
		PRODDISP_Assets::get_instance()->enqueue_slider_assets();

		$slide_settings = array(
			'autoplay' => $this->settings['autoplay'] === 'yes',
			'arrows' => $this->settings['arrows'] === 'yes',
			'dots' => $this->settings['dots'] === 'yes',
			'speed' => intval($this->settings['slide_speed']),
			'slidesToShow' => absint($this->settings['columns']),
			'slidesToScroll' => 1,
			'responsive' => array(
				array(
					'breakpoint' => 1024,
					'settings' => array(
						'slidesToShow' => min(absint($this->settings['columns']), 3),
					),
				),
				array(
					'breakpoint' => 768,
					'settings' => array(
						'slidesToShow' => 2,
					),
				),
				array(
					'breakpoint' => 480,
					'settings' => array(
						'slidesToShow' => 1,
					),
				),
			),
		);

		$slider_id = 'wcps-slider-' . rand(1000, 9999);

		$output = '<div id="' . esc_attr($slider_id) . '" class="wcps-slider">';

		foreach ( $products as $product ) {
			$output .= '<div class="wcps-slide">';
			$output .= $this->render_product($product);
			$output .= '</div>'; // End .wcps-slide
		}

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

		// Add initialization script
		$output .= '<script>
            jQuery(document).ready(function($) {
                $("#' . esc_js($slider_id) . '").slick(' . wp_json_encode($slide_settings) . ');
            });
        </script>';

		return $output;
	}

	/**
	 * Render a product in grid view for category tab
	 *
	 * @param WC_Product $product The product object
	 * @return string HTML for the product
	 */
	private function render_product_grid_item( $product ) {
		$output = '<div class="wcps-product-item" itemscope itemtype="https://schema.org/Product">';
		$output .= '<div class="wcps-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 .= '<div class="wcps-product-image">';
		$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(), $this->settings['image_size'], false, array(
				'loading' => 'lazy',
				'alt' => esc_attr($alt_text),
			));
		} else {
			$output .= wc_placeholder_img($this->settings['image_size'], array(
				'alt' => esc_attr($product->get_name() . ' - ' . __('Product Image', 'product-display')),
			));
		}

		$output .= '</a>';

		// Show action buttons if position is hover
		if ( $this->settings['action_position'] === 'hover' ) {
			$output .= $this->render_product_actions($product);
		}

		$output .= '</div>'; // End .wcps-product-image

		// Product content
		$output .= $this->render_product_content($product);

		// Show action buttons if position is below
		if ( $this->settings['action_position'] === 'below' ) {
			$output .= $this->render_product_actions($product);
		}

		$output .= '</div>'; // End .wcps-product
		$output .= '</div>'; // End .wcps-product-item

		return $output;
	}

	/**
	 * Render a product for slider view
	 *
	 * @param WC_Product $product The product object
	 * @return string HTML for the product
	 */
	private function render_product( $product ) {
		$output = '<div class="wcps-product" 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 .= '<div class="wcps-product-image">';
		$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(), $this->settings['image_size'], false, array(
				'loading' => 'lazy',
				'alt' => esc_attr($alt_text),
			));
		} else {
			$output .= wc_placeholder_img($this->settings['image_size'], array(
				'alt' => esc_attr($product->get_name() . ' - ' . __('Product Image', 'product-display')),
			));
		}

		$output .= '</a>';

		// Show action buttons if position is hover
		if ( $this->settings['action_position'] === 'hover' ) {
			$output .= $this->render_product_actions($product);
		}

		$output .= '</div>'; // End .wcps-product-image

		// Product content
		$output .= $this->render_product_content($product);

		// Show action buttons if position is below
		if ( $this->settings['action_position'] === 'below' ) {
			$output .= $this->render_product_actions($product);
		}

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

		return $output;
	}
}
