<?php

namespace Easymailing\App\Core\Provider\Woocommerce\Hooks;

use Easymailing\App\Core\Log\LogManager;
use Easymailing\App\Core\Provider\Woocommerce\Model\LogType;

/**
 * Reconstruye el carrito de WooCommerce desde una URL de recovery generada en
 * CartHooks::buildRecoveryCheckoutUrl(). Permite que los emails de carrito
 * abandonado funcionen cross-device: el usuario clica el link, se reconstruye
 * su carrito con los productos originales y se redirige al checkout.
 */
class CartRebuildHook
{
	const ACTION_PARAM = 'em_action';
	const PAYLOAD_PARAM = 'em_cart';
	const ACTION_VALUE = 'rebuild_cart';

	private $logManager;

	public function __construct(LogManager $logManager)
	{
		$this->logManager = $logManager;
	}

	/**
	 * Se dispara en wp_loaded. Si la URL actual es de recovery, vacía el carrito,
	 * añade los productos del payload base64 y redirige al checkout conservando
	 * el resto de query params (especialmente em_ch para atribución).
	 */
	public function rebuildCart(): void
	{
		if (is_admin()) {
			return;
		}

		if (!self::isRebuildUrl()) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification
		$encoded = isset($_GET[self::PAYLOAD_PARAM]) ? sanitize_text_field(wp_unslash($_GET[self::PAYLOAD_PARAM])) : '';
		if (empty($encoded)) {
			return;
		}

		$decoded = json_decode(base64_decode($encoded), true);
		if (!is_array($decoded) || empty($decoded['products']) || !is_array($decoded['products'])) {
			return;
		}

		if (!function_exists('WC') || !WC()->cart) {
			return;
		}

		WC()->cart->empty_cart(true);

		foreach ($decoded['products'] as $product) {
			if (empty($product['product_id'])) {
				continue;
			}

			WC()->cart->add_to_cart(
				(int) $product['product_id'],
				(int) ($product['quantity'] ?? 1),
				(int) ($product['variation_id'] ?? 0),
				is_array($product['variation'] ?? null) ? $product['variation'] : []
			);
		}

		$redirectUrl = wc_get_checkout_url();

		if (!empty($_SERVER['QUERY_STRING'])) {
			$redirectUrl = add_query_arg(
				sanitize_text_field(wp_unslash($_SERVER['QUERY_STRING'])),
				'',
				$redirectUrl
			);
		}

		$redirectUrl = remove_query_arg([self::ACTION_PARAM, self::PAYLOAD_PARAM], $redirectUrl);

		$this->logManager->createLog(LogType::INFO, sprintf("Rebuilt cart from recovery URL, redirecting to: %s", $redirectUrl));

		wp_safe_redirect(esc_url_raw($redirectUrl));
		exit;
	}

	public static function isRebuildUrl(): bool
	{
		// phpcs:ignore WordPress.Security.NonceVerification
		return isset($_GET[self::ACTION_PARAM]) && $_GET[self::ACTION_PARAM] === self::ACTION_VALUE;
	}
}
