<?php

namespace PixelioCartAbandonRecoveryMore\Frontend\Services;

if (!defined('ABSPATH')) exit;
use PixelioCartAbandonRecoveryMore\Admin\Wrapper\Pixelio_Cart_Abandon_Recovery_More_Woocommerce_Wrapper;

class Pixelio_Cart_Abandon_Recovery_More_Delivery_Estimator_Service
{
	private Pixelio_Cart_Abandon_Recovery_More_Woocommerce_Wrapper $woocommerce_wrapper;

	public function __construct(Pixelio_Cart_Abandon_Recovery_More_Woocommerce_Wrapper $woocommerce_Wrapper)
	{
		$this->woocommerce_wrapper = $woocommerce_Wrapper;
	}

	public function calculate(int $product_id, string $postcode): array
	{
// 1. Simuler un panier WooCommerce en mémoire
		$product = $this->woocommerce_wrapper->pixelio_wc_get_product($product_id);
		if (!$product) return ['error' => 'Produit introuvable'];
// 2. Construire un package livraison comme WC le fait en checkout
		$package = [
			'destination' => [
				'postcode' => $postcode,
				'country' => $this->woocommerce_wrapper->pixelio_get_base_country(),
			],
			'contents' => [[
				'product_id' => $product_id,
				'quantity' => 1,
				'data' => $product,
			]],
			'contents_cost' => $product->get_price(),
		];
		$shipping = $this->woocommerce_wrapper->pixelio_WC_Shipping();
		$rates = $shipping->calculate_shipping_for_package($package);
		$rates = $rates['rates'] ?? [];
		if (empty($rates)) return ['error' => 'Aucune livraison disponible à ce code postal'];
		// 4. Retourner toutes les méthodes disponibles
		return array_map(fn($rate) => [
			'carrier' => $rate->get_label(),
			'price' => (float)$rate->get_cost(),
			'free' => $rate->get_cost() == 0,
		], array_values($rates));
	}

}
