<?php

declare(strict_types=1);

namespace KupShop\CatalogBundle\Util\Product;

use Query\Operator;

class ProductGetOnTheWay
{
    public function getOnTheWay($idProduct): array
    {
        return array_merge(
            ['product' => [], 'variations' => []], // BC
            $this->getOnTheWayMulti([$idProduct])[$idProduct] ?? []
        );
    }

    public function getOnTheWayMulti(array $productIds): array
    {
        $qb = sqlQueryBuilder()->select('sii.id_product, sii.id_variation, GREATEST(MIN(si.date_issued), NOW()) as date_arrive, SUM(sii.quantity) + COALESCE(pv.in_store, p.in_store) as quantity')
            ->from('stock_in_items', 'sii')
            ->leftJoin('sii', 'stock_in', 'si', 'si.id = sii.id_stock_in')
            ->leftJoin('sii', 'products', 'p', 'p.id = sii.id_product')
            ->leftJoin('sii', 'products_variations', 'pv', 'pv.id = sii.id_variation')
            ->andWhere(Operator::equals(['si.id_index' => 'future']))
            ->andWhere(Operator::inIntArray($productIds, 'sii.id_product'))
            ->groupBy('sii.id_product, sii.id_variation');

        if ($showMax = findModule(\Modules::PRODUCTS, \Modules::SUB_SHOW_MAX)) {
            $qb->addSelect('COALESCE(pv.in_store_show_max, p.in_store_show_max, '.$showMax.') AS show_max')
                ->leftJoin('sii', 'products', 'p', 'p.id = sii.id_product')
                ->leftJoin('sii', 'products_variations', 'pv', 'pv.id = sii.id_variation');
        }

        $results = $qb->execute()->fetchAll();

        $return = [];
        foreach ($results as $result) {
            $return[$result['id_product']] ??= [];
            $qty = $result['quantity'];
            if ($showMax && $qty > $result['show_max']) {
                $qty = $result['show_max'];
            }
            if ($qty > 0) {
                if (!empty($result['id_variation'])) {
                    $return[$result['id_product']]['variations'][$result['id_variation']] = [
                        'date' => $result['date_arrive'],
                        'dateObject' => new \DateTime($result['date_arrive']),
                        'quantity' => $qty,
                    ];
                } else {
                    $return[$result['id_product']]['product'] = [
                        'date' => $result['date_arrive'],
                        'dateObject' => new \DateTime($result['date_arrive']),
                        'quantity' => $qty,
                    ];
                }
            }
        }

        return $return;
    }
}
