<?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_Cart_Repository;
use PixelioCartAbandonRecoveryMore\Frontend\Repositories\Pixelio_Cart_Abandon_Recovery_More_Email_Logs_Repository;
use PixelioCartAbandonRecoveryMore\Frontend\Repositories\Pixelio_Cart_Abandon_Recovery_More_Email_Templates_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_Builder_Service
{
	private Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $pixelio_wordpress_wrapper;
	private Pixelio_Cart_Abandon_Recovery_More_Util $pixelio_util;

	private Pixelio_Cart_Abandon_Recovery_More_Cart_Repository $pixelio_cart_repo;
	private Pixelio_Cart_Abandon_Recovery_More_Email_Coupon_Service $pixelio_email_coupon;
	private Pixelio_Cart_Abandon_Recovery_More_Email_Logger_Service $pixelio_email_logger;
	private Pixelio_Cart_Abandon_Recovery_More_Email_Sender_Service $pixelio_email_sender;
	private Pixelio_Cart_Abandon_Recovery_More_Email_Variable_Replacer_Service $pixelio_email_replacer;
	private Pixelio_Cart_Abandon_Recovery_More_Email_Logs_Repository $pixelio_email_log_repo;
	private Pixelio_Cart_Abandon_Recovery_More_Email_Templates_Repository $pixelio_email_template_repo;


	public function __construct($pixelio_wordpress_wrapper, $pixelio_util,
								$pixelio_cart_repo,
								$pixelio_email_coupon,
								$pixelio_email_logger,
								$pixelio_email_sender,
								$pixelio_email_replacer,
								$pixelio_email_log_repo,
								$pixelio_email_template_repo
	)
	{
		$this->pixelio_wordpress_wrapper = $pixelio_wordpress_wrapper;
		$this->pixelio_util = $pixelio_util;
		$this->pixelio_cart_repo = $pixelio_cart_repo;
		$this->pixelio_email_coupon = $pixelio_email_coupon;
		$this->pixelio_email_logger = $pixelio_email_logger;
		$this->pixelio_email_sender = $pixelio_email_sender;
		$this->pixelio_email_replacer = $pixelio_email_replacer;
		$this->pixelio_email_log_repo = $pixelio_email_log_repo;
		$this->pixelio_email_template_repo = $pixelio_email_template_repo;
	}

	/**
	 * Process a batch of emails based on configuration
	 *
	 * @param array $pixelio_config Configuration options including dependency checks, email type, and status builder
	 *
	 * @return array Status results for each processed email
	 */
	public function pixelio_process_emails(array $pixelio_config): array
	{

		if (!$this->pixelio_util->pixelio_cart_abandon_recovery_more_dependency_is_checked($pixelio_config['dependency'])) {
			return [];
		}
		$pixelio_emails_of_abandon_to_send = $this->pixelio_fetch_all_email_templates_locally_or_remotely($pixelio_config);

		if (!is_array($pixelio_emails_of_abandon_to_send) ) {
			return [];
		}


		$pixelio_status_data = [];
		foreach ($pixelio_emails_of_abandon_to_send["emails"] as $pixelio_abandon_email) {
			$pixelio_data = $pixelio_abandon_email ?? [];

			$pixelio_recipient_info = $this->pixelio_email_sender->pixelio_prepare_recipient($pixelio_data, $pixelio_config);

			if (!$pixelio_recipient_info || empty($pixelio_recipient_info)) continue;

			$pixelio_coupon_code = $this->pixelio_email_coupon->pixelio_maybe_create_coupon($pixelio_data, $pixelio_config, $pixelio_recipient_info['email']);

			$pixelio_coupon_info["coupon_code"] = $pixelio_coupon_code;
			$pixelio_coupon_info["coupon_value"] = $pixelio_abandon_email["coupon_value"] ?? 0;
			$pixelio_coupon_info["coupon_type"] = $pixelio_abandon_email["coupon_type"] ?? 0;

			$pixelio_coupon_info["coupon_expiration"] = $pixelio_abandon_email["coupon_expiration"];


			list($pixelio_link, $pixelio_unsub_link) = $this->pixelio_prepare_email_template($pixelio_data, $pixelio_config, $pixelio_recipient_info, $pixelio_coupon_info);

			$this->pixelio_email_logger->pixelio_log_email($pixelio_data, $pixelio_config, $pixelio_recipient_info['email']);

			$pixelio_status_data[] = $pixelio_config['status_builder']($pixelio_data, $pixelio_link, $pixelio_unsub_link);
		}

		return $pixelio_status_data;
	}

	private function pixelio_fetch_all_email_templates_locally_or_remotely(array $pixelio_config)
	{
		if ($this->pixelio_util->pixelio_cart_abandon_recovery_more_decrypt_api_key("pixelio_api_key")
		&& (((string)$pixelio_config['type_of_email']) === '1')) {
			$is_ia = $this->pixelio_util->pixelio_cart_abandon_recovery_more_dependency_is_checked("ia-setup-mode");


			$data["type"] = $pixelio_config["type_of_email"];
			$data["cartStatus"] = $pixelio_config["status"];
			$data["isIa"] = $is_ia;
			$data["withDiscount"] = $pixelio_config["with_discount"];
			return $pixelio_config['method'] === 'POST'
				? $this->pixelio_util->pixelio_cart_abandon_recovery_more_call_api(
					$this->pixelio_util->pixelio_cart_abandon_recovery_more_get_url() . $pixelio_config['endpoint'],
					'POST',
					$data
				)
				: $this->pixelio_util->pixelio_cart_abandon_recovery_more_call_api(
					$this->pixelio_util->pixelio_cart_abandon_recovery_more_get_url() . $pixelio_config['endpoint'],
					"GET",
					$data
				);
		}

		return ["emails"=>$this->pixelio_get_local_template_emails($pixelio_config['type_of_email'], $pixelio_config['status'])];
	}

	private
	function pixelio_get_local_template_emails(string $pixelio_email_type, string $pixelio_status): array
	{
		$pixelio_emails = $this->pixelio_cart_abandon_recovery_more_get_all_email_template_to_send(
			$pixelio_email_type,
			$pixelio_status
		);

		if ($this->pixelio_wordpress_wrapper->pixelio_is_wp_error($pixelio_emails)) {

			return [];
		}

		if ( !is_array($pixelio_emails)) {

			return [];
		}


		return $pixelio_emails;
	}

	private
	function pixelio_cart_abandon_recovery_more_get_all_email_template_to_send($pixelio_cart_abandon_and_more_type, $pixelio_cart_abandon_and_more_status): array
	{
		$pixelio_abandon_cart_recovery_more_email_scheduler = new Pixelio_Cart_Abandon_Recovery_More_Email_Scheduler_Service($this->pixelio_wordpress_wrapper, $this->pixelio_cart_repo, $this->pixelio_email_log_repo,
			$this->pixelio_email_template_repo);
		return $pixelio_abandon_cart_recovery_more_email_scheduler->pixelio_get_emails_to_send($pixelio_cart_abandon_and_more_type, $pixelio_cart_abandon_and_more_status);
	}

	private
	function pixelio_prepare_email_template(array $pixelio_data, array $pixelio_config, array $pixelio_recipient_info,  $pixelio_coupon_info): array
	{
		return $this->pixelio_email_template(
			$pixelio_data['template_id'] ?? 0,
			$pixelio_recipient_info['email'],
			$pixelio_data['content'] ?? '',
			$pixelio_coupon_info,
			$pixelio_data['cart_id']  ?? 0,
			$pixelio_data['subject'] ?? '',
			$pixelio_config['type_of_email'],
			$pixelio_data['order_id'] ?? null,
			$pixelio_data['uuid'] ?? ''
		);
	}

	private function pixelio_email_template($pixelio_id, ?string $pixelio_recipient, mixed $pixelio_content, $pixelio_coupon_info, mixed $pixelio_cart_id, mixed $pixelio_subject, mixed $pixelio_type, $pixelio_order_id, $pixelio_uuid): array
	{

		if ($pixelio_recipient) {
			$pixelio_link = $this->pixelio_util->pixelio_cart_abandon_recovery_more_get_url() . 'email-click?email_template_id=' . $pixelio_id . '&redirect=' . $this->pixelio_email_replacer->pixelio_cart_abandon_recovery_more_generate_cart_recovery_link($pixelio_cart_id);

			if (2 === $pixelio_type) {
				$pixelio_link = $this->pixelio_util->pixelio_cart_abandon_recovery_more_get_url() . 'email-click?email_template_id=' . $pixelio_id . '&redirect=' . $this->pixelio_email_replacer->pixelio_cart_abandon_recovery_more_generate_review_link($pixelio_order_id);
			}
			$pixelio_unsubscribed_link = $this->pixelio_util->pixelio_cart_abandon_recovery_more_get_url() . 'email-click?email_template_id=' . $pixelio_id . '&redirect=' . $this->pixelio_email_replacer->pixelio_cart_abandon_recovery_more_generate_unsubscription_link($pixelio_recipient);
			$pixelio_tracking_url = $this->pixelio_util->pixelio_cart_abandon_recovery_more_get_url() . 'pixel-tracking?email_template_id=' . $pixelio_id;

			$pixelio_content = $this->pixelio_email_replacer->pixelio_replace_email_variables($pixelio_content, $pixelio_order_id, $pixelio_coupon_info, $pixelio_link, $pixelio_unsubscribed_link, $pixelio_link, $pixelio_type == 1 ? "abandoned_cart" : "review_cart", false, $pixelio_uuid);
			$pixelio_subject = $this->pixelio_email_replacer->pixelio_replace_email_variables($pixelio_subject, $pixelio_order_id, $pixelio_coupon_info, $pixelio_link, $pixelio_unsubscribed_link, $pixelio_link, $pixelio_type == 1 ? "abandoned_cart" : "review_cart", false, $pixelio_uuid);
			$this->pixelio_util->pixelio_cart_abandon_recovery_more_send_email_to($pixelio_recipient, $pixelio_subject, $pixelio_content, $pixelio_coupon_info["coupon_code"], $pixelio_link, $pixelio_unsubscribed_link, $pixelio_tracking_url, $pixelio_type);

			return array( $pixelio_link, $pixelio_unsubscribed_link);

		}
		return array(null, null, null);

	}
}
