<?php

/**
 * UUID Model
 *
 * Handles mapping between WordPress user_id, email, and UUID.
 */
namespace PixelioCartAbandonRecoveryMore\Frontend\Repositories;

use PixelioCartAbandonRecoveryMore\Includes\Utils\Pixelio_Cart_Abandon_Recovery_More_Util;

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

class Pixelio_Cart_Abandon_Recovery_More_Uuid_Repository
{
	private string $uuid_to_contact;
	private mixed $pixelio_wordpress_wrapper;
	private mixed $wpdb;
	public function __construct($pixelio_wordpress_wrapper)
	{
		$this->pixelio_wordpress_wrapper = $pixelio_wordpress_wrapper;
		$this->wpdb = $pixelio_wordpress_wrapper->pixelio_get_wpdb();
		$this->uuid_to_contact = $this->wpdb->prefix . Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_plugin_db_prefix . 'uuid_to_contact';

	}


	public function pixelio_get_uuid_by_user_id(string $user_id): ?int
	{

		$user_uuid = $this->wpdb->get_var(
			$this->wpdb->prepare(
				"SELECT user_uuid FROM {$this->uuid_to_contact} WHERE user_id = %s LIMIT 1",
				$user_id
			)
		);

		return $user_uuid ? (int)$user_uuid : 0;
	}

	public function pixelio_get_user_id_by_uuid(string $uuid): ?int
	{


		$user_id = $this->wpdb->get_var(
			$this->wpdb->prepare(
				"SELECT user_id FROM {$this->uuid_to_contact} WHERE user_uuid = %s LIMIT 1",
				$uuid
			)
		);

		return $user_id ? (int)$user_id : -1;
	}

	/**
	 * Add or update UUID for a contact.
	 * If user_id is provided, it will update the record.
	 *
	 * @param string $uuid User UUID
	 * @param int|null $user_id Optional WordPress user_id
	 * @param string|null $email Optional email to create a new contact if needed
	 * @return int|null Contact ID on success, null on failure
	 */
	public function pixelio_add_or_update_uuid($uuid, ?int $user_id = 0): ?int
	{

		$uuid = trim($uuid);
		if (empty($uuid)) {
			return null;
		}
		// 1️⃣ Try to find by UUID
		$contact = $this->wpdb->get_row(
			$this->wpdb->prepare(
				"SELECT id, user_id FROM {$this->uuid_to_contact} WHERE user_uuid = %s LIMIT 1",
				$uuid
			)
		);

		if ($contact) {
			// Update user_id if provided
			if ($user_id && $contact->user_id != $user_id) {
				$this->wpdb->update(
					$this->uuid_to_contact,
					['user_id' => $user_id],
					['id' => $contact->id],
					['%d'],
					['%d']
				);
			}
			return (int)$contact->id;
		}

		$this->wpdb->insert(
			$this->uuid_to_contact,
			[
				'user_uuid' => $uuid,
				'user_id' => $user_id,
				'created_at' => $this->pixelio_wordpress_wrapper->pixelio_current_time(),
			],
			['%s', '%d', '%s']
		);

		return $this->wpdb->insert_id ?: null;
	}
}
