<?php

namespace common\logic\Distribution\Distribution\Export;

use common\helpers\CSV;
use common\logic\AbstractGenerator;
use common\logic\Distribution\Distribution\Model\Distribution;
use common\logic\Order\Order\Repository\OrderRepository;
use common\logic\Order\Order\Service\OrderSolver;
use common\logic\Product\Product\Repository\ProductRepository;
use common\logic\Product\Product\Service\ProductSolver;

class DistributionReportTotalProductCsvGenerator extends AbstractGenerator implements DistributionExportGeneratorInterface
{
    protected ProductRepository $productRepository;
    protected ProductSolver $productSolver;
    protected OrderRepository $orderRepository;
    protected OrderSolver $orderSolver;

    public function loadDependencies(): void
    {
        $this->productRepository = $this->loadService(ProductRepository::class);
        $this->orderRepository = $this->loadService(OrderRepository::class);
        $this->productSolver = $this->loadService(ProductSolver::class);
        $this->orderSolver = $this->loadService(OrderSolver::class);
    }

    public function generate(Distribution $distribution, bool $save = false)
    {
        $datas = [];
        $productsArray = $this->productRepository->findProductsByDistribution($distribution);
        $ordersArray = $this->orderRepository->findOrdersByDistribution($distribution);

        foreach($productsArray as $product) {
            $datas[] = [
                $this->productSolver->getNameExport($product),
                $this->orderSolver->getProductQuantityPiecesByOrders($product, $ordersArray)
            ];
        }

        CSV::send('Total_produits_' . $distribution->date . '.csv', $datas);
    }
}