<?php

namespace PixelioCartAbandonRecoveryMore\Admin\Services;

if (!defined('ABSPATH')) exit;
use PixelioCartAbandonRecoveryMore\Admin\Wrapper\Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper;
use PixelioCartAbandonRecoveryMore\Frontend\Repositories\Pixelio_Cart_Abandon_Recovery_More_User_Contact_Repository;
use PixelioCartAbandonRecoveryMore\Includes\Utils\Pixelio_Cart_Abandon_Recovery_More_Util;

class Pixelio_Cart_Abandon_Recovery_More_Segmentation_Customer_Profile_Sync_Service
{

	private array $collectors;
	private Pixelio_Cart_Abandon_Recovery_More_Util $pixelio_util;
	private Pixelio_Cart_Abandon_Recovery_More_User_Contact_Repository $contactRepo;
	private Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $wordpress_wrapper;

	public function __construct(array $collectors, Pixelio_Cart_Abandon_Recovery_More_Util $pixelio_util,Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $wordpress_Wrapper,Pixelio_Cart_Abandon_Recovery_More_User_Contact_Repository $contactRepo)
	{
		$this->collectors = $collectors;
		$this->pixelio_util = $pixelio_util;
		$this->wordpress_wrapper = $wordpress_Wrapper;
		$this->contactRepo = $contactRepo;
	}


	function pixelio_send_scoring_unlock_cron(): void
	{
		$lock = $this->wordpress_wrapper->pixelio_delete_transient('pixelio_send_scoring_lock');
	}
	function pixelio_send_scoring_cron_lock(): bool
	{
		$lock = $this->wordpress_wrapper->pixelio_get_transient('pixelio_send_scoring_lock');
		if ($lock && $lock > time()) {
			return false;
		}

		$this->wordpress_wrapper->pixelio_set_transient('pixelio_send_scoring_lock', time() + 600, 600);

		return true;
	}
	public function pixelio_cart_abandon_recovery_more_sync(): void
	{
		if(!$this->pixelio_send_scoring_cron_lock()){
			return;
		}
		$allContacts = $this->contactRepo->pixelio_get_all_customers();
		if (empty($allContacts)) return;

		$emailToUuid = [];
		$allEmails = [];

		foreach ($allContacts as $contact) {
			if (empty($contact->email)) continue;

			$email = $this->pixelio_cart_abandon_recovery_more_normalize_email($contact->email);

			$emailToUuid[$email][] = $contact->user_uuid;
			$allEmails[] = $email;
		}

		$chunks = array_chunk($allEmails, 500);

		$lastIndex = (int) get_option('pixelio_scoring_last_index', 0);

		$dataPerCustomer = [];

		for ($i = $lastIndex; $i < count($chunks); $i++) {

			foreach ($this->collectors as $collector) {

				$results = $collector->pixelio_cart_abandon_recovery_more_collect($chunks[$i]);

				foreach ($results as $email => $metrics) {

					$email = $this->pixelio_cart_abandon_recovery_more_normalize_email($email);

					if (!isset($emailToUuid[$email])) continue;

					$customerUuids = $emailToUuid[$email];

					foreach ($customerUuids as $customerUuid) {

						if (!isset($dataPerCustomer[$customerUuid])) {
							$dataPerCustomer[$customerUuid] = [];
						}

						$dataPerCustomer[$customerUuid] = array_merge(
							$dataPerCustomer[$customerUuid],
							$metrics
						);
					}
				}
			}

			if (!empty($dataPerCustomer)) {

				$payload = [];

				foreach ($dataPerCustomer as $customerUuid => $metrics) {
					$payload[] = [
						'uuid' => $customerUuid,
						'metrics' => $metrics
					];
				}

				$this->pixelio_cart_abandon_recovery_more_send_to_api($payload);

				$dataPerCustomer = []; // reset mémoire
			}

			update_option('pixelio_scoring_last_index', $i + 1);

			if (function_exists('wp_doing_cron') && wp_doing_cron()) {
				@set_time_limit(20);
			}
		}

		delete_option('pixelio_scoring_last_index');
		$this->pixelio_send_scoring_unlock_cron();
	}

	private function pixelio_cart_abandon_recovery_more_normalize_email(string $email): string
	{
		return strtolower(trim(sanitize_email($email)));
	}
	private function pixelio_cart_abandon_recovery_more_send_to_api(array $payload): void
	{
		$this->pixelio_util->pixelio_cart_abandon_recovery_more_call_api($this->pixelio_util->pixelio_cart_abandon_recovery_more_get_url() .'scoring/profile', "POST",
			$payload);

	}
}
