<?php
namespace PixelioCartAbandonRecoveryMore\Admin\Services;

use PixelioCartAbandonRecoveryMore\Frontend\Repositories\Pixelio_Cart_Abandon_Recovery_More_User_Consent_Repository;
use PixelioCartAbandonRecoveryMore\Includes\Utils\Pixelio_Cart_Abandon_Recovery_More_Util;

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

class Pixelio_Cart_Abandon_Recovery_More_Unsubscribe_Service
{
	private $wordpress_wrapper;
	private Pixelio_Cart_Abandon_Recovery_More_User_Consent_Repository $user_consent_repo;

	public function __construct($wordpress_wrapper, $user_consent_repo)
	{
		$this->wordpress_wrapper = $wordpress_wrapper;
		$this->user_consent_repo = $user_consent_repo;
	}
	public function generate_unsubscribe_link(string $email): string
	{
		$email = $this->wordpress_wrapper->pixelio_sanitize_email($email);

		$exp = time() + (30 * DAY_IN_SECONDS);

		$sig = hash_hmac(
			'sha256',
			$email . '|' . $exp,
			AUTH_KEY
		);

		return add_query_arg(
			[
				'unsubscribe' => rawurlencode($email),
				'exp'         => $exp,
				'sig'         => $sig,
			],
			home_url('/')
		);
	}
	public function handle_unsubscribe(): void
	{
		// On ne fait rien si pas de GET unsubscribe
		if (!isset($_GET['unsubscribe'])) {
			return;
		}
		$email = $this->validate_unsubscribe_link();
		if (!$email) {
			return;
		}

		// Supprime la souscription
		$this->user_consent_repo->pixelio_unsubscribe($email);

		// Redirige vers la page de succès ou page d’erreur
		$page_id = $this->wordpress_wrapper->pixelio_esc_html($this->wordpress_wrapper->pixelio_get_option('pixelio_unsubscribe_page_id'));
		$unsubscribe_url = $this->wordpress_wrapper->pixelio_get_permalink($page_id);

		$error_page_id = $this->wordpress_wrapper->pixelio_esc_html($this->wordpress_wrapper->pixelio_get_option('pixelio_error_page_id'));
		$error_unsubscribe_url = $this->wordpress_wrapper->pixelio_get_permalink($error_page_id);

		if ($unsubscribe_url) {
			$this->wordpress_wrapper->pixelio_wp_safe_redirect($unsubscribe_url);
		} elseif ($error_unsubscribe_url) {
			$this->wordpress_wrapper->pixelio_wp_safe_redirect($error_unsubscribe_url);
		}

		exit;
	}

	private function validate_unsubscribe_link(): string|false
	{
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- safe: using signed token (sig) for verification instead of nonce.
		if (!isset($_GET['unsubscribe'], $_GET['exp'], $_GET['sig'])) {

			return false;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- safe: using signed token (sig) for verification instead of nonce.
		$email = $this->wordpress_wrapper->pixelio_sanitize_email($this->wordpress_wrapper->pixelio_wp_unslash(rawurldecode($_GET['unsubscribe'])));
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- safe: using signed token (sig) for verification instead of nonce.
		$exp = (int)$this->wordpress_wrapper->pixelio_sanitize_text_field($this->wordpress_wrapper->pixelio_wp_unslash($_GET['exp']));
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- safe: using signed token (sig) for verification instead of nonce.
		$sig = $this->wordpress_wrapper->pixelio_sanitize_text_field( $this->wordpress_wrapper->pixelio_wp_unslash($_GET['sig']));

		if ($exp < time()) {

			return false;
		}
		$expected_sig = hash_hmac('sha256', $email . '|' . $exp, AUTH_KEY);
		if (!hash_equals($expected_sig, $sig)) {
			return false;
		}

		return $email;
	}

	public function render_unsubscribe_message(): string
	{
		$output = '<div class="pixelio-cart-abandon-recovery-more-unsubscribe">';
		$output .= '<h2>' . $this->wordpress_wrapper->pixelio_translate(
				'Unsubscribe from emails',
				'rivio-ai-cart-recovery-marketing-email-automation'
			) . '</h2>';
		$output .= '<p>' . $this->wordpress_wrapper->pixelio_translate(
				'Your unsubscribe request has been successfully processed. See you soon.',
				'rivio-ai-cart-recovery-marketing-email-automation'
			) . '</p>';
		$output .= '</div>';

		return $this->wordpress_wrapper->pixelio_wp_kses(
			$output,
			Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_cart_abandon_recovery_more_allowed_html
		);
	}

	function render_error_message(): string
	{
		$output = '<div class="pixelio-unsubscribe-error">';
		$output .= '<h2>' . $this->wordpress_wrapper->pixelio_translate('Unsubscribe Error', 'rivio-ai-cart-recovery-marketing-email-automation') . '</h2>';
		$output .= '<p>' . $this->wordpress_wrapper->pixelio_translate('Your unsubscribe link has expired or something went wrong. Please try again or contact us if the issue persists.', 'rivio-ai-cart-recovery-marketing-email-automation') . '</p>';
		$output .= '</div>';
		return $this->wordpress_wrapper->pixelio_wp_kses($output, Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_cart_abandon_recovery_more_allowed_html);
	}
}
