<?php

namespace PixelioCartAbandonRecoveryMore\Admin\Services;
if (!defined('ABSPATH')) exit;

use DateTime;
use PixelioCartAbandonRecoveryMore\Admin\Wrapper\Pixelio_Cart_Abandon_Recovery_More_Woocommerce_Wrapper;
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_Order_Service
{
	private Pixelio_Cart_Abandon_Recovery_More_Woocommerce_Wrapper $woocommerce_wrapper;
	private Pixelio_Cart_Abandon_Recovery_More_Wordpress_Wrapper $wordpress_wrapper;
	private Pixelio_Cart_Abandon_Recovery_More_Util $pixelio_util;

	public function __construct($woocommerce_wrapper, $pixelio_util, $wordpress_wrapper)
	{
		$this->woocommerce_wrapper = $woocommerce_wrapper;
		$this->pixelio_util = $pixelio_util;
		$this->wordpress_wrapper = $wordpress_wrapper;
	}

	public function pixelio_cart_abandon_recovery_more_get_recent_order(int $minutes = 60): array
	{

		$after = new DateTime('-' . $minutes . ' minutes');


		$orders = $this->woocommerce_wrapper->pixelio_wc_get_orders([
			'status' => ['completed', 'processing'],
			'limit' => -1
		]);


		return array_filter($orders, function ($order) use ($after) {
			$created = $order->get_date_created();
			if (!$created) return false;

			return $created->format('Y-m-d H:i:s') >= $after->format('Y-m-d H:i:s');
		});
	}

	public function pixelio_cart_abandon_recovery_more_format_orders(array $orders, $product_id): array
	{
		$results = [];

		foreach ($orders as $order) {

			$customer_name = $order->get_billing_first_name();
			$state = $order->get_billing_state();
			$city = $order->get_billing_city();

			$customer_location = $city . ($state ? ', ' . $state : '');

			foreach ($order->get_items() as $item) {

				$order_product_id = $item->get_product_id();

				if ($product_id !== null && $order_product_id != $product_id) {
					continue;
				}

				$product = $item->get_product();

				if (!$product) {
					continue;
				}

				$results[] = [
					'customer_name' => $customer_name,
					'customer_location' => $customer_location,
					'product_name' => $product->get_name(),
					'product_image' => $this->wordpress_wrapper
						->pixelio_wp_get_attachment_url($product->get_image_id()),
					'product_id' => $product->get_id(),
					'min' => $this->pixelio_util
						->pixelio_cart_abandon_recovery_more_time_ago($order->get_date_created()),
				];
			}
		}

		return $results;
	}

}
