<?php

namespace PixelioCartAbandonRecoveryMore\Frontend\Repositories;

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_User_Contact_Repository
{
	private Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $pixelio_wordpress_wrapper;
	private $contact ;
	private $wpdb;
	public function __construct(Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $pixelio_wordpress_wrapper)
	{
		$this->pixelio_wordpress_wrapper = $pixelio_wordpress_wrapper;
		$this->wpdb = $pixelio_wordpress_wrapper->pixelio_get_wpdb();
		$this->contact = $this->wpdb->prefix . Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_plugin_db_prefix . 'contacts';
		$this->uuid_contact = $this->wpdb->prefix . Pixelio_Cart_Abandon_Recovery_More_Util::$pixelio_plugin_db_prefix . 'uuid_to_contact';
	}

	public function pixelio_get_all_customers(): array
	{
		global $wpdb;

		$results = $wpdb->get_results(
			"SELECT c.id,u.user_uuid, c.email FROM {$this->uuid_contact} u  INNER  JOIN {$this->contact} c
            ON u.user_id = c.id WHERE c.email != '' ORDER BY u.id ASC"
		);
		return $results ?: [];
	}

	public function pixelio_find_by_email(string $email): ?int
	{
		global $wpdb;

		$user_id = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT c.id FROM {$this->contact} c
             WHERE c.email = %s
             LIMIT 1",
				$email
			)
		);
		return $user_id !== null ? (int) $user_id : null;
	}
}
