<?php

namespace PixelioCartAbandonRecoveryMore\Admin\Services;
if (!defined('ABSPATH')) exit;

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_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\Includes\Utils\Pixelio_Cart_Abandon_Recovery_More_Util;

class Pixelio_Cart_Abandon_Recovery_More_Uuid_Service
{
	private Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $wordpress_wrapper;
	private Pixelio_Cart_Abandon_Recovery_More_Util $pixelio_util;
	private Pixelio_Cart_Abandon_Recovery_More_User_Consent_Repository $user_consent_repo;

	private Pixelio_Cart_Abandon_Recovery_More_Uuid_Repository $uuid_repo;
	private Pixelio_Cart_Abandon_Recovery_More_Woocommerce_Wrapper $woocommerce_wrapper;


	public function __construct($wordpress_wrapper, $user_consent_repo, $pixelio_util, $uuid_repo, $woocommerce_wrapper)
	{
		$this->wordpress_wrapper = $wordpress_wrapper;
		$this->user_consent_repo = $user_consent_repo;
		$this->uuid_repo = $uuid_repo;
		$this->pixelio_util = $pixelio_util;
		$this->woocommerce_wrapper = $woocommerce_wrapper;
	}


	/**
	 * Generate a secure random UUID-like string.
	 *
	 * @return string The generated UUID.
	 * @since 0.1.0
	 *
	 */
	public function ensure_uuid($utm_source,
								 $utm_campaign,$utm_medium): string
	{

		$uuid = null;
		if ($this->wordpress_wrapper->pixelio_is_user_logged_in()) {
			$current_user = $this->wordpress_wrapper->pixelio_wp_get_current_user();
			$email = $current_user->user_email;

			if ($email) {
				$gdpr_active = $this->pixelio_util->pixelio_cart_abandon_recovery_more_dependency_is_checked("pixelio-cart-abandon-recovery-more-gdpr-consent-checkbox");

				if ($gdpr_active) {
					$user_id = $this->user_consent_repo->pixelio_get_user_id_by_email($email,$utm_source,
						$utm_campaign,$utm_medium);
					if (!$this->user_consent_repo->pixelio_is_subscribed(
						$email,
						Pixelio_Cart_Abandon_Recovery_More_Util::$finalite_cart
					) && !$this->wordpress_wrapper->pixelio_wc_get_session('uuid')) {
						$uuid = $this->generate_uuid();
					}else{
						$uuid = $this->wordpress_wrapper->pixelio_wc_get_session('uuid');
					}
					$this->uuid_repo->pixelio_add_or_update_uuid($uuid,$user_id);

				} else {
					$uuid = $this->wordpress_wrapper->pixelio_wc_get_session('uuid') ?? $this->generate_uuid();

					$user_id = $this->user_consent_repo->pixelio_save_consent(
						$email,
						Pixelio_Cart_Abandon_Recovery_More_Util::$gdpr_not_active,
						"RGPD NOT APPLICABLE",
						true,$utm_source,
						$utm_campaign,$utm_medium
					);


					$this->uuid_repo->pixelio_add_or_update_uuid($uuid, $user_id);


				}
			}
		}

		// Sinon, génère un nouvel UUID aléatoire
		if (!$uuid) {
			$uuid = $this->wordpress_wrapper->pixelio_wc_get_session('uuid') ?? ($this->wordpress_wrapper->pixelio_getcookie() ?? $this->generate_uuid());
			$user_id = $this->uuid_repo->pixelio_add_or_update_uuid($uuid, 0);
		}

		$this->woocommerce_wrapper->pixelio_wc_set_session('uuid',$uuid);

		$this->wordpress_wrapper->pixelio_setcookie('uuid', $uuid, [
			'expires' => time() + 86400,  // 1 heure
			'path' => '/',               // accessible sur tout le site
			'secure' => isset($_SERVER['HTTPS']), // https seulement si en SSL
			'httponly' => false,          // accessible en JS si nécessaire
			'samesite' => 'Lax'           // ou 'None' / 'Strict' selon ton besoin
		]);
		return $uuid;
	}

	/**
	 * Génère un UUID sécurisé au format XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
	 *
	 * @return string
	 */
	private function generate_uuid(): string
	{
		try {
			return sprintf(
				'%s-%s-%s-%s-%s',
				bin2hex(random_bytes(4)),
				bin2hex(random_bytes(2)),
				bin2hex(random_bytes(2)),
				bin2hex(random_bytes(2)),
				bin2hex(random_bytes(6))
			);
		} catch (\Exception $e) {
			// fallback si random_bytes échoue
			return uniqid('', true);
		}
	}
}
