<?php

namespace PixelioCartAbandonRecoveryMore\Admin\Validator;

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

/**
 * Service responsible for validating email and UUID
 * from AJAX requests for temporary coupons.
 *
 * Dependencies are injected to allow unit testing without
 * loading WordPress.
 */
class Pixelio_Cart_Abandon_Recovery_More_Coupon_Validator
{
	private $wordpress_wrapper;
	private $pixelio_util;

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

	/**
	 * Validate email and UUID from $_POST and $_COOKIE
	 *
	 * @return string sanitized email
	 * @throws \RuntimeException
	 * @throws \InvalidArgumentException
	 */
	public function pixelio_cart_abandon_recovery_more_validate_email_and_uuid(): string
	{
		if (!defined('DOING_AJAX') || !DOING_AJAX) {
			throw new \RuntimeException('Not an AJAX request');
		}


		if (!isset($_POST['pixelio-cart-abandon-recovery-more-pop-up-email'])) {
			throw new \InvalidArgumentException('Email missing');
		}

		$email = $this->wordpress_wrapper->pixelio_sanitize_text_field(
			$this->wordpress_wrapper->pixelio_wp_unslash($_POST['pixelio-cart-abandon-recovery-more-pop-up-email'])
		);

		if (empty($email) || !is_email($email)) {
			throw new \InvalidArgumentException('Invalid email');
		}

		if ($this->pixelio_util->pixelio_cart_abandon_recovery_more_is_temporary_email($email)) {
			throw new \InvalidArgumentException('Temporary email not allowed');
		}

		return $email;
	}

	/**
	 * Get sanitized UUID from cookie
	 *
	 * @return string
	 */
	public function pixelio_cart_abandon_recovery_more_get_uuid(): string
	{
		return $this->wordpress_wrapper->pixelio_sanitize_text_field($this->wordpress_wrapper->pixelio_wc_get_session('uuid'));
	}
}
