<?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_Avg_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;

	}

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

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

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

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

		$query = $wpdb->prepare(
			"
		SELECT
			c.email,
			SUM(o.net_total) as total_spent,
			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 = %s
		GROUP BY c.email
		",
			array_merge($emails, ['wc-completed'])
		);

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

		$output = [];

		foreach ($results as $row) {
			if ($row->order_count > 0) {
				$output[$row->email] = [
					'avg_order_value' => round($row->total_spent / $row->order_count, 2)
				];
			}
		}

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

		return $output;
	}
}
