<?php

namespace PixelioCartAbandonRecoveryMore\Admin\Services;


use PixelioCartAbandonRecoveryMore\Admin\Wrapper\Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper;
use PixelioCartAbandonRecoveryMore\Frontend\Repositories\Pixelio_Cart_Abandon_Recovery_More_User_Consent_Repository;
use PixelioCartAbandonRecoveryMore\Frontend\Repositories\Pixelio_Cart_Abandon_Recovery_More_Uuid_Repository;
use PixelioCartAbandonRecoveryMore\Includes\Utils\Pixelio_Cart_Abandon_Recovery_More_Util;

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_Sender_Service
{
	/**
	 * WordPress abstraction layer (POST, sanitize, esc_html, etc).
	 *
	 * @var object
	 */
	private Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $pixelio_wordpress_wrapper;

	/**
	 * Pixelio utility service (options + business logic).
	 *
	 * @var object
	 */
	private Pixelio_Cart_Abandon_Recovery_More_Util $pixelio_util;





	private Pixelio_Cart_Abandon_Recovery_More_Email_Variable_Replacer_Service $pixelio_email_replacer;

	/**
	 * Constructor
	 *
	 * @param object $pixelio_wordpress_wrapper WordPress wrapper
	 * @param object $pixelio_util Plugin utility service
	 * @param object $woocommerce_wrapper WooCommerce wrapper
	 */
	public function __construct(Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $pixelio_wordpress_wrapper, Pixelio_Cart_Abandon_Recovery_More_Util $pixelio_util, Pixelio_Cart_Abandon_Recovery_More_Email_Variable_Replacer_Service $pixelio_email_replacer)
	{
		$this->pixelio_wordpress_wrapper = $pixelio_wordpress_wrapper;
		$this->pixelio_util = $pixelio_util;

		$this->pixelio_email_replacer = $pixelio_email_replacer;
	}


	/**
	 * Sends a test email or email from POST parameters
	 *
	 * Retrieves recipient, subject, content, and coupon from POST,
	 * replaces template variables, and sends the email.
	 *
	 * @return bool True if sent successfully, false otherwise
	 */
	public function pixelio_get_recovery_more_send_email_to(): bool
	{
		$recipient = $this->pixelio_wordpress_wrapper->pixelio_sanitize_email(
			$this->pixelio_wordpress_wrapper->pixelio_get_post('recipient')
		);

		$pixelio_subject = $this->pixelio_wordpress_wrapper->pixelio_sanitize_text_field(
			$this->pixelio_wordpress_wrapper->pixelio_get_post('subject')
		);

		$pixelio_content = $this->pixelio_wordpress_wrapper->pixelio_wp_kses_post(
			$this->pixelio_wordpress_wrapper->pixelio_get_post('content')
		);

		$pixelio_coupon["value"] = $this->pixelio_wordpress_wrapper->pixelio_sanitize_text_field(
			$this->pixelio_wordpress_wrapper->pixelio_get_post('coupon')
		);

		$pixelio_coupon["expire_value"] = $this->pixelio_wordpress_wrapper->pixelio_sanitize_text_field(
			$this->pixelio_wordpress_wrapper->pixelio_get_post('coupon_value', 48 * 60 * 60 * 1000)
		);

		$pixelio_coupon["type"] = $this->pixelio_wordpress_wrapper->pixelio_sanitize_text_field(
			$this->pixelio_wordpress_wrapper->pixelio_get_post('coupon_type')
		);

		$pixelio_type_of_email = $this->pixelio_wordpress_wrapper->pixelio_sanitize_text_field(
			$this->pixelio_wordpress_wrapper->pixelio_get_post('type_of_email')
		);

		$pixelio_cart_abandon_recovery_more_email_template_id = $this->pixelio_wordpress_wrapper->pixelio_sanitize_text_field(
			$this->pixelio_wordpress_wrapper->pixelio_get_post('id')
		);

		$pixelio_content = $this->pixelio_email_replacer->pixelio_replace_email_variables($pixelio_content, null, $pixelio_coupon, "", "", "", $pixelio_type_of_email, true, "");

		$pixelio_subject = $this->pixelio_email_replacer->pixelio_replace_email_variables($pixelio_subject, null, $pixelio_coupon, "", "", "", $pixelio_type_of_email, true, "");
		$pixelio_sent = $this->pixelio_util->pixelio_cart_abandon_recovery_more_send_email_to($recipient, $pixelio_subject, $pixelio_content, '', '', "", "", $pixelio_cart_abandon_recovery_more_email_template_id);
		return $pixelio_sent;
	}

	public function pixelio_prepare_recipient(array $pixelio_data, array $pixelio_config): ?array
	{

		if (!$this->pixelio_can_send($pixelio_data, $pixelio_config)) {
			return null;
		}

		$pixelio_email = $this->pixelio_resolve_recipient_email($pixelio_data, $pixelio_config);

		if (empty($pixelio_email)) {
			return [];
		}

		return ['email' => $pixelio_email];
	}

	public  function pixelio_can_send(array $pixelio_data, array $pixelio_config): bool
	{
		$pixelio_is_ia_allowed = $this->pixelio_util
			->pixelio_cart_abandon_recovery_more_dependency_is_checked("ia-setup-mode");

//		$pixelio_is_promo_code_allowed = $this->pixelio_util
//			->pixelio_cart_abandon_recovery_more_dependency_is_checked($pixelio_config["coupon_dependency"]);
		return $this->pixelio_should_send_email(
			$pixelio_is_ia_allowed,
			$pixelio_data['is_ia'] ?? '',
			true,
			$pixelio_data["coupon_value"],
			$pixelio_data['language'] ?? ''
		);
	}

	/**
	 * Final condition
	 */
	function pixelio_should_send_email(bool $pixelio_is_ia_allowed, bool $pixelio_is_ia, bool $pixelio_is_promo_code_allowed,$pixelio_coupon_type, string $pixelio_user_language): bool
	{

		return (($this->pixelio_is_ia_and_promo_ok($pixelio_is_ia_allowed, $pixelio_is_ia, $pixelio_is_promo_code_allowed, $pixelio_coupon_type)
				|| $this->pixelio_is_ia_not_allowed($pixelio_is_ia_allowed, $pixelio_is_ia)
			|| 	$this->pixelio_is_promo_valid($pixelio_is_promo_code_allowed, $pixelio_coupon_type))
			&& $this->pixelio_is_language_ok($pixelio_user_language));
	}

	/**
	 * Check if IA & promo conditions are satisfied
	 */
	function pixelio_is_ia_and_promo_ok(bool $pixelio_is_ia_allowed, bool $pixelio_is_ia, bool $pixelio_is_promo_code_allowed, $coupon_value): bool
	{
		return $this->pixelio_is_ia_active($pixelio_is_ia_allowed, $pixelio_is_ia) &&
			$this->pixelio_is_promo_valid($pixelio_is_promo_code_allowed, $coupon_value);
	}

	/**
	 * Check if IA (intelligence artificielle) is allowed and active
	 */
	function pixelio_is_ia_active( $pixelio_is_ia_allowed,  $pixelio_is_ia): bool
	{
		return $pixelio_is_ia_allowed == 1 && $pixelio_is_ia == 1;
	}

	/**
	 * Check if the promo code condition is satisfied
	 */
	function pixelio_is_promo_valid( $pixelio_is_promo_code_allowed,  $coupon_value): bool
	{
		return ($pixelio_is_promo_code_allowed && ($coupon_value!=0) ) || (!$pixelio_is_promo_code_allowed && ($coupon_value==0));
	}

	/**
	 * Check if IA is not allowed
	 */
	function pixelio_is_ia_not_allowed($pixelio_is_ia_allowed, $pixelio_is_ia): bool
	{

		return !$pixelio_is_ia_allowed && !$pixelio_is_ia ;
	}

	/**
	 * Check if language matches
	 */
	function pixelio_is_language_ok(string $pixelio_user_language): bool
	{
		$pixelio_current_locale = substr($this->pixelio_util->pixelio_cart_abandon_recovery_more_get_locale(), 0, 2);

		return strtolower($pixelio_user_language) === strtolower($pixelio_current_locale);
	}

	private function pixelio_resolve_recipient_email(array $pixelio_data, array $pixelio_config): ?string
	{
		$pixelio_uuid_model = new Pixelio_Cart_Abandon_Recovery_More_Uuid_Repository($this->pixelio_wordpress_wrapper);
		$pixelio_user_model = new Pixelio_Cart_Abandon_Recovery_More_User_Consent_Repository($this->pixelio_wordpress_wrapper);

		// 📦 Cas abandon cart
		if ($pixelio_config['type'] === 'abandon') {

			$pixelio_user_id = $pixelio_uuid_model
				->pixelio_get_user_id_by_uuid($pixelio_data['uuid'] ?? '');

			if (!$pixelio_user_id) {
				return null;
			}

			$user_email = $pixelio_user_model->pixelio_get_email_by_user_id($pixelio_user_id);

			if (empty($user_email) || !$pixelio_user_model->pixelio_is_subscribed($user_email, "Cart")) {
				return null;
			}

			return $pixelio_user_model->pixelio_get_email_by_user_id($pixelio_user_id);
		}

		$pixelio_order_id = $pixelio_data['order_id'] ?? 0;

		if (!$pixelio_order_id) {
			return "";
		}

		$pixelio_order = wc_get_order($pixelio_order_id);
		$pixelio_email = $pixelio_order?->get_billing_email();

		if (!$pixelio_email) {
			return "";
		}

		return $pixelio_user_model->pixelio_is_subscribed($pixelio_email, "review")
			? $pixelio_email
			: "";
	}


}
