<?php

namespace PixelioCartAbandonRecoveryMore\Frontend\Services;

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

use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Email_Logger_Service;
use PixelioCartAbandonRecoveryMore\Admin\Services\Pixelio_Cart_Abandon_Recovery_More_Uuid_Service;
use PixelioCartAbandonRecoveryMore\Admin\Wrapper\Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper;
use PixelioCartAbandonRecoveryMore\Frontend\Repositories\Pixelio_Cart_Abandon_Recovery_More_Email_Logs_Repository;
use PixelioCartAbandonRecoveryMore\Frontend\Repositories\Pixelio_Cart_Abandon_Recovery_More_User_Contact_Repository;
use PixelioCartAbandonRecoveryMore\Includes\Utils\Pixelio_Cart_Abandon_Recovery_More_Util;
use PixelioCartAbandonRecoveryMore\Includes\Validators\Pixelio_Cart_Abandon_Recovery_More_Wishlist_Email_Validator;

class Pixelio_Cart_Abandon_Recovery_More_Wishlist_Service
{
	public function __construct(
		private Pixelio_Cart_Abandon_Recovery_More_Wishlist_Email_Validator $validator,
		private Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $wordpress_wrapper,
		private Pixelio_Cart_Abandon_Recovery_More_Uuid_Service $uuid_service,
		private Pixelio_Cart_Abandon_Recovery_More_User_Contact_Repository $contacts
	) {
	}

	public function check(?string $email = null): array
	{


		if (empty($email)) {
			return [
				'requires_email' => true,
			];
		}

		if (!$this->validator->validate($email)) {
			return [
				'error' => $this->wordpress_wrapper->pixelio_translate('Invalid email.'),
			];
		}

		return [
			'user_id'    => $this->contacts->pixelio_find_by_email($email),
			'email'      => $email,
		];
	}

	public function create_or_get_recovery_token(string $email, array $identity): string
	{
		$email = $this->wordpress_wrapper->pixelio_sanitize_email($email);

		$token_key = 'pixelio_wishlist_recovery_token_' . md5(strtolower($email));
		$existing_token = $this->wordpress_wrapper->pixelio_get_transient($token_key);

		if (!empty($existing_token)) {
			return $existing_token;
		}

		$token = $this->wordpress_wrapper->pixelio_wp_generate_password(48, false, false);

		$this->wordpress_wrapper->pixelio_set_transient(
			$token_key,
			$token,
			MONTH_IN_SECONDS
		);

		$this->wordpress_wrapper->pixelio_set_transient(
			'pixelio_wishlist_recovery_' . $token,
			[
				'email'      => $email,
				'user_id'    => $identity['user_id'] ?? null,
				'contact_id' => $identity['contact_id'] ?? null,
			],
			MONTH_IN_SECONDS
		);

		return $token;
	}

	public function maybe_restore_wishlist_from_token(): void
	{
		if (empty($_GET['pixelio_wishlist_token'])) {
			return;
		}

		$token = $this->wordpress_wrapper->pixelio_sanitize_text_field(
			$this->wordpress_wrapper->pixelio_wp_unslash($_GET['pixelio_wishlist_token'])
		);

		$data = $this->wordpress_wrapper->pixelio_get_transient(
			'pixelio_wishlist_recovery_' . $token
		);


		if (!$data || empty($data['email'])) {
			return;
		}

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

		if (empty($email) || !is_email($email)) {
			return;
		}

		$this->uuid_service->ensure_uuid("wishlist","wishlist","wishlist");

		$this->wordpress_wrapper->pixelio_setcookie(
			'pixelio_wishlist_email',
			$email,
			time() + YEAR_IN_SECONDS,
			COOKIEPATH,
			COOKIE_DOMAIN,
			is_ssl(),
			true
		);

		$this->wordpress_wrapper->pixelio_add_action('wp_enqueue_scripts', function () use ($email) {

			$script = sprintf(
				'window.localStorage.setItem("pixelio_wishlist_email", %s);',
				$this->wordpress_wrapper->pixelio_wp_json_encode($email)
			);

			$result =$this->wordpress_wrapper->pixelio_wp_add_inline_script(
				Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_plugin_slug . '-public-script',
				$script,
				'after'
			);

		});

		$wishlist_page_id = (int) get_option('pixelio_wishlist_page_id');

		$wishlist_page_url = $wishlist_page_id
			? get_permalink($wishlist_page_id)
			: $this->wordpress_wrapper->pixelio_home_url('/pixelio-wishlist/');

		$this->wordpress_wrapper->pixelio_wp_safe_redirect(
			$wishlist_page_url
		);

		exit;
	}


}
