<?php

namespace PixelioCartAbandonRecoveryMore\Frontend\Models;


use DateTime;
use PixelioCartAbandonRecoveryMore\Admin\Wrapper\Pixelio_Cart_Abandon_Recovery_More_Woocommerce_Wrapper;
use PixelioCartAbandonRecoveryMore\Admin\Wrapper\Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper;
use WC_Coupon;

class Pixelio_Cart_Abandon_Recovery_More_Coupon_Model
{

	private Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $wordpress_wrapper;
	private Pixelio_Cart_Abandon_Recovery_More_Woocommerce_Wrapper $woocommerce_wrapper;

	public function __construct(Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $pixelio_wordpress_wrapper,Pixelio_Cart_Abandon_Recovery_More_Woocommerce_Wrapper $woocommerce_wrapper)
	{
		$this->wordpress_wrapper = $pixelio_wordpress_wrapper;
		$this->woocommerce_wrapper = $woocommerce_wrapper;
	}
	protected function get_active_coupon_for_email(string $email): ?WC_Coupon
	{
		$existing = $this->wordpress_wrapper->pixelio_get_coupons_from_email($email);

		if (empty($existing)) {
			return null;
		}

		foreach ($existing as $c) {

			$coupon = new WC_Coupon($c->ID);

			// expiré ?
			$expiry = $coupon->get_date_expires();
			if ($expiry && $expiry->getTimestamp() < time()) {
				continue;
			}

			// usage full ?
			$limit = $coupon->get_usage_limit();
			$used  = $coupon->get_usage_count();

			if ($limit && $used >= $limit) {
				continue;
			}

			return $coupon;
		}

		return null;
	}



	public function pixelio_cart_abandon_recovery_more_create_user_specific_coupon(string|array $user_email, $expiration, $discount = 15, $type = "percent", $createDiscountForPopup=false): string
	{
		if ((string) $type === '1') {
			$type = 'percent';
		} elseif ((string) $type === '2') {
			$type = 'fixed_cart';
		}
		$email = is_array($user_email) ? ($user_email[0]->email ?? '') : $user_email;

		if (!$email || (string) $type === '0') return '';
		return $this->generate_user_coupon($email, $discount, $type,$expiration,$createDiscountForPopup);
	}

	protected function is_coupon_valid($coupon_id): bool
	{
		$coupon = new WC_Coupon($coupon_id);

		// 1. Expiration
		$expiry = $coupon->get_date_expires();
		if ($expiry && $expiry->getTimestamp() < time()) {
			return false;
		}

		// 2. Déjà utilisé (usage limit atteint)
		$usage_limit = $coupon->get_usage_limit();
		$usage_count = $coupon->get_usage_count();

		if ($usage_limit && $usage_count >= $usage_limit) {
			return false;
		}

		return true;
	}
	/**
	 * Create coupon
	 */
	protected function generate_user_coupon(
		string $email,
		float $discount = 15,
		string $type = 'percent',
			   $expiration = 1,
		$isPopup
	): string
	{
		if ($discount <= 0) {
			return "";
		}

		if (empty($expiration)) {
			$expiration = 1;
		}

		// 1. check coupon actif
		$active = $this->get_active_coupon_for_email($email);

		if ($active) {

			// 2. si exactement identique → reuse
			if ($this->is_same_coupon($active, $discount, $type, (int)$expiration)) {
				error_log('Reusing existing identical coupon');
				return $active->get_code();
			}

			// 3. sinon désactiver ancien coupon
			$active->set_date_expires(current_time('mysql'));
			$active->set_usage_limit(0);

			if (method_exists($active, 'set_status')) {
				$active->set_status('draft');
			}

			$active->save();

		}

		// 4. create new coupon
		$coupon_code = $this->generate_unique_coupon();
		$coupon = $this->woocommerce_wrapper->pixelio_get_coupon_model();

		$coupon->set_code($coupon_code);
		$coupon->set_discount_type($type);
		$coupon->set_amount($discount);
		$coupon->set_usage_limit(1);
		$coupon->set_individual_use(true);
		$coupon->set_email_restrictions([$email]);

		$expires = $this->woocommerce_wrapper->pixelio_get_WC_DateTime();
		if($isPopup){
			$expires->modify('+' . $expiration . ' min');
		}else{
			$expires->modify('+' . $expiration . ' day');
		}
		$coupon->set_date_expires($expires);

		$id = $coupon->save();

		if (!$id) {
			error_log('Failed to create coupon');
			return "";
		}

		return $coupon_code;
	}
	protected function is_same_coupon($coupon, float $discount, string $type, int $expiration_days): bool
	{
		if ((float) $coupon->get_amount() !== (float) $discount) {
			return false;
		}

		if ($coupon->get_discount_type() !== $type) {
			return false;
		}

		$expiry = $coupon->get_date_expires();
		if (!$expiry) {
			return false;
		}

		$expected = (new DateTime())->modify('+' . $expiration_days . ' day')->getTimestamp();

		// marge de 2 minutes pour éviter les micro-différences
		return abs($expiry->getTimestamp() - $expected) < 120;
	}
	protected function disable_user_coupons(string $email): void
	{
		$existing = $this->wordpress_wrapper->pixelio_get_coupons_from_email($email);

		if (empty($existing)) {
			return;
		}

		foreach ($existing as $coupon_data) {

			$coupon = new WC_Coupon($coupon_data->ID);

			// Désactive proprement le coupon
			$coupon->set_date_expires(current_time('mysql')); // expire immédiatement
			$coupon->set_usage_limit(0);

			// optionnel mais recommandé
			if (method_exists($coupon, 'set_status')) {
				$coupon->set_status('draft');
			}

			$coupon->save();
		}
	}
	/**
	 * Generate unique coupon
	 */
	private function generate_unique_coupon(): string
	{
		do {
			$code = $this->generate_random_coupon_name();
		} while ($this->coupon_exists($code));

		return $code;
	}

	private function generate_random_coupon_name(int $length = 3): string
	{
		return 'hello' . substr(
				str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'),
				0,
				$length
			);
	}

	private function coupon_exists(string $code): bool
	{
		$query = $this->wordpress_wrapper->pixelio_wp_query([
			'post_type' => 'shop_coupon',
			'title' => $code,
			'post_status' => 'any',
			'posts_per_page' => 1,
			'fields' => 'ids'
		]);

		return !empty($query->posts);
	}

}
