<?php


namespace admin\segmentations\collectors;

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

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


class Pixelio_Cart_Abandon_Recovery_More_Segmentation_Recency_Collectors implements Pixelio_Cart_Abandon_Recovery_More_Segmentation_Collector_Interface
{

	private Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $pixelio_wordpress_wrapper;
	public function __construct(Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $pixelio_wordpress_wrapper)
	{
		$this->pixelio_wordpress_wrapper = $pixelio_wordpress_wrapper;

	}
	public function pixelio_cart_abandon_recovery_more_collect(array $emails): array
	{
		if (empty($emails)) return [];

		$wpdb = $this->pixelio_wordpress_wrapper->pixelio_get_wpdb();

		// sanitize
		$emails = array_map('sanitize_email', $emails);

		$placeholders = implode(',', array_fill(0, count($emails), '%s'));

		$query = $wpdb->prepare(
			"
		SELECT
			c.email,
			MAX(o.date_created) as last_order_date
		FROM {$wpdb->prefix}wc_order_stats o
		JOIN {$wpdb->prefix}wc_customer_lookup c
			ON o.customer_id = c.customer_id
		WHERE c.email IN ($placeholders)
		AND o.status IN ('wc-completed', 'wc-processing')
		GROUP BY c.email
		",
			$emails
		);

		$results = $wpdb->get_results($query);

		$output = [];
		$now = new DateTime();

		foreach ($results as $row) {
			if (!empty($row->last_order_date)) {
				$lastDate = new DateTime($row->last_order_date);
				$days = $lastDate->diff($now)->days;

				$output[$row->email] = [
					'days_since_last_order' => (int)$days
				];
			}
		}

		// fallback → jamais commandé
		foreach ($emails as $email) {
			if (!isset($output[$email])) {
				$output[$email] = [
					'days_since_last_order' => 9999
				];
			}
		}

		return $output;
	}

}
