<?php

use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\OrderingBundle\Util\Delivery\DeliveryDatesService;
use KupShop\OrderingBundle\Util\Order\DeliveryInfo;

/**
 * Return array with three items:
 * - 'list' - List of deliveries. Each delivery has new property 'date'.
 * - 'min' - Array of precomputed minimal values across the deliveries.
 * - 'variations' - List of the variations of the `products`. Each variation is the array with the properties 'list' and 'min' related to the variation.
 *
 * @note If you don't need variations, use tag `get_delivery_dates`.
 *
 * @param product  product that is used to restrict list of deliveries and delivery dates
 * @param only_supported  if true, deliveries are filtered by the restrictions of the shop settings and `product` properties (default: true)
 * @param price  price that is used to restrict list of deliveries
 *
 * @return array|void
 */
function smarty_function_get_variations_delivery_dates($params, &$smarty)
{
    if (empty($params['product'])) {
        throw new InvalidArgumentException('Missing required parameter \'product\'');
    }

    /** @var DeliveryDatesService $deliveryDates */
    $deliveryDates = ServiceContainer::getService(DeliveryDatesService::class);

    /** @var DeliveryInfo $deliveryInfo */
    $deliveryInfo = ServiceContainer::getService(DeliveryInfo::class);

    $only_supported = true;
    $product = null;
    $price = null;

    extract($params);

    $price = $product->getProductPrice();
    $purchaseState = $deliveryDates->initPurchaseState($product, $price);

    $activeDeliveries = $deliveryDates->filterDeliveries(Delivery::getAll(), $only_supported, $price, $purchaseState);
    $minDeliveryPrice = $deliveryDates->calcMinDeliveryPrice($activeDeliveries);

    $productList = $deliveryDates->initializeProductCollection($product, true);

    $deliveriesDates = $deliveryInfo->getProductsDeliveriesDeliveryDates($productList, $activeDeliveries);

    $variationResults = [];
    $dateMinInPerson = null;
    $dateMinDelivery = null;

    list($variationResults, $dateMinInPerson, $dateMinDelivery) = $deliveryDates->calcResultsForEachVariation($deliveriesDates,
        $activeDeliveries,
        $minDeliveryPrice,
        $variationResults,
        $dateMinInPerson,
        $dateMinDelivery);

    $deliveriesList = $deliveryDates->calcTotalDeliveryListForVariations($activeDeliveries, $deliveriesDates);

    $totalResult = [
        'list' => $deliveriesList,
        'min' => [
            'in_person' => $dateMinInPerson,
            'delivery' => $dateMinDelivery,
            'total' => min($dateMinDelivery, $dateMinInPerson),
            'deliveryPrice' => $minDeliveryPrice,
        ],
        'variations' => $variationResults,
    ];

    if (!empty($assign)) {
        $smarty->assign($assign, $totalResult);
    } else {
        return $totalResult;
    }
}
