<?php

namespace PixelioCartAbandonRecoveryMore\Frontend\Repositories;
if (!defined('ABSPATH')) exit;

use PixelioCartAbandonRecoveryMore\Admin\Wrapper\Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper;
use PixelioCartAbandonRecoveryMore\Includes\Utils\Pixelio_Cart_Abandon_Recovery_More_Util;

class Pixelio_Cart_Abandon_Recovery_More_Wishlist_Repository
{
	private $table;
	private Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $wordpress_wrapper;
	private string|\wpdb $wpdb;

	public function __construct($wordpress_wrapper)
	{
		$this->wordpress_wrapper = $wordpress_wrapper;
		$this->table = $this->wordpress_wrapper->pixelio_get_wpdb()->prefix . Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_plugin_db_prefix . 'wishlist';
		$this->wpdb = $this->wordpress_wrapper->pixelio_get_wpdb();
	}

	public function add(int $product_id, $user_id): bool
	{

		if ($this->exists($product_id, $user_id)) return false;
		return (bool)$this->wpdb->insert($this->table, [
			'product_id' => $product_id,
			'user_id' => $user_id,
		]);
	}

// ── Vérifier si déjà en wishlist ───────────────────
	public function exists($product_id, $user_id): bool
	{
		if (!$product_id || !($user_id)) {
			return false;
		}

		$sql = $this->wpdb->prepare(
			"SELECT id
		 FROM {$this->table}
		 WHERE product_id = %d
		 AND user_id = %d
		 LIMIT 1",
			$product_id,
			$user_id
		);

		return (bool) $this->wpdb->get_var($sql);
	}

// ── Tous les contacts d'un produit (pour Restock) ──
	public function find_by_product(int $product_id): array
	{

		return $this->wpdb->get_results($this->wpdb->prepare(
			"SELECT user_id FROM %i WHERE product_id = %d",
			$this->table, $product_id
		), ARRAY_A);
	}

	// ── Supprimer ──────────────────────────────────────
	public function remove(int $product_id, ?int $user_id): bool
	{
		global $wpdb;

		$table = $wpdb->prefix . 'pixelio_wishlist_items';

		$where = [
			'product_id' => $product_id,
		];

		$format = ['%d'];

		if ($user_id) {
			$where['user_id'] = $user_id;
			$format[] = '%d';
		}

		return (bool) $wpdb->delete($table, $where, $format);
	}

// ── Items sans relance envoyée depuis X jours ──────────
	public function find_pending_reminders(int $days): array
	{
		global $wpdb;
// Items ajoutés il y a plus de $days jours
// et pour lesquels on n'a pas encore envoyé de relance
		return $wpdb->get_results($wpdb->prepare(
			"SELECT id, product_id, user_id, created_at
FROM %i
WHERE created_at <= DATE_SUB( NOW(), INTERVAL %d DAY )
AND reminded_at IS NULL",
			$this->table, $days
		), ARRAY_A);
	}

	public function get_all_item_by_user_id(mixed $user_id)
	{


		$sql = $this->wpdb->prepare(
			"SELECT product_id FROM {$this->table}
		 WHERE user_id = %d
		 ORDER BY id DESC",
			$user_id
		);
		return $this->wpdb->get_results($sql);
	}


}
