<?php
/**
 * Recommendations renderer.
 *
 * @package PRECO
 */

namespace PRECO\Includes\Frontend\Core;

use PRECO\Includes\Admin\Rest\GlobalStylesRest;
use PRECO\Includes\Frontend\Core\Layouts\LayoutFactory;
use PRECO\Includes\Preco;

defined( 'ABSPATH' ) || exit;

/**
 * Renders product IDs using standard WooCommerce loop templates.
 */
class RecommendationsRenderer {

	/**
	 * Render a list of products.
	 *
	 * @param int[]  $product_ids   Product IDs.
	 * @param string $wrapper_class Wrapper CSS class.
	 * @param array  $list_item     Optional list item data, including label.
	 * @return void
	 */
	public function render_products( $product_ids, $wrapper_class = '', $list_item = array() ) {
		$product_ids = is_array( $product_ids ) ? array_values( array_filter( array_map( 'absint', $product_ids ) ) ) : array();

		if ( empty( $product_ids ) ) {
			return;
		}
		if ( ! function_exists( 'woocommerce_product_loop_start' ) ) {
			return;
		}

		// Fetch products directly using WooCommerce API.
		$products = wc_get_products(
			array(
				'include' => $product_ids,
				'limit'   => count( $product_ids ),
				'orderby' => 'include',
				'status'  => 'publish',
			)
		);

		if ( empty( $products ) ) {
			return;
		}

		$this->render_product_objects( $products, $wrapper_class, $list_item );
	}

	/**
	 * Render a list of already-loaded product objects — the shared tail end
	 * of render_products(), also used directly by PreviewRenderer to render
	 * DummyProduct placeholders instead of a database-fetched product list.
	 *
	 * @param \WC_Product[] $products      Product objects.
	 * @param string        $wrapper_class Wrapper CSS class.
	 * @param array         $list_item     Optional list item data, including label.
	 * @return void
	 */
	public function render_product_objects( $products, $wrapper_class = '', $list_item = array() ) {
		$label = isset( $list_item['label'] ) ? (string) $list_item['label'] : '';

		if ( empty( $products ) ) {
			return;
		}
		if ( ! function_exists( 'woocommerce_product_loop_start' ) ) {
			return;
		}

		$design_data = isset( $list_item['design'] ) && is_array( $list_item['design'] ) ? $list_item['design'] : array(
			'columns'         => array(
				'lg' => 2,
				'md' => 2,
				'sm' => 1,
			),
			'label_alignment' => 'left',
			'item_sorting'    => array(
				'product_image'    => true,
				'product_price'    => true,
				'product_title'    => true,
				'add_to_cart'      => false,
				'product_rating'   => false,
				'product_category' => false,
			),
		);

		$style_data = ! empty( $design_data['style'] ) ? $design_data['style'] : array();

		$layout = LayoutFactory::create( isset( $style_data['template_layout'] ) ? $style_data['template_layout'] : '' );

		$wrapper_class = trim( (string) $wrapper_class );
		$cls           = 'preco-recommendations';
		if ( $wrapper_class ) {
			$cls .= ' ' . $wrapper_class;
		}

		$cls .= ' ' . $layout->get_wrapper_class();
		$cls .= ' preco--bordered-' . ( ! empty( $style_data['container_border'] ) ? esc_attr( $style_data['container_border'] ) : 'default' );
		$cls .= ' preco--content_size-' . ( ! empty( $style_data['content_size'] ) ? esc_attr( $style_data['content_size'] ) : 'medium' );

		// Border radius and button style come from the global Widget Style
		// option, not the per-rule design data.
		$global_styles = get_option( GlobalStylesRest::OPTION_NAME, array() );
		$global_styles = is_array( $global_styles ) ? $global_styles : array();

		$border_radius = isset( $global_styles['border_radius'] ) ? sanitize_key( $global_styles['border_radius'] ) : 'rounded';
		if ( ! in_array( $border_radius, GlobalStylesRest::BORDER_RADII, true ) ) {
			$border_radius = 'rounded';
		}

		$button_style = isset( $global_styles['button_style'] ) ? sanitize_key( $global_styles['button_style'] ) : 'rounded';
		if ( ! in_array( $button_style, GlobalStylesRest::BUTTON_STYLES, true ) ) {
			$button_style = 'rounded';
		}

		$cls .= ' preco--radius-' . esc_attr( $border_radius );
		$cls .= ' preco--btn-' . esc_attr( $button_style );

		// Pre-filter once and pass products to template for rendering.
		$valid_products = array();
		foreach ( $products as $p ) {
			if ( ! $p || ! is_a( $p, 'WC_Product' ) ) {
				continue;
			}
			if ( ! in_array( $p->get_type(), Preco::PRODUCT_RENDER_TYPES, true ) || ! $p->is_in_stock() ) {
				continue;
			}
			$valid_products[] = $p;
		}

		if ( empty( $valid_products ) ) {
			return;
		}

		$data_attributes = array(
			'data-location-source' => ! empty( $list_item['custom_props']['location_key'] ) ? esc_attr( $list_item['custom_props']['location_key'] ) : '',
			'data-page-source'     => ! empty( $list_item['custom_props']['page_key'] ) ? esc_attr( $list_item['custom_props']['page_key'] ) : '',
		);

		// Sequential display: expose the list ID so JS can show/hide by ID.
		if ( ! empty( $list_item['custom_props']['list_id'] ) ) {
			$data_attributes['data-list-id'] = esc_attr( $list_item['custom_props']['list_id'] );
		}

		$seq_hidden = ! empty( $list_item['custom_props']['seq_hidden'] );

		$template_vars = array(
			'products'        => $valid_products,
			'design_data'     => $design_data,
			'style_data'      => $style_data,
			'layout'          => $layout,
			'label'           => $label,
			'cls'             => $cls,
			'data_attributes' => $data_attributes,
			'seq_hidden'      => $seq_hidden,
		);

		// Template directory: frontend/templates relative to this file.
		$template_dir  = PRECO_PATH . 'includes/frontend/templates/';
		$template_file = $template_dir . 'recommendations-grid.php';
		if ( file_exists( $template_file ) ) {
			if ( function_exists( 'wc_get_template' ) ) {
				wc_get_template( 'recommendations-grid.php', $template_vars, '', $template_dir );
			} else {
				// Explicit variable extraction instead of extract() (WP discouraged).
				$products        = $template_vars['products'];
				$design_data     = $template_vars['design_data'];
				$style_data      = $template_vars['style_data'];
				$layout          = $template_vars['layout'];
				$label           = $template_vars['label'];
				$cls             = $template_vars['cls'];
				$data_attributes = $template_vars['data_attributes'];
				$seq_hidden      = $template_vars['seq_hidden'];
				include $template_file;
			}
		}
	}
}
