<?php

namespace domain\Distribution\Distribution\Export;

use common\helpers\CSV;
use domain\Distribution\Distribution\Distribution;
use domain\Order\Order\OrderRepository;
use domain\Order\Order\OrderSolver;
use domain\Product\Product\ProductRepository;
use domain\Product\Product\ProductSolver;
use domain\_\AbstractGenerator;

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, true,'product.order ASC');
        $ordersArray = $this->orderRepository->findOrdersByDistribution($distribution);

        $datas[] = [
            'Produit',
            'Quantité (pièces)',
            'Poids'
        ];

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

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