<?php
/**
 * Frontend Controller
 *
 * Handles all public-facing features such as sessions, popups,
 * timers, recommendations and email capture logic.
 *
 * @package PixelioCartAbandonRecoveryMore
 * @since 0.1
 */

namespace PixelioCartAbandonRecoveryMore\Frontend\controllers;


use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Cart_Service;
use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Consent_Service;
use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Head_Meta_Renderer_Service;
use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Popup_Renderer_Service;
use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Unsubscribe_Service;
use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Uuid_Service;
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;
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_Wishlist_Service;
use PixelioCartAbandonRecoveryMore\Includes\Utils\Pixelio_Cart_Abandon_Recovery_More_Util;

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

/**
 * Frontend controller for the Pixelio Cart Abandon Recovery plugin.
 *
 * Handles session initialization, popup rendering, timers,
 * email capture, and product/page-view tracking on the frontend.
 *
 * @since 0.1
 */
class Pixelio_Cart_Abandon_Recovery_More_Frontend_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_Uuid_Repository $uuid_repo;
	private Pixelio_Cart_Abandon_Recovery_More_User_Consent_Repository $user_consent_repo;
	private Pixelio_Cart_Abandon_Recovery_More_Cart_Item_Repository $pixelio_cart_item_model;
	private Pixelio_Cart_Abandon_Recovery_More_Wishlist_Service $wishlist_service;
	private Pixelio_Cart_Abandon_Recovery_More_Wishlist_Repository $wishlist_repo;

	/**
	 * Initialize frontend actions and session handling.
	 *
	 * @since 0.1
	 */
	public function __construct(Pixelio_Cart_Abandon_Recovery_More_Util                    $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_Repository         $pixelio_cart_model,
								Pixelio_Cart_Abandon_Recovery_More_Cart_Item_Repository    $pixelio_cart_item_model,
								Pixelio_Cart_Abandon_Recovery_More_Wishlist_Service        $wishlist_service,
								Pixelio_Cart_Abandon_Recovery_More_Wishlist_Repository        $wishlist_repo,
								Pixelio_Cart_Abandon_Recovery_More_User_Consent_Repository $user_consent_repo, Pixelio_Cart_Abandon_Recovery_More_Uuid_Repository $uuid_repo
	)
	{
		$this->wordpress_wrapper = $wordpress_wrapper;
		$this->woocommerce_wrapper = $woocommerce_wrapper;
		$this->pixelio_util = $pixelio_util;
		$this->wishlist_repo = $wishlist_repo;
		$this->cart_model = $pixelio_cart_model;
		$this->pixelio_cart_item_model = $pixelio_cart_item_model;
		$this->wishlist_service = $wishlist_service;
		$this->user_consent_repo = $user_consent_repo;
		$this->uuid_repo = $uuid_repo;
		parent::__construct($wordpress_wrapper, $pixelio_util);
		session_set_cookie_params(
			array(
				'lifetime' => 0,
				'path' => '/',
				'domain' => isset($_SERVER['HTTP_HOST']) ? $this->wordpress_wrapper->pixelio_sanitize_text_field($this->wordpress_wrapper->pixelio_wp_unslash($_SERVER['HTTP_HOST'])) : '',
				'secure' => true,
				'httponly' => true,
				'samesite' => 'Lax',
			)
		);

		$this->wordpress_wrapper->pixelio_add_action('template_redirect', array($this, 'pixelio_cart_abandon_recovery_more_start_session'));
		$this->wordpress_wrapper->pixelio_add_action('wp_body_open', array($this, 'pixelio_cart_abandon_recovery_more_add_bought_by'));
		$this->wordpress_wrapper->pixelio_add_action('wp_head', array($this, 'pixelio_cart_abandon_recovery_more_add_head'));
		$this->wordpress_wrapper->pixelio_add_action('wp_enqueue_scripts', array($this, 'pixelio_cart_abandon_recovery_more_enqueue'));
		$this->wordpress_wrapper->pixelio_add_shortcode('pixelio_unsubscribe', array($this, 'pixelio_cart_abandon_recovery_more_unsubscribe_shortcode'));
		$this->wordpress_wrapper->pixelio_add_shortcode('pixelio_error', array($this, 'pixelio_cart_abandon_recovery_more_error_shortcode'));
		$this->wordpress_wrapper->pixelio_add_shortcode('pixelio_wishlist', array($this, 'pixelio_cart_abandon_recovery_more_render_wishlist'));

		$this->wordpress_wrapper->pixelio_add_action('woocommerce_after_add_to_cart_button', array($this, 'pixelio_cart_abandon_recovery_more_add_delivery_calculator_after_cart_button'));
		$this->wordpress_wrapper->pixelio_add_action('woocommerce_after_add_to_cart_button', array($this, 'pixelio_cart_abandon_recovery_more_add_wishlist_option_after_cart_button'));;
		$this->wordpress_wrapper->pixelio_add_action(
			'init',
			[$this, 'maybe_restore_wishlist_from_token']
		);
	}


	public function pixelio_cart_abandon_recovery_more_render_wishlist(): string
	{
		$email = $_COOKIE['pixelio_wishlist_email'] ?? '';

		$email = sanitize_email($email);

		if (empty($email) || !is_email($email)) {
			return '<p>' . esc_html__('Your wishlist is empty.', 'pixelio') . '</p>';
		}
		$identity = $this->wishlist_service->check($email);
		$items = $this->wishlist_repo->get_all_item_by_user_id($identity["user_id"]);

		if (empty($items)) {
			return '<p>' . esc_html__('Your wishlist is empty.', 'pixelio') . '</p>';
		}

		ob_start();

		echo '<div class="pixelio-wishlist-grid">';

		foreach ($items as $item) {

			$product = wc_get_product($item->product_id);

			if (!$product) {
				continue;
			}

			?>

			<div class="pixelio-wishlist-card">

				<a href="<?php echo esc_url(get_permalink($product->get_id())); ?>">

					<?php echo $product->get_image('medium'); ?>

					<h3>
						<?php echo esc_html($product->get_name()); ?>
					</h3>

					<span>
					<?php echo wp_kses_post($product->get_price_html()); ?>
				</span>

				</a>

			</div>

			<?php
		}

		echo '</div>';

		return ob_get_clean();
	}

	function pixelio_cart_abandon_recovery_more_add_wishlist_option_after_cart_button()
	{
		if ($this->pixelio_util->pixelio_cart_abandon_recovery_more_dependency_is_checked("pixelio-cart-abandon-recovery-more-wishlist-checkbox")) {
			$product = $this->woocommerce_wrapper->pixelio_get_product();
			?>
			<div class="rivio-wishlist">
				<button
					id="wishlist-btn"
					class="rivio-wishlist-btn"
					type="button"
					product-id="<?= esc_attr($product->get_id()); ?>"
				>
					<span class="rivio-wishlist-icon">♡</span>
					<span>Ajouter à ma wishlist</span>
				</button>

				<div id="wishlist-email-modal" class="rivio-wishlist-modal" style="display:none">
					<div class="rivio-wishlist-modal-box">
						<button id="wishlist-modal-close" class="rivio-wishlist-close" type="button">✕</button>

						<h3>Sauvegarder votre wishlist</h3>
						<p>Entrez votre email pour retrouver votre wishlist plus tard.</p>

						<input
							type="email"
							id="wishlist-email-input"
							class="rivio-wishlist-input"
							placeholder="Votre email"
						/>

						<?php if ($this->pixelio_util->pixelio_cart_abandon_recovery_more_dependency_is_checked("pixelio-cart-abandon-recovery-more-gdpr-consent-checkbox")) { ?>
							<label class="rivio-wishlist-consent">
								<input
									type="checkbox"
									name="pixelio-cart-abandon-recovery-more-wishlist-rgpd"
									class="pixelio-cart-abandon-recovery-more-wishlist-rgpd"
									required
								>
								<span><?php $this->wordpress_wrapper->pixelio_esc_html_e("I consent to the processing of my personal data for the purpose of saving and retrieving my wishlist, in accordance with the Privacy Policy."); ?></span>
							</label>
						<?php } ?>

						<button id="wishlist-email-submit" class="rivio-wishlist-submit" type="button">
							Confirmer
						</button>
					</div>
				</div>

				<span id="wishlist-error" class="rivio-wishlist-error" style="display:none"></span>
			</div>
			<?php
		}
	}

	function pixelio_cart_abandon_recovery_more_add_delivery_calculator_after_cart_button()
	{

		if ($this->pixelio_util->pixelio_cart_abandon_recovery_more_dependency_is_checked("pixelio-cart-abandon-recovery-more-delivery-fee-checkbox")) {
			$product = $this->woocommerce_wrapper->pixelio_get_product();
			?>
			<div id="delivery-estimator" class="pixelio-delivery-box">

				<div class="pixelio-delivery-input-group">
					<div class="pixelio-delivery-input-group-item">

						<h3><?php $this->wordpress_wrapper->pixelio_esc_html_e("Calculate your delivery fee:"); ?></h3>
					</div>
					<div class="pixelio-delivery-input-group-item">
						<input
							type="text"
							id="delivery-postcode"
							product-id="<?php echo esc_attr($product->get_id()); ?>"
							placeholder="Code postal"
							maxlength="10"
							autocomplete="postal-code"
						/>

						<button id="delivery-check-btn">
							Vérifier
						</button>
					</div>
				</div>

				<div id="delivery-result" class="pixelio-delivery-result"></div>
			</div>
			<?php
		}
	}

	function pixelio_cart_abandon_recovery_more_error_shortcode(): string
	{
		$renderer = new Pixelio_Cart_Abandon_Recovery_More_Unsubscribe_Service($this->wordpress_wrapper, $this->user_consent_repo);
		return $renderer->render_error_message();
	}

	/**
	 * Add meta tags to the document head (UUID, product ID).
	 *
	 * @return void
	 * @since 0.1
	 */
	public function pixelio_cart_abandon_recovery_more_add_head(): void
	{
		$renderer = new Pixelio_Cart_Abandon_Recovery_More_Head_Meta_Renderer_Service($this->wordpress_wrapper, $this->woocommerce_wrapper);
		echo $this->wordpress_wrapper->pixelio_wp_kses($renderer->render_head_meta(), Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_cart_abandon_recovery_more_allowed_html);
	}


	public function maybe_restore_wishlist_from_token(){

		$this->wishlist_service->maybe_restore_wishlist_from_token();
	}
	/**
	 * Enqueue public CSS/JS files and pass localized script data.
	 *
	 * @return void
	 * @since 0.1
	 */
	public function pixelio_cart_abandon_recovery_more_enqueue(): void
	{
		$this->wordpress_wrapper->pixelio_wp_enqueue_style('pixelio-abandon-recovery-more-style', plugins_url('../assets/css/public.css', __FILE__), array(), '0.0.1');
		$this->wordpress_wrapper->pixelio_wp_enqueue_script(Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_plugin_slug . '-public-script', plugins_url('../../admin/assets/js/pages/dist/public.bundle.js', __FILE__), array("jquery"), '0.0.1', true);

		$this->wordpress_wrapper->pixelio_wp_localize_script(
			Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_plugin_slug . '-public-script',
			'pixelio_ajax',
			array(
				'pixelio_ajax_url' => $this->wordpress_wrapper->pixelio_admin_url('admin-ajax.php'),
				'pixelio_ajax_nonce' => $this->wordpress_wrapper->pixelio_wp_create_nonce('pixelio_ajax_nonce'),
				'show_bought_popup' => $this->pixelio_util->pixelio_cart_abandon_recovery_more_dependency_is_checked('pixelio-cart-abandon-recovery-more-show-others-buy-checkbox'),
				'expiration_time_of_bought_popup' => Pixelio_Cart_Abandon_Recovery_More_Util::$expiration_time_of_bought_popup,
				'show_bought_popup_only_in_page' => $this->pixelio_util->pixelio_cart_abandon_recovery_more_dependency_is_checked('pixelio-cart-abandon-recovery-more-show-others-buy-only-product-checkbox'),
				'exit_popup' => $this->pixelio_util->pixelio_cart_abandon_recovery_more_dependency_is_checked('pixelio-cart-abandon-recovery-more-exit-popup-checkbox'),
				'emailPopupId' => '.pixelio-cart-abandon-recovery-more-pop-up-container-email-capture',
				'hideClass' => 'pixelio-cart-abandon-recovery-more-hide-it',
				'isRgpdActive' => $this->pixelio_util->pixelio_cart_abandon_recovery_more_dependency_is_checked('pixelio-cart-abandon-recovery-more-gdpr-consent-checkbox'),
				'timerTime' => defined('WP_PIXELIO_TEST') ? 5 * 60 : 15 * 60,
				'newsletterSubmitClass' => '.pixelio-cart-abandon-recovery-more-newsletters-submit',
				'consentRefusedName' => 'consent_refused',
				'consentUnknown' => '0',
				'isCheckoutOrCart' => is_cart() || is_checkout(),
				'consentRefused' => '1',
				'productId' => is_product() ? get_the_ID() : 0,
				'pageType' => is_product() ? 'product' : (is_cart() ? 'cart' : (is_checkout() ? 'checkout' : 'page')),
				'hasConsent' => isset($_COOKIE['pixelio_marketing_consent']) && $_COOKIE['pixelio_marketing_consent'] === '1',
				'email_required'        => $this->wordpress_wrapper->pixelio_translate('Please enter your email address.'),
				'privacy_required'      => $this->wordpress_wrapper->pixelio_translate('Please accept the privacy policy terms.'),
				'add_to_wishlist'       => $this->wordpress_wrapper->pixelio_translate('♡ Add to my wishlist'),
				'in_wishlist'           => $this->wordpress_wrapper->pixelio_translate('♥ In your wishlist'),
				'removed'               => $this->wordpress_wrapper->pixelio_translate('Removed from your wishlist.'),
				'recovery_email_sent'   => $this->wordpress_wrapper->pixelio_translate('Your wishlist has been saved. An email has been sent so you can retrieve it later.'),
				'newsletterSignupAction' => 'pixelio_cart_abandon_recovery_more_create_temporary_coupon',
				'userClickedAddToCart' => $this->wordpress_wrapper->pixelio_esc_attr__('User has clicked add to cart!'),
				'emailFound' => $this->wordpress_wrapper->pixelio_esc_attr__('Email found: '),
				'emailNotFound' => $this->wordpress_wrapper->pixelio_esc_attr__('No email field found nearby.'),
				'missing_email' => $this->wordpress_wrapper->pixelio_translate('Please enter your email.'),
				'missing_rgpd' => $this->wordpress_wrapper->pixelio_translate('Please accept the GDPR terms.'),
				'success' => $this->wordpress_wrapper->pixelio_translate('Thank you for subscribing!'),
				'success_promo' => $this->wordpress_wrapper->pixelio_translate('Thank you for subscribing! You will get an email with your discount'),
				'error' => $this->wordpress_wrapper->pixelio_translate('An error occurred, please try again.'),
				'cartCleared' => $this->wordpress_wrapper->pixelio_translate('The cart has been cleared because the reservation time has expired.')
			)
		);
	}

	/**
	 * Render purchase notifications and exit popups on the frontend.
	 *
	 * @return void
	 * @since 0.1
	 */
	public function pixelio_cart_abandon_recovery_more_add_bought_by(): void
	{
		$popup_renderer = new Pixelio_Cart_Abandon_Recovery_More_Popup_Renderer_Service($this->wordpress_wrapper, $this->pixelio_util);

		// Affichage propre
		$popup_renderer->render_bought_message_popup();
		$popup_renderer->render_exit_popup();

		// Ajouts complémentaires
		$this->pixelio_cart_abandon_recovery_more_add_cart_timer();
		$this->pixelio_cart_abandon_recovery_more_add_capture_user_mail();
	}

	/**
	 * Display countdown timer in cart or checkout if activated.
	 *
	 * @return void
	 * @since 0.1
	 */
	public function pixelio_cart_abandon_recovery_more_add_cart_timer(): void
	{
		if (!$this->wordpress_wrapper->pixelio_is_admin() && ($this->woocommerce_wrapper->pixelio_is_cart() || $this->woocommerce_wrapper->pixelio_is_checkout()) && !$this->woocommerce_wrapper->pixelio_is_cart_empty()) {
			if ($this->pixelio_util->pixelio_cart_abandon_recovery_more_dependency_is_checked('pixelio-cart-abandon-recovery-more-show-timer-in-cart-hurry-up-checkbox')) {
				include Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_plugin_dir_path . 'admin/views/preview/class-pixelio-cart-abandon-recovery-more-cart-timer.php';
			}
		}
	}

	/**
	 * Display the email capture popup if enabled and allowed.
	 *
	 * @return void
	 * @since 0.1
	 */
	public function pixelio_cart_abandon_recovery_more_add_capture_user_mail(): void
	{
		$popup_renderer = new Pixelio_Cart_Abandon_Recovery_More_Popup_Renderer_Service($this->wordpress_wrapper, $this->pixelio_util);

		$popup_renderer->render_capture_user_mail_popup();
	}

	function pixelio_cart_abandon_recovery_more_unsubscribe_shortcode(): string
	{
		$unsubscribe_service = new Pixelio_Cart_Abandon_Recovery_More_Unsubscribe_Service($this->wordpress_wrapper, $this->user_consent_repo);
		return $unsubscribe_service->render_unsubscribe_message();
	}

	/**
	 * Manage frontend session initialization, consent saving, cookie creation,
	 * cart recovery logic, and product/page-view tracking.
	 *
	 * @return void
	 * @since 0.1.0
	 */
	public function pixelio_cart_abandon_recovery_more_start_session(): void
	{
		$consentService = new Pixelio_Cart_Abandon_Recovery_More_Consent_Service($this->wordpress_wrapper, $this->pixelio_util, $this->user_consent_repo);
		$consentService->save_consent_from_post();

		$cartService = new Pixelio_Cart_Abandon_Recovery_More_Cart_Service($this->woocommerce_wrapper, $this->cart_model, $this->pixelio_cart_item_model, $this->wordpress_wrapper);
		$cartService->recover_cart_from_get();

		$uuidService = new Pixelio_Cart_Abandon_Recovery_More_Uuid_Service($this->wordpress_wrapper, $this->user_consent_repo, $this->pixelio_util, $this->uuid_repo, $this->woocommerce_wrapper);
		$uuidService->ensure_uuid("","","");

		$unsubscribeService = new Pixelio_Cart_Abandon_Recovery_More_Unsubscribe_Service(
			$this->wordpress_wrapper, $this->user_consent_repo
		);
		$unsubscribeService->handle_unsubscribe();

	}


}
