<?php

namespace PixelioCartAbandonRecoveryMore\Admin\Services;


use PixelioCartAbandonRecoveryMore\Admin\Wrapper\Pixelio_Cart_Abandon_Recovery_More_Woocommerce_Wrapper;
use PixelioCartAbandonRecoveryMore\Admin\Wrapper\Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper;
use PixelioCartAbandonRecoveryMore\Frontend\Repositories\Pixelio_Cart_Abandon_Recovery_More_Cart_Item_Repository;
use PixelioCartAbandonRecoveryMore\Frontend\Repositories\Pixelio_Cart_Abandon_Recovery_More_Cart_Repository;

if (!defined('ABSPATH')) exit;


/**
 * Class Pixelio_Cart_Abandon_Recovery_More_Email
 *
 * Handles email sending for abandoned carts and order review requests.
 * Core responsibilities:
 *  - Retrieve and validate recipients from POST data or WooCommerce orders
 *  - Generate coupons and prepare email content
 *  - Replace placeholders in email templates
 *  - Log sent emails
 *  - Generate recovery, review, and unsubscribe links
 *  - Process email queues and update status via API or local storage
 *
 * @package PixelioCartAbandonRecoveryMore\Admin\Service
 */
class Pixelio_Cart_Abandon_Recovery_More_Email_Variable_Replacer_Service
{
	/**
	 * WordPress abstraction layer (POST, sanitize, esc_html, etc).
	 *
	 * @var Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper
	 */
	private Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $pixelio_wordpress_wrapper;




	/**
	 * WooCommerce wrapper for order and product operations.
	 *
	 * @var Pixelio_Cart_Abandon_Recovery_More_Woocommerce_Wrapper
	 */
	private Pixelio_Cart_Abandon_Recovery_More_Woocommerce_Wrapper $pixelio_woocommerce_wrapper;

	/**
	 * Cart Model for cart & cart item recuperation and  operations.
	 *
	 * @var Pixelio_Cart_Abandon_Recovery_More_Cart_Repository
	 */
	private Pixelio_Cart_Abandon_Recovery_More_Cart_Repository $pixelio_cart_repo;
	private Pixelio_Cart_Abandon_Recovery_More_Cart_Item_Repository $pixelio_cart_item_repo;

	/**
	 * Constructor
	 *
	 */
	public function __construct($pixelio_wordpress_wrapper, $woocommerce_wrapper, $pixelio_cart_repo,$pixelio_cart_item_repo)
	{
		$this->pixelio_wordpress_wrapper = $pixelio_wordpress_wrapper;
		$this->pixelio_woocommerce_wrapper = $woocommerce_wrapper;
		$this->pixelio_cart_repo = $pixelio_cart_repo;
		$this->pixelio_cart_item_repo = $pixelio_cart_item_repo;
	}

	/**
	 * Génère le HTML complet du panier
	 */
	protected
	function generate_cart_html(array $pixelio_cart_items): string
	{
		$pixelio_html = '';
		$pixelio_total = 0;

		foreach ($pixelio_cart_items as $pixelio_item) {
			$pixelio_product = $pixelio_item['product'];
			$pixelio_quantity = $pixelio_item['quantity'];
			$pixelio_line_total = $pixelio_item['total'];
			$pixelio_total += $pixelio_line_total;

			$pixelio_name = $pixelio_product->get_name();
			$pixelio_price = $this->pixelio_wordpress_wrapper->pixelio_wc_price($pixelio_line_total / max(1, $pixelio_quantity));
			$pixelio_line_total_html = $this->pixelio_wordpress_wrapper->pixelio_wc_price($pixelio_line_total);

			$pixelio_image = $pixelio_product->get_image_id()
				? $this->pixelio_wordpress_wrapper->pixelio_wp_get_attachment_image_url($pixelio_product->get_image_id(), 'thumbnail')
				: $this->pixelio_wordpress_wrapper->pixelio_esc_attr(
					$this->pixelio_wordpress_wrapper->pixelio_plugins_url('../assets/img/product-placeholder.png', __FILE__)
				);

			$pixelio_description = $this->pixelio_wordpress_wrapper->pixelio_wp_trim_words(
				$this->pixelio_wordpress_wrapper->pixelio_wp_strip_all_tags($pixelio_product->get_short_description()),
				18
			);

			// --- Include item template ---
			ob_start();
			$pixelio_template_path = $this->pixelio_wordpress_wrapper->pixelio_plugin_dir_path(__FILE__) . '../views/preview/class-pixelio-cart-abandon-recovery-more-generate-cart-content.php';
			if (file_exists($pixelio_template_path)) {
				include $pixelio_template_path;
			}
			$pixelio_html .= ob_get_clean();
		}

		// --- Include total template ---
		ob_start();
		$pixelio_total_template_path = $this->pixelio_wordpress_wrapper->pixelio_plugin_dir_path(__FILE__) . '../views/preview/class-pixelio-cart-abandon-recovery-more-generate-total-cart-content.php';
		if (file_exists($pixelio_total_template_path)) {
			include $pixelio_total_template_path;
		}
		$pixelio_html .= ob_get_clean();

		return $pixelio_html;
	}


	/**
	 * Replace placeholder variables in email content with actual data.
	 *
	 * This function processes placeholders such as:
	 * - {{prenom}}: Customer's first name
	 * - {{nom}}: Customer's last name
	 * - {{email}}: Customer's email address
	 * - {{cart}}: HTML table of order items (product name, quantity, price)
	 * - {{discount_code}}: Discount or coupon code
	 * - {{store_name}}: Name of the store
	 * - {{store_url}}: Store homepage URL
	 * - {{review_link}}: Link to submit a product review
	 * - {{product_name}}: Product name if provided
	 * - {{unsubscribe_link}}: Unsubscribe link for email communications
	 *
	 * @param string $pixelio_content The email content with placeholders.
	 *
	 * @return string The email content with all placeholders replaced by actual values.
	 */
	public
	function pixelio_replace_email_variables(
		string $pixelio_content,
			   $pixelio_order_id,
			   $pixelio_coupon,
		string $pixelio_review_link,
		string $pixelio_unsubscribe,
		string $pixelio_recover_link,
		string $pixelio_type_of_email,
		bool   $demo,
		string $pixelio_uuid
	): string
	{

		// 1️⃣ Remplace les placeholders de coupon
		$pixelio_content = $this->replace_discount_placeholders($pixelio_content, $pixelio_coupon, $pixelio_type_of_email, $demo);

		//
//		// 2️⃣ Remplace les placeholders utilisateur (firstname, lastname)
		$pixelio_content = $this->replace_user_placeholders($pixelio_content, $demo);

//
//		// 3️⃣ Remplace les placeholders spécifiques au magasin
		$pixelio_content = $this->replace_store_placeholders($pixelio_content);

//
//		// 4️⃣ Remplace les liens (recover, review, unsubscribe)
		$pixelio_content = $this->replace_links($pixelio_content, $pixelio_recover_link, $pixelio_review_link, $pixelio_unsubscribe);
//
//		// 5️⃣ Remplace le contenu du panier
		$pixelio_content = $this->cart_content_replacement($pixelio_content, $pixelio_order_id, $pixelio_uuid);

		return $pixelio_content;
	}



	private function format_expiration($expiration,$pixelio_content): string
	{
		$expiration = trim((string) $expiration);

		if (stripos($pixelio_content, 'minutes') !== false) {
			return $expiration;
		}

		return $expiration . ' minutes';
	}

	/**
	 * Replace discount-related placeholders
	 */
	private
	function replace_discount_placeholders(string $pixelio_content, $pixelio_coupon, string $pixelio_type_of_email, bool $pixelio_demo): string
	{
		if ($pixelio_coupon && $pixelio_demo) {
			$pixelio_code = "EXAMPLE" . $pixelio_coupon['coupon_code'];
			$pixelio_expiration = $this->format_expiration(
				$this->pixelio_wordpress_wrapper->pixelio_sanitize_text_field(
					$this->pixelio_wordpress_wrapper->pixelio_wp_unslash(
						$pixelio_coupon['coupon_expiration'],
					)
				),$pixelio_content
			);
		} else if ($pixelio_demo) {
			$pixelio_code = $this->pixelio_wordpress_wrapper->pixelio_translate('Please activate coupon in settings or override them in email editor', 'rivio-ai-cart-recovery-marketing-email-automation');
			$pixelio_expiration = $pixelio_code;
		} else if ($pixelio_coupon) {
			$pixelio_code = $pixelio_coupon['coupon_code'];
			$pixelio_expiration =  $this->format_expiration(
				$pixelio_coupon['coupon_expiration'],$pixelio_content
			);
		} else {
			$pixelio_code = '';
			$pixelio_expiration = '';
		}

		$pixelio_content = str_replace('{{discount_code}}', $pixelio_code, $pixelio_content);
		$pixelio_content = str_replace('{{discount_expiration_time}}', $pixelio_expiration, $pixelio_content);

		return $pixelio_content;
	}

	/**
	 * Replace user-related placeholders
	 */
	private
	function replace_user_placeholders(string $pixelio_content, bool $pixelio_demo): string
	{
		$pixelio_user = $this->pixelio_wordpress_wrapper->pixelio_wp_get_current_user();

		if ($pixelio_user && $pixelio_user->exists() && !$pixelio_demo) {
			$pixelio_firstname = $pixelio_user->first_name;
			$pixelio_lastname = $pixelio_user->last_name;
		} else {
			$pixelio_firstname = 'Jean';
			$pixelio_lastname = 'UNEXEMPLE';
		}

		return str_replace(
			['{{firstname}}', '{{lastname}}', '{{prenom}}', '{{nom}}', '{{email}}'],
			[$pixelio_firstname, $pixelio_lastname, '', '', ''],
			$pixelio_content
		);
	}

	/**
	 * Replace store-related placeholders
	 */
	private
	function replace_store_placeholders(string $pixelio_content): string
	{
		$pixelio_store_name = $this->pixelio_wordpress_wrapper->pixelio_get_bloginfo('name');
		return str_replace('{{store_name}}', $pixelio_store_name, $pixelio_content);
	}

	/**
	 * Replace links placeholders
	 */
	private
	function replace_links(string $pixelio_content, string $pixelio_recover_link, string $pixelio_review_link, string $pixelio_unsubscribe): string
	{
		$pixelio_content = str_replace(['href="{{recover_link}}"', "href='{{recover_link}}'"], "href='{$pixelio_recover_link}'", $pixelio_content);
		$pixelio_content = str_replace('{{recover_link}}', "<a href='{$pixelio_recover_link}'>" .
			$this->pixelio_wordpress_wrapper->pixelio_translate('Recover my cart', 'rivio-ai-cart-recovery-marketing-email-automation') . "</a>", $pixelio_content);



		$pixelio_content = str_replace(['href="{{review_link}}"', "href='{{review_link}}'"], "href='{$pixelio_review_link}'", $pixelio_content);
		$pixelio_content = str_replace('{{review_link}}', "<a href='{$pixelio_review_link}'>" .
			$this->pixelio_wordpress_wrapper->pixelio_translate('Unsubscribe', 'rivio-ai-cart-recovery-marketing-email-automation') . "</a>", $pixelio_content);

		$pixelio_unsubscribe_link = $pixelio_unsubscribe ?? '';
		$pixelio_content = str_replace('{{unsubscribe}}', "<a href='{$pixelio_unsubscribe_link}'>" .
			$this->pixelio_wordpress_wrapper->pixelio_translate('Unsubscribe', 'rivio-ai-cart-recovery-marketing-email-automation') . "</a>", $pixelio_content);

		return $pixelio_content;
	}

	/**
	 * Replace cart placeholders in email content
	 */
	public function cart_content_replacement(string $pixelio_content, $pixelio_order_id, string $pixelio_uuid): string
	{
		$pixelio_cart_items = $this->get_cart_items($pixelio_order_id, $pixelio_uuid);

		$pixelio_content = str_replace(
			["\r\n", "\r", "\n", '\\r\\n', '\\r', '\\n'],
			'<br>',
			$pixelio_content
		);

		if (empty($pixelio_cart_items)) {
			$empty_cart_text = $this->pixelio_wordpress_wrapper->pixelio_translate(
				'Nothing in your cart',
				'rivio-ai-cart-recovery-marketing-email-automation'
			);

			return preg_replace(
				'/\{\{cart\}\}|\{\{cart_content\}\}/i',
				$empty_cart_text,
				$pixelio_content
			);
		}

		$pixelio_cart_content_html = $this->generate_cart_html($pixelio_cart_items);

		if (stripos($pixelio_cart_content_html, '<tr') !== false) {
			$pixelio_cart_content_html = "<table><tbody>{$pixelio_cart_content_html}</tbody></table>";
		}

		return preg_replace(
			'/\{\{cart\}\}|\{\{cart_content\}\}/i',
			$pixelio_cart_content_html,
			$pixelio_content
		);
	}

	/**
	 * Récupère les items du panier depuis WooCommerce ou UUID sauvegardé
	 */
	protected
	function get_cart_items($pixelio_order_id, string $pixelio_uuid): array
	{
		$pixelio_cart_items = [];

		if ($pixelio_order_id && $pixelio_order_id > 0) {
			$pixelio_order = $this->pixelio_woocommerce_wrapper->pixelio_wc_get_order($pixelio_order_id);
			if ($pixelio_order) {
				foreach ($pixelio_order->get_items() as $item) {
					$pixelio_product = $item->get_product();
					if (!$pixelio_product) continue;

					$pixelio_quantity = (int)$item->get_quantity();
					$pixelio_line_total = (float)$item->get_total();

					$pixelio_cart_items[] = [
						'product' => $pixelio_product,
						'quantity' => $pixelio_quantity,
						'total' => $pixelio_line_total
					];
				}
			}
		}

		if (empty($pixelio_cart_items) && !empty($pixelio_uuid)) {
			$pixelio_cart_id = $this->pixelio_cart_repo->pixelio_find_by_uuid($pixelio_uuid);
			$pixelio_saved_items = $this->pixelio_cart_item_repo->pixelio_find_item_by_cart_id($pixelio_cart_id);
			if (is_array($pixelio_saved_items)) {
				foreach ($pixelio_saved_items as $pixelio_item) {
					$pixelio_product = $pixelio_item->woo_product_id;
					$pixelio_quantity = (int)$pixelio_item->quantity;

					$woo_product = wc_get_product($pixelio_product);
					$pixelio_line_total = "Price not found";
					if ($woo_product) {
						$pixelio_line_total = (float)$woo_product->get_price() * $pixelio_quantity;
					}


					$pixelio_cart_items[] = [
						'product' => $woo_product,
						'quantity' => $pixelio_quantity,
						'total' => $pixelio_line_total
					];
				}
			}
		}

		return $pixelio_cart_items;
	}

	/**
	 * Generate a unique cart recovery link for a given cart ID.
	 *
	 * This method creates a random token, updates the cart record with the token,
	 * and returns a URL that the user can use to recover their abandoned cart.
	 *
	 * @param int $pixelio_id The ID of the cart for which to generate the recovery link.
	 *
	 * @return string The full URL to recover the cart, including the unique token as a query parameter.
	 */
	public function pixelio_cart_abandon_recovery_more_generate_cart_recovery_link($pixelio_id): string
	{

		$pixelio_token = bin2hex(random_bytes(16));
		$this->pixelio_cart_repo->pixelio_cart_abandon_recovery_more_update_if_exist($pixelio_id, $pixelio_token);
		return $this->pixelio_wordpress_wrapper->pixelio_add_query_arg(
			array(
				'recover_cart' => $pixelio_token,
				'template_id' => $pixelio_id,
			),
			$this->pixelio_wordpress_wrapper->pixelio_home_url('/')
		);
	}

	/**
	 * Generate a review link for the first product in an order.
	 *
	 * This method retrieves the WooCommerce order by its ID and returns a link
	 * to the product page with the "#reviews" anchor, allowing the user to leave a review.
	 * if the order does not exist or has no products, it returns an empty string .
	 *
	 * @param int | mixed $pixelio_order_id The WooCommerce order ID .
	 *
	 * @return string The URL to the product's review section, or an empty string if not available.
	 */
	public function pixelio_cart_abandon_recovery_more_generate_review_link(mixed $pixelio_order_id): string
	{
		$pixelio_order = $this->pixelio_woocommerce_wrapper->pixelio_wc_get_order($pixelio_order_id);
		if (!$pixelio_order) {
			return '';
		}

		foreach ($pixelio_order->get_items() as $pixelio_item) {
			$pixelio_product_id = $pixelio_item->get_product_id();
			if ($pixelio_product_id) {
				return $this->pixelio_wordpress_wrapper->pixelio_get_permalink($pixelio_product_id) . '#reviews';
			}
		}
		return '';
	}

	/**
	 * Generate an unsubscribe link for a given email address.
	 *
	 * @param string $pixelio_email User email
	 * @param string $pixelio_expire Expiration string compatible with strtotime (default '+30 days')
	 *
	 * @return string|null Encoded unsubscribe URL, or null if no email
	 */
	public function pixelio_cart_abandon_recovery_more_generate_unsubscription_link($pixelio_email, $pixelio_expire = '+30 days'): ?string
	{

		if (!$pixelio_email) {
			return null;
		}

		$secret = AUTH_KEY;
		$pixelio_timestamp = strtotime($pixelio_expire);
		$data = $pixelio_email . '|' . $pixelio_timestamp;
		$pixelio_sig = hash_hmac('sha256', $data, $secret);

		$pixelio_unsubscribe_url = $this->pixelio_wordpress_wrapper->pixelio_add_query_arg(
			array(
				'unsubscribe' => rawurlencode($pixelio_email),
				'exp' => $pixelio_timestamp,
				'sig' => $pixelio_sig,
			),
			$this->pixelio_wordpress_wrapper->pixelio_home_url('/')
		);

		return rawurlencode($pixelio_unsubscribe_url);
	}
}
