<?php


namespace admin\segmentations\collectors;

use PixelioCartAbandonRecoveryMore\Admin\Wrapper\Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper;

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


class Pixelio_Cart_Abandon_Recovery_More_Segmentation_Order_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;
	}

	function pixelio_cart_abandon_recovery_more_collect(array $emails)
	{
		$wpdb = $this->pixelio_wordpress_wrapper->pixelio_get_wpdb();

		if (empty($emails)) return [];

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

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

		$query = $wpdb->prepare(
			"
		SELECT
			c.email,
			COUNT(o.order_id) as order_count
		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 = [];

		foreach ($results as $row) {
			$output[$row->email] = [
				'total_orders' => (int) $row->order_count
			];
		}

		// fallback pour emails sans commandes
		foreach ($emails as $email) {
			if (!isset($output[$email])) {
				$output[$email] = [
					'total_orders' => 0
				];
			}
		}

		return $output;
	}
}
