<?php
/**
 * Ajax Controller for Pixelio Cart Abandon Recovery More.
 *
 * Handles all AJAX requests for cart abandon recovery, user consent,
 * temporary coupons, and tracking user actions on pages.
 *
 * @package PixelioCartAbandonRecoveryMore
 * @version 0.1
 */

namespace PixelioCartAbandonRecoveryMore\Frontend\Controllers;

use JetBrains\PhpStorm\NoReturn;
use PixelioCartAbandonRecoveryMore\Admin\Sanitizers\Pixelio_Cart_Abandon_Recovery_More_Request_Sanitizer;
use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Email_Coupon_Service;
use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Order_Service;
use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Uuid_Service;
use PixelioCartAbandonRecoveryMore\Admin\Validator\Pixelio_Cart_Abandon_Recovery_More_Coupon_Validator;
use PixelioCartAbandonRecoveryMore\Admin\Validator\Pixelio_Cart_Abandon_Recovery_More_Template_Validator;
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\Dispatchers\Pixelio_Cart_Abandon_Recovery_More_Wishlist_Event_Dispatcher;
use PixelioCartAbandonRecoveryMore\Frontend\Repositories\Pixelio_Cart_Abandon_Recovery_More_Cart_Item_Repository;
use PixelioCartAbandonRecoveryMore\Frontend\Repositories\Pixelio_Cart_Abandon_Recovery_More_Cart_Repository;
use PixelioCartAbandonRecoveryMore\Frontend\Repositories\Pixelio_Cart_Abandon_Recovery_More_Email_Templates_Repository;
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\Frontend\Repositories\Pixelio_Cart_Abandon_Recovery_More_Wishlist_Repository;
use PixelioCartAbandonRecoveryMore\Frontend\Services\Pixelio_Cart_Abandon_Recovery_More_Delivery_Estimator_Service;
use PixelioCartAbandonRecoveryMore\Frontend\Services\Pixelio_Cart_Abandon_Recovery_More_Wishlist_Service;
use PixelioCartAbandonRecoveryMore\Includes\Utils\Pixelio_Cart_Abandon_Recovery_More_Util;

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

/**
 * Class Pixelio_Cart_Abandon_Recovery_More_Ajax_Controller
 *
 * Handles AJAX requests for cart abandonment and user interactions.
 *
 * @package PixelioCartAbandonRecoveryMore
 * @version 0.1
 */
class Pixelio_Cart_Abandon_Recovery_More_Ajax_Controller extends Pixelio_Cart_Abandon_Recovery_More_General_Controller
{

	private Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $wordpress_wrapper;
	private Pixelio_Cart_Abandon_Recovery_More_Woocommerce_Wrapper $woocommerce_wrapper;
	private Pixelio_Cart_Abandon_Recovery_More_Cart_Item_Repository $cart_item_repo;

	private Pixelio_Cart_Abandon_Recovery_More_Order_Service $pixelio_order_service;
	private Pixelio_Cart_Abandon_Recovery_More_Email_Coupon_Service $pixelio_coupon_service;
	private Pixelio_Cart_Abandon_Recovery_More_User_Consent_Repository $user_consent_repo;
	private Pixelio_Cart_Abandon_Recovery_More_Uuid_Service $uuid_service;
	private Pixelio_Cart_Abandon_Recovery_More_Wishlist_Event_Dispatcher $dispatcher;
	private Pixelio_Cart_Abandon_Recovery_More_Wishlist_Service $wishlist_service;
	private Pixelio_Cart_Abandon_Recovery_More_Wishlist_Repository $wishlist_repository;


	/**
	 * Pixelio AJAX controller constructor.
	 *
	 * Registers AJAX hooks for cart, coupon, and user consent actions.
	 */
	public function __construct($pixelio_util, Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $wordpress_wrapper,
								Pixelio_Cart_Abandon_Recovery_More_Woocommerce_Wrapper $woocommerce_wrapper,
								Pixelio_Cart_Abandon_Recovery_More_Cart_Item_Repository $cart_item_repo,
								Pixelio_Cart_Abandon_Recovery_More_Order_Service $pixelio_order_service,
								Pixelio_Cart_Abandon_Recovery_More_Email_Coupon_Service $pixelio_coupon_service,
								Pixelio_Cart_Abandon_Recovery_More_User_Consent_Repository $user_consent_repo,
								Pixelio_Cart_Abandon_Recovery_More_Uuid_Service $uuid_Service,
								Pixelio_Cart_Abandon_Recovery_More_Cart_Repository $cart_repo,
								Pixelio_Cart_Abandon_Recovery_More_Wishlist_Service $wishlist_service,
								Pixelio_Cart_Abandon_Recovery_More_Wishlist_Event_Dispatcher $dispatcher,
								Pixelio_Cart_Abandon_Recovery_More_Wishlist_Repository $wishlist_repository,)
	{
		$this->woocommerce_wrapper = $woocommerce_wrapper;
		$this->pixelio_util = $pixelio_util;
		$this->cart_model = $cart_repo;
		$this->wordpress_wrapper = $wordpress_wrapper;
		$this->cart_item_repo = $cart_item_repo;
		$this->pixelio_order_service = $pixelio_order_service;
		$this->pixelio_coupon_service = $pixelio_coupon_service;
		$this->user_consent_repo = $user_consent_repo;
		$this->uuid_service = $uuid_Service;
		$this->dispatcher = $dispatcher;
		$this->wishlist_service = $wishlist_service;
		$this->wishlist_repository = $wishlist_repository;
		parent::__construct($wordpress_wrapper, $pixelio_util);
		$this->pixelio_cart_abandon_recovery_more_add_ajax();
	}

	/**
	 * Register all AJAX actions.
	 */
	public function pixelio_cart_abandon_recovery_more_add_ajax(): void
	{

		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_pixelio_cart_abandon_recovery_more_create_temporary_coupon', array($this, 'pixelio_cart_abandon_recovery_more_create_temporary_coupon'));
		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_nopriv_pixelio_cart_abandon_recovery_more_create_temporary_coupon', array($this, 'pixelio_cart_abandon_recovery_more_create_temporary_coupon'));

		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_pixelio_cart_abandon_recovery_more_get_uuid', array($this, 'pixelio_cart_abandon_recovery_more_get_uuid'));
		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_nopriv_pixelio_cart_abandon_recovery_more_get_uuid', array($this, 'pixelio_cart_abandon_recovery_more_get_uuid'));


		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_pixelio_cart_abandon_recovery_more_save_three', array($this, 'pixelio_cart_abandon_recovery_more_save_user_consent'));
		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_nopriv_pixelio_cart_abandon_recovery_more_save_three', array($this, 'pixelio_cart_abandon_recovery_more_save_user_consent'));

		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_pixelio_cart_abandon_recovery_more_save_four', array($this, 'pixelio_cart_abandon_recovery_more_save_user_action_on_page'));
		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_nopriv_pixelio_cart_abandon_recovery_more_save_four', array($this, 'pixelio_cart_abandon_recovery_more_save_user_action_on_page'));

		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_pixelio_cart_abandon_recovery_more_clear_cart', array($this, 'pixelio_cart_abandon_recovery_more_clear_cart'));
		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_nopriv_pixelio_cart_abandon_recovery_more_clear_cart', array($this, 'pixelio_cart_abandon_recovery_more_clear_cart'));

		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_pixelio_cart_abandon_recovery_more_check_bought', array($this, 'pixelio_cart_abandon_recovery_more_is_bought'));
		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_nopriv_pixelio_cart_abandon_recovery_more_check_bought', array($this, 'pixelio_cart_abandon_recovery_more_is_bought'));

		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_pixelio_cart_abandon_recovery_more_is_cart_empty', array($this, 'pixelio_cart_abandon_recovery_more_is_cart_empty'));
		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_nopriv_pixelio_cart_abandon_recovery_more_is_cart_empty', array($this, 'pixelio_cart_abandon_recovery_more_is_cart_empty'));

		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_pixelio_cart_abandon_recovery_more_is_consent_gived', array($this, 'pixelio_cart_abandon_recovery_more_is_consent_gived'));
		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_nopriv_pixelio_cart_abandon_recovery_more_is_consent_gived', array($this, 'pixelio_cart_abandon_recovery_more_is_consent_gived'));

//todo remove
//		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_pixelio_cart_abandon_recovery_more_newsletter_signup', array($this, 'pixelio_cart_abandon_recovery_more_create_temporary_coupon'));
//		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_nopriv_pixelio_cart_abandon_recovery_more_newsletter_signup', array($this, 'pixelio_cart_abandon_recovery_more_create_temporary_coupon'));

		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_pixelio_cart_abandon_recovery_more_save_email_template', array($this, 'pixelio_cart_abandon_recovery_more_save_email_template_ajax'));
		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_nopriv_pixelio_cart_abandon_recovery_more_save_email_template', array($this, 'pixelio_cart_abandon_recovery_more_save_email_template_ajax'));


		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_pixelio_cart_abandon_recovery_more_remove_email_template', array($this, 'pixelio_cart_abandon_recovery_more_remove_email_template_ajax'));
		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_nopriv_pixelio_cart_abandon_recovery_more_remove_email_template', array($this, 'pixelio_cart_abandon_recovery_more_remove_email_template_ajax'));


		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_pixelio_calculate_delivery', array($this, 'pixelio_calculate_delivery'));
		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_nopriv_pixelio_calculate_delivery', array($this, 'pixelio_calculate_delivery'));

		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_add_to_wishlist', array($this, 'pixelio_add_to_wishlist'));
		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_nopriv_add_to_wishlist', array($this, 'pixelio_add_to_wishlist'));

		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_wishlist_check_status', array($this, 'pixelio_wishlist_check_status'));
		$this->wordpress_wrapper->pixelio_add_action('wp_ajax_nopriv_wishlist_check_status', array($this, 'pixelio_wishlist_check_status'));
	}

	public function pixelio_wishlist_check_status(): void
	{
		$product_id = (int)$this->wordpress_wrapper->pixelio_sanitize_text_field($_POST['pixelio_wishlist_product_id'] ?? '');
		$email = $this->wordpress_wrapper->pixelio_sanitize_email($_POST['pixelio_wishlist_email'] ?? '');
		$identity = $this->wishlist_service->check($email);
		$in_wishlist = !isset($identity['requires_email'])
			&& $this->wishlist_repository->exists($product_id, $identity['user_id']);

		$this->wordpress_wrapper->pixelio_wp_send_json_success(['in_wishlist' => $in_wishlist]);
		$this->wordpress_wrapper->pixelio_wp_die();
	}

	public function pixelio_add_to_wishlist(): void
	{
		if (!check_ajax_referer('pixelio_ajax_nonce', 'nonce', false)) {
			$this->wordpress_wrapper->pixelio_wp_send_json_error(['message' => $this->wordpress_wrapper->pixelio_esc_html__('Invalid request.')], 403);
			$this->wordpress_wrapper->pixelio_wp_die();
		}

		$utm_source   = $this->pixelio_util->pixelio_get_post_value('utm_source');
		$utm_campaign = $this->pixelio_util->pixelio_get_post_value('utm_campaign');
		$utm_medium   = $this->pixelio_util->pixelio_get_post_value('utm_medium');

		$uuid = $this->uuid_service->ensure_uuid($utm_source,
			$utm_campaign,$utm_medium);

		$product_id = isset($_POST['pixelio_wishlist_product_id'])
			? absint($_POST['pixelio_wishlist_product_id'])
			: 0;

		$email = isset($_POST['pixelio_wishlist_email'])
			? sanitize_email(wp_unslash($_POST['pixelio_wishlist_email']))
			: '';

		$action_type = isset($_POST['pixelio_wishlist_action_type'])
			? sanitize_key(wp_unslash($_POST['pixelio_wishlist_action_type']))
			: 'add';


		if (!$product_id) {
			$this->wordpress_wrapper->pixelio_wp_send_json_error(['message' => $this->wordpress_wrapper->pixelio_esc_html__('Invalid Product.')], 400);
			$this->wordpress_wrapper->pixelio_wp_die();
		}

		if (empty($email) || !is_email($email)) {
			$this->wordpress_wrapper->pixelio_wp_send_json_error(['message' => $this->wordpress_wrapper->pixelio_esc_html__('Valid email is required.')], 422);
			$this->wordpress_wrapper->pixelio_wp_die();
		}


		$already_has_consent = $this->user_consent_repo->pixelio_is_subscribed($email, Pixelio_Cart_Abandon_Recovery_More_Util::$finalite_wishlist);
		if ($this->pixelio_util->pixelio_cart_abandon_recovery_more_dependency_is_checked('pixelio-cart-abandon-recovery-more-gdpr-consent-checkbox')) {
			$consent_definition = isset($_POST['pixelio_wishlist_gdpr_label'])
				? $this->wordpress_wrapper->pixelio_sanitize_text_field(
					$this->wordpress_wrapper->pixelio_wp_unslash($_POST['pixelio_wishlist_gdpr_label'])
				)
				: '';



			if (empty($consent_definition) && !$already_has_consent) {
				$this->wordpress_wrapper->pixelio_wp_send_json_error(['message' => $this->wordpress_wrapper->pixelio_esc_html__('GDPR label is required.')], 422);
				$this->wordpress_wrapper->pixelio_wp_die();
			}
			if (!empty($consent_definition) && !$already_has_consent) {
				$this->register_user_consent(
					$email,
					$uuid,
					Pixelio_Cart_Abandon_Recovery_More_Util::$finalite_wishlist,
					$consent_definition
					,$utm_source,
					$utm_campaign,$utm_medium
				);
			}
		}else if(!$already_has_consent && !$this->pixelio_util->pixelio_cart_abandon_recovery_more_dependency_is_checked('pixelio-cart-abandon-recovery-more-gdpr-consent-checkbox')){
			$this->register_user_consent(
				$email,
				$uuid,
				Pixelio_Cart_Abandon_Recovery_More_Util::$finalite_wishlist,
				Pixelio_Cart_Abandon_Recovery_More_Util::$gdpr_not_active
				,$utm_source,
				$utm_campaign,$utm_medium
			);
		}
		$identity = $this->wishlist_service->check($email);
		if (isset($identity['error'])) {
			$this->wordpress_wrapper->pixelio_wp_send_json_error(['message' => $identity['error']], 422);
			$this->wordpress_wrapper->pixelio_wp_die();
		}

		if ($action_type === 'remove') {
			$removed = $this->wishlist_repository->remove(
				$product_id,
				$identity['user_id'],
			);

			if ($removed) {
				$this->dispatcher->dispatch('item_removed', $email, $identity);
			}

			$this->wordpress_wrapper->pixelio_wp_send_json_success([
				'action' => 'removed',
				'removed' => $removed,
				'message' => $this->wordpress_wrapper->pixelio_esc_html__('Removed from your wishlist.', 'pixelio'),
			]);

			$this->wordpress_wrapper->pixelio_wp_die();
		}



		$added = $this->wishlist_repository->add(
			$product_id,
			$identity['user_id'],
		);

		if ($added) {
			$this->dispatcher->dispatch('item_added', $email, $identity);
		}


		$this->wordpress_wrapper->pixelio_wp_send_json_success([
			'action' => 'added',
			'added' => $added,
			'message' => $this->wordpress_wrapper->pixelio_esc_html__('Your wishlist has been saved. A recovery email has been sent.', 'pixelio'),
		]);

		$this->wordpress_wrapper->pixelio_wp_die();
	}

	protected function register_user_consent(string $email, string $uuid, $finalite, string $consent_definition,$utm_source,
																							$utm_campaign,$utm_medium): void
	{
		$uuid_model = new Pixelio_Cart_Abandon_Recovery_More_Uuid_Repository($this->wordpress_wrapper);

		$existing = $this->user_consent_repo->pixelio_is_subscribed($email, $finalite);
		if ($existing) {
			throw new \RuntimeException('User already used this offer');
		}
		$user_id = $this->user_consent_repo->pixelio_save_consent($email, Pixelio_Cart_Abandon_Recovery_More_Util::$finalite_cart, $consent_definition, 1,$utm_source,
			$utm_campaign,$utm_medium);
		$this->user_consent_repo->pixelio_save_consent($email, Pixelio_Cart_Abandon_Recovery_More_Util::$finalite_review, $consent_definition, 1,$utm_source,
			$utm_campaign,$utm_medium);
		$uuid_model->pixelio_add_or_update_uuid($uuid, $user_id);
	}

	function pixelio_calculate_delivery(): void
	{
		check_ajax_referer('pixelio_ajax_nonce', 'nonce');

		$product_id = intval($_POST['product_id'] ?? 0);
		$postcode = sanitize_text_field($_POST['postcode'] ?? '');

		if (!$product_id || !$postcode) {
			$this->wordpress_wrapper->pixelio_wp_send_json_error('Paramètres invalides');
		}

		$service = new Pixelio_Cart_Abandon_Recovery_More_Delivery_Estimator_Service($this->woocommerce_wrapper);

		$result = $service->calculate($product_id, $postcode);

		if (isset($result['error'])) {
			$this->wordpress_wrapper->pixelio_wp_send_json_error($result['error']);
		}

		$this->wordpress_wrapper->pixelio_wp_send_json_success($result);
	}

	function pixelio_cart_abandon_recovery_more_remove_email_template_ajax(): void
	{

		$this->wordpress_wrapper->pixelio_check_ajax_referer("pixelio_toggle_nonce", "nonce");

		if (!$this->wordpress_wrapper->pixelio_current_user_can('manage_options')) {
			$this->wordpress_wrapper->pixelio_wp_send_json_error(['message' => 'Unauthorized'], 403);
		}

		$id = isset($_POST['id']) ? intval($_POST['id']) : 0;

		if (!$id) {
			$this->wordpress_wrapper->pixelio_wp_send_json_error(['message' => 'ID invalide'], 400);
		}

		$pixelio_Cart_Abandon_Recovery_More_Email_Templates_Model = new Pixelio_Cart_Abandon_Recovery_More_Email_Templates_Repository($this->wordpress_wrapper);
		$deleted = $pixelio_Cart_Abandon_Recovery_More_Email_Templates_Model->delete($id);


		if (!$deleted) {
			$this->wordpress_wrapper->pixelio_wp_send_json_error(['message' => 'Impossible de supprimer le template']);
		}
		$this->wordpress_wrapper->pixelio_do_action('pixelio_sync_tables_cron');
		$this->wordpress_wrapper->pixelio_wp_send_json_success(['message' => 'Template supprimé avec succès']);
	}

	/**
	 * Save or update email
	 *
	 */
	public function pixelio_cart_abandon_recovery_more_save_email_template_ajax(): void
	{
		$this->wordpress_wrapper->pixelio_check_ajax_referer('pixelio_toggle_nonce', 'nonce');

		if (!$this->wordpress_wrapper->pixelio_current_user_can('manage_options')) {
			$this->wordpress_wrapper->pixelio_wp_send_json_error(['message' => 'Unauthorized'], 403);
			$this->wordpress_wrapper->pixelio_wp_die();
		}

		$sanitizer = new Pixelio_Cart_Abandon_Recovery_More_Request_Sanitizer($this->wordpress_wrapper);
		$data = $sanitizer->pixelio_sanitize_request($_POST);

		if (!empty($_POST['body_json'])) {
			$raw_body_json = wp_unslash($_POST['body_json']);
			$decoded = json_decode($raw_body_json, true);

			if (json_last_error() !== JSON_ERROR_NONE || !is_array($decoded)) {
				$this->wordpress_wrapper->pixelio_wp_send_json_error([
					'message' => 'Invalid email template JSON'
				], 400);
				$this->wordpress_wrapper->pixelio_wp_die();
			}

			$data['body_json'] = wp_json_encode($decoded);
		}

		if (empty($data['body_json']) && empty($data['body_html'])) {
			$this->wordpress_wrapper->pixelio_wp_send_json_error([
				'message' => 'Template body is required'
			], 400);
			$this->wordpress_wrapper->pixelio_wp_die();
		}

		$pixelio_template_validator = new Pixelio_Cart_Abandon_Recovery_More_Template_Validator(
			$this->wordpress_wrapper,
			$this->pixelio_util
		);

		$data = $pixelio_template_validator->pixelio_validate_template_data($data);

		$email_templates = new Pixelio_Cart_Abandon_Recovery_More_Email_Templates_Repository($this->wordpress_wrapper);
		$result = $email_templates->pixelio_add_or_update_email($data);

		if ($this->wordpress_wrapper->pixelio_is_wp_error($result)) {
			$this->wordpress_wrapper->pixelio_wp_send_json_error([
				'message' => $result->getMessage()
			]);
			$this->wordpress_wrapper->pixelio_wp_die();
		}

		$this->wordpress_wrapper->pixelio_do_action('pixelio_sync_tables_cron');

		$this->wordpress_wrapper->pixelio_wp_send_json_success([
			'message' => $this->wordpress_wrapper->pixelio_translate(
				'Template saved successfully',
				'rivio-ai-cart-recovery-marketing-email-automation'
			),
			'data' => $result
		]);

		$this->wordpress_wrapper->pixelio_wp_die();
	}

	/**
	 * Verify if user consent is given.
	 *
	 * @return void
	 */
	#[NoReturn]
	public function pixelio_cart_abandon_recovery_more_is_consent_gived(): void
	{
		$this->wordpress_wrapper->pixelio_check_ajax_referer('pixelio_ajax_nonce', 'nonce');
		if (isset($_POST['uuid'])) {
			$uuid = $this->wordpress_wrapper->pixelio_sanitize_text_field($this->wordpress_wrapper->pixelio_wp_unslash($_POST['uuid']));
			$uuid_repo = new Pixelio_Cart_Abandon_Recovery_More_Uuid_Repository($this->wordpress_wrapper);
			$user_id = $uuid_repo->pixelio_get_user_id_by_uuid($uuid);
			$user_email = $this->user_consent_repo->pixelio_get_email_by_user_id($user_id);
			$consent = $this->user_consent_repo->pixelio_is_subscribed($user_email, Pixelio_Cart_Abandon_Recovery_More_Util::$finalite_cart);
			$this->wordpress_wrapper->pixelio_wp_send_json_success($consent);
		} else {
			$this->wordpress_wrapper->pixelio_wp_send_json_error('UUID doesn\'t exist.', 403);
		}

		$this->wordpress_wrapper->pixelio_wp_die();
	}

	/**
	 * Check if cart is empty.
	 *
	 * @return void
	 */
	#[NoReturn]
	public function pixelio_cart_abandon_recovery_more_is_cart_empty(): void
	{
		$this->wordpress_wrapper->pixelio_check_ajax_referer('pixelio_ajax_nonce', 'nonce');
		$this->wordpress_wrapper->pixelio_wp_send_json_success(WC()->cart->is_empty());
		$this->wordpress_wrapper->pixelio_wp_die();
	}

	/**
	 * Save user action on page.
	 *
	 * @return void
	 */
	#[NoReturn]
	public function pixelio_cart_abandon_recovery_more_save_user_action_on_page(): void
	{
		$this->wordpress_wrapper->pixelio_check_ajax_referer('pixelio_ajax_nonce', 'nonce');
		$this->wordpress_wrapper->pixelio_wp_die('not yet implemented');
	}

	/**
	 * Check if product is bought.
	 *
	 * @return void
	 */
	#[NoReturn]
	public function pixelio_cart_abandon_recovery_more_is_bought(): void
	{
		$this->wordpress_wrapper->pixelio_check_ajax_referer('pixelio_ajax_nonce', 'nonce');
		if ($this->pixelio_util->pixelio_cart_abandon_recovery_more_dependency_is_checked('pixelio-cart-abandon-recovery-more-show-others-buy-checkbox')) {
			$product_id = null;
			if (isset($_POST['product_id'])) {
				$product_id = $this->wordpress_wrapper->pixelio_sanitize_text_field($this->wordpress_wrapper->pixelio_wp_unslash($_POST['product_id']));
			}
			$this->pixelio_cart_abandon_recovery_more_get_recent_order_info(Pixelio_Cart_Abandon_Recovery_More_Util::$expiration_time_of_bought_popup, $product_id);
		}
		$this->wordpress_wrapper->pixelio_wp_die();
	}

	/**
	 * Get recent order info.
	 *
	 * @param int $minutes Time limit in minutes.
	 * @param int|null $product_id Optional product ID filter.
	 *
	 * @return void
	 */
	public function pixelio_cart_abandon_recovery_more_get_recent_order_info($minutes = 60, $product_id = null): void
	{
		$orders = $this->pixelio_order_service->pixelio_cart_abandon_recovery_more_get_recent_order($minutes);
		$order_info = $this->pixelio_order_service->pixelio_cart_abandon_recovery_more_format_orders($orders, $product_id);
		$this->wordpress_wrapper->pixelio_wp_send_json_success(
			$this->wordpress_wrapper->pixelio_wp_json_encode($order_info)
		);

		$this->wordpress_wrapper->pixelio_wp_die();
	}

	/**
	 * Clear cart.
	 *
	 * @return void
	 */
	#[NoReturn]
	public function pixelio_cart_abandon_recovery_more_clear_cart(): void
	{
		$this->wordpress_wrapper->pixelio_check_ajax_referer('pixelio_ajax_nonce', 'nonce');

		if (isset($_POST['uuid'])) {
			$this->woocommerce_wrapper->pixelio_empty_cart();
			$cart_id = $this->cart_model->pixelio_find_by_uuid(sanitize_text_field(wp_unslash($_POST['uuid'])));
			$this->cart_item_repo->pixelio_remove_all_item_by_cart_id($cart_id);
			$this->wordpress_wrapper->pixelio_wp_send_json_success('Cart cleared');
			$this->wordpress_wrapper->pixelio_wp_die();
		}
		$this->wordpress_wrapper->pixelio_wp_send_json_error('no nonce or uuid');
		$this->wordpress_wrapper->pixelio_wp_die();
	}

	/**
	 * Save user consent.
	 *
	 * @return void
	 */
	public function pixelio_cart_abandon_recovery_more_save_user_consent(): void
	{
		$this->wordpress_wrapper->pixelio_check_ajax_referer('pixelio_ajax_nonce', 'nonce');

		if (!isset($_POST['email'], $_POST['consent_status'], $_POST['uuid'], $_POST['consent_definition'])) {
			$this->wordpress_wrapper->pixelio_wp_send_json_error('');
		}

		$uuid = $this->wordpress_wrapper->pixelio_sanitize_text_field(
			$this->wordpress_wrapper->pixelio_wp_unslash($_POST['uuid'])
		);

		$utm_source   = $this->pixelio_util->pixelio_get_post_value('utm_source');
		$utm_campaign = $this->pixelio_util->pixelio_get_post_value('utm_campaign');
		$utm_medium   = $this->pixelio_util->pixelio_get_post_value('utm_medium');


		$email = $this->wordpress_wrapper->pixelio_sanitize_email(
			$this->wordpress_wrapper->pixelio_wp_unslash($_POST['email'])
		);

		$email = preg_replace('/\s+/', '', $email);

		$checked_raw = $this->wordpress_wrapper->pixelio_wp_unslash($_POST['consent_status']);
		$consent_definition = $this->wordpress_wrapper->pixelio_sanitize_text_field($_POST['consent_definition']);
		$checked = filter_var($checked_raw, FILTER_VALIDATE_BOOLEAN);

		$is_gdpr_active = $this->pixelio_util
			->pixelio_cart_abandon_recovery_more_dependency_is_checked('pixelio-cart-abandon-recovery-more-gdpr-consent-checkbox');

		if ($is_gdpr_active) {
			if (!$checked || empty($consent_definition)) {
				$this->wordpress_wrapper->pixelio_wp_send_json_error('Consent not given');
			}

			$finalite = Pixelio_Cart_Abandon_Recovery_More_Util::$finalite_cart;
		} else {
			$checked = true;
			$finalite = Pixelio_Cart_Abandon_Recovery_More_Util::$gdpr_not_active;
			$consent_definition = Pixelio_Cart_Abandon_Recovery_More_Util::$gdpr_not_active;
		}

		$user_id = $this->user_consent_repo->pixelio_save_consent(
			$email,
			$finalite,
			$consent_definition,
			$checked
			,$utm_source,
			$utm_campaign,$utm_medium
		);

		$uuid_model = new Pixelio_Cart_Abandon_Recovery_More_Uuid_Repository($this->wordpress_wrapper);
		$uuid_model->pixelio_add_or_update_uuid($uuid, $user_id);

		$this->wordpress_wrapper->pixelio_wp_send_json_success(
			$this->wordpress_wrapper->pixelio_translate(
				'Success'
			)
		);
	}

	/**
	 * Create temporary coupon.
	 *
	 * @return void
	 */
	public function pixelio_cart_abandon_recovery_more_create_temporary_coupon(): void
	{
		try {
			$this->wordpress_wrapper->pixelio_check_ajax_referer('pixelio_ajax_nonce', 'nonce');

			if (!class_exists('WC_Coupon')) {
				$this->wordpress_wrapper->pixelio_wp_send_json_error(['message' => $this->wordpress_wrapper->pixelio_translate('WooCommerce not active', 'rivio-ai-cart-recovery-marketing-email-automation')]);
			}
			$pixelio_coupon_validator = new Pixelio_Cart_Abandon_Recovery_More_Coupon_Validator($this->wordpress_wrapper, $this->pixelio_util);
			$email = $pixelio_coupon_validator->pixelio_cart_abandon_recovery_more_validate_email_and_uuid();
			$utm_source   = $this->pixelio_util->pixelio_get_post_value('utm_source');
			$utm_campaign = $this->pixelio_util->pixelio_get_post_value('utm_campaign');
			$utm_medium   = $this->pixelio_util->pixelio_get_post_value('utm_medium');

			$uuid = $this->uuid_service->ensure_uuid($utm_source,
				$utm_campaign,$utm_medium);
			$consent_definition = Pixelio_Cart_Abandon_Recovery_More_Util::$gdpr_not_active;
			if ($this->pixelio_util->pixelio_cart_abandon_recovery_more_dependency_is_checked('pixelio-cart-abandon-recovery-more-gdpr-consent-checkbox')) {
				$consent_definition = $this->wordpress_wrapper->pixelio_sanitize_text_field(
					$this->wordpress_wrapper->pixelio_wp_unslash($_POST['pixelio-cart-abandon-recovery-more-pop-up-rgpd-label'])
				);
			}
			$this->register_user_consent($email, $uuid,Pixelio_Cart_Abandon_Recovery_More_Util::$finalite_cart, $consent_definition,$utm_source,
			$utm_campaign,$utm_medium);
			$discount = $this->pixelio_util->pixelio_cart_abandon_recovery_more_dependency_get_input_content("pixelio-cart-abandon-recovery-more-use-promo-code-percent", false);
			if (!isset($_POST['save'])) {
				$coupon_code = $this->pixelio_coupon_service->pixelio_cart_abandon_recovery_more_create_coupon($email, $discount ?? null, 15, true);
				$this->wordpress_wrapper->pixelio_wp_send_json_success([
					'coupon_code' => $coupon_code,
					'expires_in' => $this->wordpress_wrapper->pixelio_translate('15 minutes'),
					'gdpr' => $this->pixelio_util->pixelio_cart_abandon_recovery_more_dependency_is_checked("pixelio-cart-abandon-recovery-more-gdpr-consent-checkbox")
				]);
			} else {
				$this->wordpress_wrapper->pixelio_wp_send_json_success(true);
			}


			$this->wordpress_wrapper->pixelio_wp_die();

		} catch (\Exception $e) {
			$this->wordpress_wrapper->pixelio_wp_send_json_error(['message' => $e->getMessage()]);
			$this->wordpress_wrapper->pixelio_wp_die();
		}
	}

	function pixelio_cart_abandon_recovery_more_get_uuid(): void
	{
		$this->wordpress_wrapper->pixelio_check_ajax_referer('pixelio_ajax_nonce', 'nonce');
		if ($this->wordpress_wrapper->pixelio_wc_get_session('uuid')) {
			$this->wordpress_wrapper->pixelio_wp_send_json_success(sanitize_text_field(wp_unslash($this->wordpress_wrapper->pixelio_wc_get_session('uuid'))));
			$this->wordpress_wrapper->pixelio_wp_die();
		}
		$this->wordpress_wrapper->pixelio_wp_send_json_success("no uuid");
		$this->wordpress_wrapper->pixelio_wp_die();
	}


}
