<?php

namespace common\logic\Distribution\Distribution\Export;

use common\logic\AbstractGenerator;
use common\logic\Distribution\Distribution\Model\Distribution;
use common\logic\Distribution\ProductDistribution\Repository\ProductDistributionRepository;
use common\logic\Order\Order\Repository\OrderRepository;
use common\logic\Order\Order\Service\OrderBuilder;
use common\logic\PointSale\PointSale\Repository\PointSaleRepository;
use common\logic\Product\Product\Repository\ProductRepository;
use common\logic\Product\ProductCategory\Repository\ProductCategoryRepository;
use kartik\mpdf\Pdf;

class DistributionReportGridPdfGenerator extends AbstractGenerator implements DistributionExportGeneratorInterface
{
    protected OrderRepository $orderRepository;
    protected OrderBuilder $orderBuilder;
    protected ProductDistributionRepository $productDistributionRepository;
    protected PointSaleRepository $pointSaleRepository;
    protected ProductCategoryRepository $productCategoryRepository;
    protected ProductRepository $productRepository;

    public function loadDependencies(): void
    {
        $this->orderRepository = $this->loadService(OrderRepository::class);
        $this->orderBuilder = $this->loadService(OrderBuilder::class);
        $this->productDistributionRepository = $this->loadService(ProductDistributionRepository::class);
        $this->pointSaleRepository = $this->loadService(PointSaleRepository::class);
        $this->productCategoryRepository = $this->loadService(ProductCategoryRepository::class);
        $this->productRepository = $this->loadService(ProductRepository::class);
    }

    public function generate(Distribution $distribution, bool $save = false)
    {
        $producer = $this->getProducerContext();
        $ordersArray = $this->orderRepository->findOrdersByDistribution($distribution);
        $selectedProductsArray = $this->productDistributionRepository->findProductDistributionsByDistribution($distribution);
        $pointsSaleArray = $this->pointSaleRepository->findPointSales();
        foreach ($pointsSaleArray as $pointSale) {
            $this->orderBuilder->initPointSaleOrders($pointSale, $ordersArray);
        }

        $ordersByPage = 22;
        $ordersArrayPaged = [];

        foreach ($pointsSaleArray as $pointSale) {
            $index = 0;
            $indexPage = 0;

            foreach ($pointSale->orders as $order) {
                if (!isset($ordersArrayPaged[$pointSale->id])) {
                    $ordersArrayPaged[$pointSale->id] = [];
                }
                if (!isset($ordersArrayPaged[$pointSale->id][$indexPage])) {
                    $ordersArrayPaged[$pointSale->id][$indexPage] = [];
                }
                $ordersArrayPaged[$pointSale->id][$indexPage][] = $order;

                $index++;

                if ($index == $ordersByPage) {
                    $index = 0;
                    $indexPage++;
                }
            }
        }

        $categoriesArray = $this->productCategoryRepository->findProductCategories();
        array_unshift($categoriesArray, null);
        $productsArray = $this->productRepository->findProductsByDistribution($distribution);

        $viewPdf = '@backend/views/distribution/report-grid';
        $orientationPdf = Pdf::ORIENT_PORTRAIT;

        if ($producer->slug == 'bourlinguepacotille') {
            $viewPdf = '@backend/views/distribution/report-bourlingue';
            $orientationPdf = Pdf::ORIENT_LANDSCAPE;
        }

        $content = \Yii::$app->getView()->render($viewPdf, [
            'date' => $distribution->date,
            'distribution' => $distribution,
            'selectedProductsArray' => $selectedProductsArray,
            'pointsSaleArray' => $pointsSaleArray,
            'categoriesArray' => $categoriesArray,
            'productsArray' => $productsArray,
            'ordersArray' => $ordersArrayPaged,
            'producer' => $producer
        ]);

        $dateStr = date('d/m/Y', strtotime($distribution->date));

        $pdf = new Pdf([
            'mode' => Pdf::MODE_UTF8,
            'format' => Pdf::FORMAT_A4,
            'orientation' => $orientationPdf,
            'destination' => $save ? Pdf::DEST_FILE : Pdf::DEST_BROWSER,
            'filename' => \Yii::getAlias(
                '@app/web/pdf/Commandes-' . $distribution->date . '-' . $producer->id . '.pdf'
            ),
            'content' => $content,
            //'cssFile' => Yii::getAlias('@web/css/distribution/report.css'),
            'cssInline' => '
                        table {
                            border-spacing : 0px ;
                            border-collapse : collapse ;
                            width: 100% ;
                        }
                        
                        table tr th,
                        table tr td {
                            padding: 0px ;
                            margin: 0px ;
                            border: solid 1px #e0e0e0 ;
                            padding: 3px ;
                            vertical-align : top;
                            page-break-inside: avoid !important;
                        }

                        table tr th { 
                            font-size: 10px ;
                        }
                       
                        table tr td { 
                            font-size: 10px ;
                        }
                        
                        table thead tr {
                                line-height: 220px;
                                text-align:left;
                        }
                       
                        .th-user,
                         .td-nb-products {
                                /* width: 35px ; */
                                text-align: center ;
                        }
                        
                        .th-user {
                                padding: 10px ;
                        }
                        
                        .category-name {
                                font-weight: bold ;
                        }
                        
                    ',
            'methods' => [
                'SetHeader' => ['Commandes du ' . $dateStr],
                'SetFooter' => ['{PAGENO}'],
            ]
        ]);

        return $pdf->render();
    }
}