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

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

/**
 * Class PRODDISP_Gallery
 *
 * This class handles the rendering of the gallery layout for product showcase.
 * It extends the base layout class and provides methods to render products in a grid format,
 * including category filtering and product actions.
 */

class PRODDISP_Gallery extends PRODDISP_Layout_Base {
	/**
	 * Render the gallery layout
	 *
	 * @param array $products WooCommerce product objects
	 * @return string HTML output
	 */
	public function render( $products ) {
		// Enqueue gallery-specific assets
		PRODDISP_Assets::get_instance()->enqueue_gallery_style_assets();

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

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

		$columns = absint($this->settings['columns'] ?? 4);
		if ( $columns < 1 ) {
			$columns = 4;
		}

		$gallery_id = 'wcps-gallery-' . rand(1000, 9999);

		$output = '<div id="' . esc_attr($gallery_id) . '" class="wcps-gallery wcps-columns-' . esc_attr($columns) . '" style="margin-bottom: 30px;">';

		// Filter navigation for product categories
		$output .= $this->render_filter_nav($products);

		// Products container
		$output .= '<div class="wcps-gallery-container" style="margin-top: 20px;">';

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

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

		// Add initialization script
		$output .= '<script>
            jQuery(document).ready(function($) {
                // Initialize isotope filtering
                var $grid = $("#' . esc_js($gallery_id) . ' .wcps-gallery-container");
                
                $grid.imagesLoaded(function() {
                    $grid.isotope({
                        itemSelector: ".wcps-gallery-item",
                        percentPosition: true,
                        masonry: {
                            columnWidth: ".wcps-gallery-item"
                        }
                    });
                });
                
                // Filter items on button click
                $("#' . esc_js($gallery_id) . ' .wcps-gallery-filter").on("click", "button", function() {
                    var filterValue = $(this).attr("data-filter");
                    $grid.isotope({ filter: filterValue });
                    $(this).siblings().removeClass("active");
                    $(this).addClass("active");
                });
            });
        </script>';

		return $output;
	}

	/**
	 * Render filter navigation for product categories
	 *
	 * @param array $products WooCommerce product objects
	 * @return string HTML for the filter navigation
	 */
	private function render_filter_nav( $products ) {
		$categories = array();

		// Collect all categories from products
		foreach ( $products as $product ) {
			$product_cats = wc_get_product_category_list($product->get_id(), ', ', '', '');
			if ( ! empty($product_cats) ) {
				$cat_slugs = $this->extract_category_slugs($product_cats);
				foreach ( $cat_slugs as $cat_slug ) {
					if ( ! isset($categories[ $cat_slug['slug'] ]) ) {
						$categories[ $cat_slug['slug'] ] = $cat_slug['name'];
					}
				}
			}
		}

		// No categories found
		if ( empty($categories) ) {
			return '';
		}

		// Build filter navigation
		$output = '<div class="wcps-gallery-filter" style="display: flex; flex-wrap: wrap; gap: 10px; justify-content: center; margin-bottom: 20px;">';
		$output .= '<button class="active" data-filter="*" style="padding: 8px 16px; background-color: #4a6cf7; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; transition: all 0.3s ease;">' . esc_html__('All', 'product-display') . '</button>';

		foreach ( $categories as $slug => $name ) {
			$output .= '<button data-filter=".category-' . esc_attr($slug) . '" style="padding: 8px 16px; background-color: #f5f5f5; color: #333333; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; transition: all 0.3s ease;">' . esc_html($name) . '</button>';
		}

		$output .= '</div>';

		return $output;
	}

	/**
	 * Extract category slugs from category HTML
	 *
	 * @param string $category_html Category HTML from wc_get_product_category_list()
	 * @return array Array of category slugs and names
	 */
	private function extract_category_slugs( $category_html ) {
		$slugs = array();
		$pattern = '/<a href=".*?\/product-category\/(.*?)\/.*?">(.*?)<\/a>/i';

		preg_match_all($pattern, $category_html, $matches, PREG_SET_ORDER);

		foreach ( $matches as $match ) {
			if ( isset($match[1]) && isset($match[2]) ) {
				$slugs[] = array(
					'slug' => sanitize_title($match[1]),
					'name' => wp_strip_all_tags($match[2]),
				);
			}
		}

		return $slugs;
	}

	/**
	 * Render a single product in the gallery
	 *
	 * @param WC_Product $product The product object
	 * @return string HTML for the product
	 */
	private function render_product( $product ) {
		// Get product categories for filtering
		$product_cats = wc_get_product_category_list($product->get_id(), ', ', '', '');
		$cat_slugs = $this->extract_category_slugs($product_cats);

		$category_classes = '';
		foreach ( $cat_slugs as $cat_slug ) {
			$category_classes .= ' category-' . esc_attr($cat_slug['slug']);
		}

		$output = '<div class="wcps-gallery-item' . $category_classes . '" style="padding: 10px; width: calc(100% / ' . absint($this->settings['columns'] ?? 4) . ' - 20px); float: left; box-sizing: border-box;" itemscope itemtype="https://schema.org/Product">';
		$output .= '<div class="wcps-product" style="height: 100%; position: relative; background: white; border: 1px solid #eaeaea; border-radius: 8px; overflow: hidden; transition: all 0.3s ease; display: flex; flex-direction: column;">';

		// 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" style="position: relative; overflow: hidden;">';
		$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'] ?? 'woocommerce_thumbnail', false, array(
				'style' => 'width: 100%; height: auto; display: block; transition: transform 0.4s ease;',
				'loading' => 'lazy',
				'alt' => esc_attr($alt_text),
			));
		} else {
			$output .= wc_placeholder_img($this->settings['image_size'] ?? 'woocommerce_thumbnail', 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'] ?? 'below' ) === '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' ) === 'below' ) {
			$output .= $this->render_product_actions($product);
		}

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

		return $output;
	}
}
