<?php
/**
 * Cart Preview Recommendations
 *
 * @package   EDD\Pro\Recommendations
 * @copyright Copyright (c) 2025, Sandhills Development, LLC
 * @license   https://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since     3.6.2
 */

namespace EDD\Pro\Recommendations;

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit; // @codeCoverageIgnore

use EDD\EventManagement\SubscriberInterface;

/**
 * Cart Preview Recommendations class
 *
 * @since 3.6.2
 */
class Preview implements SubscriberInterface {

	/**
	 * Get the subscribed events.
	 *
	 * @since 3.6.2
	 * @return array
	 */
	public static function get_subscribed_events(): array {
		return array(
			'edd_cart_preview_data'            => 'add_recommendations',
			'edd_cart_preview_assets_enqueued' => 'enqueue_script',
			'edd_cart_preview_after_items'     => 'render_recommendations_section',
			'edd_cart_preview_templates'       => 'render_recommendation_template',
		);
	}

	/**
	 * Add recommendations to the cart preview data.
	 *
	 * @since 3.6.2
	 * @param array $cart_data The cart data.
	 * @return array The cart data.
	 */
	public function add_recommendations( $cart_data ): array {
		if ( ! edd_get_option( 'cart_recommendations', false ) ) {
			return $cart_data;
		}

		// Extract product IDs from cart items.
		$product_ids = wp_list_pluck( $cart_data['items'], 'id' );
		if ( empty( $product_ids ) ) {
			return $cart_data;
		}

		$query           = new Query();
		$recommendations = $query->get_cart_recommendations( $product_ids, array( 'limit' => 3 ) );
		if ( empty( $recommendations ) ) {
			return $cart_data;
		}

		$cart_data['recommendations'] = array_values( array_filter( array_map( array( $this, 'format_recommendation' ), $recommendations ) ) );

		return $cart_data;
	}

	/**
	 * Format a recommendation.
	 *
	 * @since 3.6.2
	 * @param array $recommendation The recommendation.
	 * @return array The formatted recommendation.
	 */
	private function format_recommendation( $recommendation ) {
		if ( empty( $recommendation['product_id'] ) ) {
			return false;
		}

		$download_id = absint( $recommendation['product_id'] );
		$download    = edd_get_download( $download_id );
		if ( ! $download || ! $download->can_purchase() ) {
			return false;
		}

		// Product recommendations will default to the default variation.
		if ( $download->has_variable_prices() ) {
			$price_id = $download->get_default_price_id();
			$price    = edd_get_price_option_amount( $download_id, $price_id );
			$name     = edd_get_download_name( $download_id, $price_id );
		} else {
			$price = $download->get_price();
			$name  = edd_get_download_name( $download_id );
		}

		return array(
			'product_id' => $download_id,
			'url'        => get_permalink( $download_id ),
			'title'      => $name,
			'price'      => edd_currency_filter( edd_format_amount( $price ) ),
			'thumbnail'  => $this->get_thumbnail_url( $download_id ),
		);
	}

	/**
	 * Enqueue the recommendations preview script.
	 *
	 * @since 3.6.2
	 * @return void
	 */
	public function enqueue_script() {
		if ( ! edd_get_option( 'cart_recommendations', false ) ) {
			return;
		}

		wp_enqueue_script(
			'edd-recommendations-preview',
			EDD_PLUGIN_URL . 'assets/build/pro/js/frontend/recommendations.js',
			array( 'edd-cart-preview' ),
			edd_admin_get_script_version(),
			true
		);

		wp_localize_script(
			'edd-recommendations-preview',
			'eddRecommendationsPreview',
			array(
				'i18n' => array(
					/* translators: %s is the product name */
					'addItemLabel' => __( 'Add %s to cart', 'easy-digital-downloads' ),
				),
			)
		);
	}

	/**
	 * Render the recommendations section container.
	 *
	 * @since 3.6.2
	 * @return void
	 */
	public function render_recommendations_section() {
		if ( ! edd_get_option( 'cart_recommendations', false ) ) {
			return;
		}
		?>
		<div class="cart-preview-recommendations hidden" part="recommendations">
			<h3 class="cart-preview-recommendations__title" part="recommendations-title"><?php esc_html_e( 'You might also like:', 'easy-digital-downloads' ); ?></h3>
			<ul class="cart-preview-recommendations__list" part="recommendations-list"></ul>
		</div>
		<?php
	}

	/**
	 * Render the recommendation item template.
	 *
	 * @since 3.6.2
	 * @return void
	 */
	public function render_recommendation_template() {
		if ( ! edd_get_option( 'cart_recommendations', false ) ) {
			return;
		}
		?>
		<!-- Recommendation Item Template -->
		<template id="edd-cart-preview-recommendation-template">
			<li class="cart-preview-recommendation" part="recommendation recommendation-item" data-product-id="">
				<img src="" alt="" class="cart-preview-recommendation__image" part="recommendation-image" style="display: none;">
				<div class="cart-preview-recommendation__details" part="recommendation-details">
					<h4 class="cart-preview-recommendation__title" part="recommendation-title"><a href=""></a></h4>
					<div class="cart-preview-recommendation__price" part="recommendation-price"></div>
				</div>
				<button class="cart-preview-recommendation__button" part="recommendation-button" data-product-id="" type="button">
					<?php esc_html_e( 'Add to Cart', 'easy-digital-downloads' ); ?>
				</button>
			</li>
		</template>
		<?php
	}

	/**
	 * Get thumbnail URL for download.
	 *
	 * @since 3.6.2
	 * @param int $download_id Download ID.
	 * @return string|null Thumbnail URL or null.
	 */
	private function get_thumbnail_url( $download_id ) {
		if ( ! has_post_thumbnail( $download_id ) ) {
			return null;
		}

		$thumbnail_id = get_post_thumbnail_id( $download_id );
		$thumbnail    = wp_get_attachment_image_src( $thumbnail_id, 'thumbnail' );

		if ( ! $thumbnail ) {
			return null;
		}

		return $thumbnail[0];
	}
}
