<?php

namespace Modules\Reception\Controller;

use GuzzleHttp\Psr7\Response;
use Helpers\Outil\Roles;
use Helpers\Pagination\PaginatorGestion;
use Helpers\Trad\ITrad;
use Modules\Reception\Repository\CreationBR;
use Modules\Reception\Repository\Lot;
use Modules\Reception\Service\CreationBRService;
use Modules\Reception\Service\LotService;
use Skeleton\Controller\Controller;

class LotController extends Controller
{
    /**
     * @var array<mixed>
     */
    protected array $droits = [];

    private LotService $service;
    private CreationBRService $serviceCreation;
    private Lot $repository;
    private CreationBR $repositoryCreation;
    private ITrad $trad;
    private PaginatorGestion $paginator;


    /**
     * init
     * gestion des droits
     *
     * @return void
     */
    public function init(): void
    {
        $this->service            = new LotService($this->pdo, $this->getTranslationService());
        $this->serviceCreation    = new CreationBRService($this->pdo, $this->getTranslationService());
        $this->repository         = new Lot($this->pdo);
        $this->repositoryCreation = new CreationBR($this->pdo);
        $this->paginator          = new PaginatorGestion();
        $this->trad               = $this->getTranslationService();

        $droits = [
            // Droit de visu des prix des commandes sur BR
            'HA_BR_PX' => Roles::droitsUtilisateur($this->pdo, 'HA_BR_PX', $_SESSION["Session_Login"]),
        ];

        $this->droits = $droits;
    }

    /**
     * ajaxAddBatchAction
     * ajoute une ligne de répartition par lots sur une ligne de BR
     *
     * @return Response|string
     */
    public function ajaxAddBatchAction()
    {
        $line = $this->request->getAttribute('line');
        if ($this->service->addBatch($line)) {
            $lineDetail = $this->repositoryCreation->getOxaBrLigne($_SESSION['Session_Login'], $line);

            $lot = [
                'NO_LOT'    => 0,
                'QTE_LOT'   => 0,
                'DTE_PEREM' => '00000000',
            ];
            return $this->renderer->render('@Reception/Lot/ajaxAddBatch', [
                'line'    => $lineDetail,
                'lot'     => $lot
            ]);
        } else {
            return new Response(400, [], (string)json_encode(
                $this->trad->t('Renseignez ce lot avant d\'en ajouter un nouveau')
            ));
        }
    }

    /**
     * ajaxUpdateBatchAction
     *
     * @return Response|string
     */
    public function ajaxUpdateBatchAction()
    {
        $post = $this->request->getParsedBody();
        $explode = explode('-', $post['field']);
        $field = $explode[0];
        $line = $explode[1];
        $batch = $explode[2] ?? '';

        $result = $this->service->updateBatch($line, $field, $batch, $post['value']);
        $lineDetail = $this->repositoryCreation->getOxaBrLigne($_SESSION['Session_Login'], $line);
        $order = $this->repositoryCreation->getInfoBrEntete($_SESSION['Session_Login'], 'no_cde')['no_cde'];

        $this->serviceCreation->setSubArianeForResponse($order);

        if (is_array($result)) {
            return new Response(200, [], (string)json_encode([
                'batch' => $this->renderer->render('@Reception/Lot/ajaxAddBatch', [
                    'line'                  => $lineDetail,
                    'lot'                   => $result['batch'],
                ]),
                'disabledExpirationDate'    => $result['disabledExpirationDate'],
                'toBeDistributed'           => number_format((float)$result['toBeDistributed'], $lineDetail['NB_DECIM']),
                'subAriane'                 => $this->renderer->render('@Reception/Creation/arianeSub')
            ]));
        } else {
            return new Response();
        }
    }

    /**
     * ajaxRemoveBatchAction
     * retire une ligne de répartition par lots sur une ligne de BR
     *
     * @return Response
     */
    public function ajaxRemoveBatchAction(): Response
    {
        $line = $this->request->getAttribute('line');
        $batch = $this->request->getAttribute('batch') ?? '';
        $result = $this->service->removeBatch($line, $batch);

        $lineDetail = $this->repositoryCreation->getOxaBrLigne($_SESSION['Session_Login'], $line);
        $order = $this->repositoryCreation->getInfoBrEntete($_SESSION['Session_Login'], 'no_cde')['no_cde'];

        $this->serviceCreation->setSubArianeForResponse($order);

        if (is_array($result) && !empty($result)) {
            return new Response(200, [], (string)json_encode([
                'batch' => $this->renderer->render('@Reception/Lot/ajaxAddBatch', [
                    'line'                  => $lineDetail,
                    'lot'                   => $result['batch'],
                ]),
                'disabledExpirationDate'    => false,
                'toBeDistributed'           => number_format((float)$result['toBeDistributed'], $lineDetail['NB_DECIM']),
                'subAriane'                 => $this->renderer->render('@Reception/Creation/arianeSub'),
                'onlyOneBatch'              => $result['onlyOneBatch'],
            ]));
        } else {
            return new Response();
        }
    }

    /**
     * listeLotsAction
     * affiche la liste des lots disponibles pour la répartition des quantités de lignes de BR
     *
     * @return string
     */
    public function listeLotsAction(): string
    {
        $post = $this->request->getParsedBody();

        $listeLots = $this->repository->listeLots($post);
        $infoPagination = $this->paginator->getInfoPagination();

        return $this->renderer->render('@Reception/Lot/listeLots', [
            'infoPagination'    => $infoPagination,
            'post'              => $post,
            'list'         => $listeLots,
            'path'              => 'Reception.Lot.listeLots',
            'titrePopup'    => $this->trad->t('Liste des lots'),
        ]);
    }

    public function ajaxUpdateBatchReturnAction(): Response
    {
        $post = $this->request->getParsedBody();
        $this->service->updateBatchReturn($post['brNumber'], $post['line'], $post['batch'], $post['field'], $post['value']);

        return new Response();
    }
}
