<?php

namespace Modules\DemandeAchat\Controller;

use Entity\Model\DaEntet;
use Entity\Model\DaLigne;
use Entity\Model\DaPlann;
use Entity\Model\Memos;
use Entity\Model\TpEnt;
use GuzzleHttp\Psr7\Response;
use Helpers\CaracCompl\CaracCompl;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Outil\Date;
use Helpers\Trad\Trad;
use Modules\Commande\Service\CalculPlanningService;
use Modules\DemandeAchat\Outil\FormArray;
use Modules\DemandeAchat\Repository\DemandeAchat;
use Modules\DemandeAchat\Repository\ModificationDemandeAchat;
use Modules\DemandeAchat\Service\CreationDemandeAchatService;
use Modules\DemandeAchat\Service\ModificationDemandeAchatService;
use Modules\DemandeAchat\Validator\CreationValidator;
use Modules\TermeDePaiement\Service\TermeDePaiementService;
use Skeleton\Controller\Controller;

class ModificationLigneDemandeAchatController extends Controller
{
    private ModificationDemandeAchatService $service;

    public function init(
        ModificationDemandeAchatService $modificationDemandeAchatService
    ): void {
        $this->service = $modificationDemandeAchatService;
    }

    public function ajaxAjoutLigneAction(
        TpEnt $tpEnt
    ): string {
        $purchaseRequestId = $this->request->getAttribute('idDA');

        $newLine = [];
        $params  = [];
        $lineCs  = [];

        $this->service
            ->initNewLineAndParams($purchaseRequestId, $newLine, $params, $lineCs);

        /* VALUE SELECT */
        $formArray = FormArray::getFormArrays(
            $this->getTranslationService(),
        );

        return $this->renderer->render('@DemandeAchat/Modification/line/line', [
            'tabTransport' => (new CreationDemandeAchatService($this->pdo, $this->getTranslationService()))
                ->getTransportOptions(),
            'idDA' => $purchaseRequestId,
            'da' => (new DaEntet($this->pdo))
                ->find(['NO_DA' => $purchaseRequestId]),
            'planning' => (new DaPlann($this->pdo))
                ->findAll([
                    'NO_DA' => $purchaseRequestId,
                    'NO_PO' => $newLine['NO_PO']
                ]),
            'idLigneCS' => ChampSupp::autoCompletCodeEnr($purchaseRequestId, $newLine['NO_PO'], 'DA_LIGNE'),
            'newLine' => $newLine,
            'initCC' => true,
            'listeCC' => (new CaracCompl(
                $this->pdo,
            ))->getListeCCInit(),
            'lineParam' => $params,
            'open' => true,
            'tabTypeMarchePublic' => $formArray['tabTypeMarchePublic'],
            'tabPeriodicite' => $formArray['tabPeriodicite'],
            'tabPeriode' => $formArray['tabPeriode'],
            'tabJoursAppli' => $formArray['tabJoursAppli'],
            'lineCs' => $lineCs,
            'ModeModif' => false,
            'hasTp' => (bool) $tpEnt->find(['NUM_CDE' => $purchaseRequestId, 'TYPEOBJ' => 'DA_ENTET'])
        ]);
    }

    public function ajaxModificationLigneAction(
        TpEnt $tpEnt
    ): string {
        $purchaseRequestId = $this->request->getAttribute('idDA');
        $post              = $this->request->getParsedBody();

        $modifiedLine = [
            'NO_PO' => $post['index']
        ];
        $params       = [];

        $this->service
            ->initModifiedLineAndParams($purchaseRequestId, $modifiedLine, $params);

        $formArray = FormArray::getFormArrays(
            $this->getTranslationService(),
        );

        return $this->renderer->render('@DemandeAchat/Modification/line/line', [
            'tabTransport' => (new CreationDemandeAchatService($this->pdo, $this->getTranslationService()))
                ->getTransportOptions(),
            'idDA' => $purchaseRequestId,
            'da' => (new DaEntet($this->pdo))
                ->find(['NO_DA' => $purchaseRequestId]),
            'planning' => (new DaPlann($this->pdo))
                ->findAll([
                    'NO_DA' => $purchaseRequestId,
                    'NO_PO' => $post['index']
                ]),
            'newLine' => $modifiedLine,
            'initCC' => false,
            'CC_typeDoc' => 'DA',
            'CC_idDoc' => $purchaseRequestId,
            'CC_idLigne' => $modifiedLine['NO_PO'],
            'listeCC' => $modifiedLine['cc'],
            'lineParam' => $params,
            'open' => true,
            'tabTypeMarchePublic' => $formArray['tabTypeMarchePublic'],
            'tabPeriodicite' => $formArray['tabPeriodicite'],
            'tabPeriode' => $formArray['tabPeriode'],
            'tabJoursAppli' => $formArray['tabJoursAppli'],
            'ModeModif' => true,
            'hasTp' => (bool) $tpEnt->find(['NUM_CDE' => $purchaseRequestId, 'TYPEOBJ' => 'DA_ENTET'])
        ]);
    }

    /**
     * ajaxEditLineItemAction
     *
     * @return Response
     */
    public function ajaxEditLineItemAction(
        TpEnt $tpEnt
    ): Response {
        $post   = $this->request->getParsedBody();
        $params = [];

        $this->service->initItemAndParams($post, $params);

        /* VALUE SELECT */
        $formArray = FormArray::getFormArrays(
            $this->getTranslationService(),
        );

        $cs = $this->service->initLineCs('ARTICLES', $post['ligne_CODE_ART'] ?? '', $post['NO_DA'], $post['NO_PO']);
        $cs = array_merge($cs, $this->service->initLineCs('SSFAM', $post['SSFAM'] ?? '', $post['NO_DA'], $post['NO_PO']));
        $cs = array_merge($cs, $this->service->initLineCs('SECTIMPU', $post['SECTIMP'] ?? '', $post['NO_DA'], $post['NO_PO']));
        $cs = array_merge($cs, $this->service->initLineCs('CODECOMP', $post['CODE_COMP'] ?? '', $post['NO_DA'], $post['NO_PO']));
        $cs = array_merge($cs, $this->service->initLineCs('SSCPTANA', $post['SSCPTEANA'] ?? '', $post['NO_DA'], $post['NO_PO']));

        return $this->createJsonResponse(
            [
                'html' => $this->renderer->render('@DemandeAchat/Modification/line/line', [
                    'tabTransport' => (new CreationDemandeAchatService($this->pdo, $this->getTranslationService()))
                        ->getTransportOptions(),
                    'idDA' => $post['NO_DA'],
                    'da' => (new DaEntet($this->pdo))
                        ->find(['NO_DA' => $post['NO_DA']]),
                    'newLine' => $post,
                    'lineParam' => $params,
                    'open' => true,
                    'tabTypeMarchePublic' => $formArray['tabTypeMarchePublic'],
                    'tabPeriodicite' => $formArray['tabPeriodicite'],
                    'tabPeriode' => $formArray['tabPeriode'],
                    'tabJoursAppli' => $formArray['tabJoursAppli'],
                    'initCC' => true,
                    'listeCC' => (new CaracCompl(
                        $this->pdo,
                        $post['ligne_CODE_ART'] ?? '',
                        $post['SSFAM'] ?? '',
                    ))->getListeCCInit(),
                    'hasTp' => (bool) $tpEnt->find(['NUM_CDE' => $post['NO_DA'], 'TYPEOBJ' => 'DA_ENTET'])
                ]),
                'cs' => $this->_initLineCs($post),
            ],
            200
        );
    }

    /**
     * ajaxEditLineFrameworkAgreementAction
     *
     * @return Response
     */
    public function ajaxEditLineFrameworkAgreementAction(
        TpEnt $tpEnt
    ): Response {
        $post   = $this->request->getParsedBody();
        $params = [];

        $this->service->initLineAcdAndParams($post, $params);

        /* VALUE SELECT */
        $formArray = FormArray::getFormArrays(
            $this->getTranslationService(),
        );

        return $this->createJsonResponse(
            [
                'html' => $this->renderer->render('@DemandeAchat/Modification/line/line', [
                    'tabTransport' => (new CreationDemandeAchatService($this->pdo, $this->getTranslationService()))
                        ->getTransportOptions(),
                    'idDA' => $post['NO_DA'],
                    'da' => (new DaEntet($this->pdo))
                        ->find(['NO_DA' => $post['NO_DA']]),
                    'newLine' => $post,
                    'lineParam' => $params,
                    'open' => true,
                    'tabTypeMarchePublic' => $formArray['tabTypeMarchePublic'],
                    'tabPeriodicite' => $formArray['tabPeriodicite'],
                    'tabPeriode' => $formArray['tabPeriode'],
                    'tabJoursAppli' => $formArray['tabJoursAppli'],
                    'initCC' => true,
                    'listeCC' => (new CaracCompl(
                        $this->pdo,
                        $post['ligne_CODE_ART'] ?? '',
                        $post['SSFAM'] ?? '',
                    ))->getListeCCInit(),
                    'hasTp' => (bool) $tpEnt->find(['NUM_CDE' => $post['NO_DA'], 'TYPEOBJ' => 'DA_ENTET'])
                ]),
                'cs' => $this->_initLineCs($post),
            ],
            200
        );
    }

    /**
     * ajaxEditLineSupplierAction
     *
     * @return Response
     */
    public function ajaxEditLineSupplierAction(
        TpEnt $tpEnt
    ): Response {
        $post   = $this->request->getParsedBody();
        $params = [];

        $this->service->initLineSupplierAndParams($post, $params);

        /* VALUE SELECT */
        $formArray = FormArray::getFormArrays(
            $this->getTranslationService(),
        );

        return $this->createJsonResponse(
            [
                'html' => $this->renderer->render('@DemandeAchat/Modification/line/line', [
                    'tabTransport' => (new CreationDemandeAchatService($this->pdo, $this->getTranslationService()))
                        ->getTransportOptions(),
                    'idDA' => $post['NO_DA'],
                    'da' => (new DaEntet($this->pdo))
                        ->find(['NO_DA' => $post['NO_DA']]),
                    'newLine' => $post,
                    'lineParam' => $params,
                    'open' => true,
                    'tabTypeMarchePublic' => $formArray['tabTypeMarchePublic'],
                    'tabPeriodicite' => $formArray['tabPeriodicite'],
                    'tabPeriode' => $formArray['tabPeriode'],
                    'tabJoursAppli' => $formArray['tabJoursAppli'],
                    'initCC' => true,
                    'listeCC' => (new CaracCompl(
                        $this->pdo,
                        $post['ligne_CODE_ART'] ?? '',
                        $post['SSFAM'] ?? '',
                    ))->getListeCCInit(),
                    'hasTp' => (bool) $tpEnt->find(['NUM_CDE' => $post['NO_DA'], 'TYPEOBJ' => 'DA_ENTET'])
                ]),
                'cs' => $this->_initLineCs($post),
            ],
            200
        );
    }

    /**
     * ajaxEditLineQuantityAction
     *
     * @return Response
     */
    public function ajaxEditLineQuantityAction(
        TpEnt $tpEnt
    ): Response {
        $post   = $this->request->getParsedBody();
        $params = [];
        $this->service->initLineQuantityAndParams($post, $params);

        /* VALUE SELECT */
        $formArray = FormArray::getFormArrays(
            $this->getTranslationService(),
        );

        return $this->createJsonResponse(
            [
                'html' => $this->renderer->render('@DemandeAchat/Modification/line/line', [
                    'tabTransport' => (new CreationDemandeAchatService($this->pdo, $this->getTranslationService()))
                        ->getTransportOptions(),
                    'idDA' => $post['NO_DA'],
                    'da' => (new DaEntet($this->pdo))
                        ->find(['NO_DA' => $post['NO_DA']]),
                    'newLine' => $post,
                    'lineParam' => $params,
                    'open' => true,
                    'tabTypeMarchePublic' => $formArray['tabTypeMarchePublic'],
                    'tabPeriodicite' => $formArray['tabPeriodicite'],
                    'tabPeriode' => $formArray['tabPeriode'],
                    'tabJoursAppli' => $formArray['tabJoursAppli'],
                    'initCC' => true,
                    'listeCC' => (new CaracCompl(
                        $this->pdo,
                        $post['ligne_CODE_ART'] ?? '',
                        $post['SSFAM'] ?? '',
                    ))->getListeCCInit(),
                    'planning' => $post['planning'],
                    'hasTp' => (bool) $tpEnt->find(['NUM_CDE' => $post['NO_DA'], 'TYPEOBJ' => 'DA_ENTET'])
                ]),
                'cs' => $this->_initLineCs($post),
            ],
            200
        );
    }

    /**
     * ajaxEditLineUnitAction
     *
     * @return Response
     */
    public function ajaxEditLineUnitAction(
        TpEnt $tpEnt
    ): Response {
        $post   = $this->request->getParsedBody();
        $params = [];
        $this->service->initLineQuantityAndParams($post, $params);

        /* VALUE SELECT */
        $formArray = FormArray::getFormArrays(
            $this->getTranslationService(),
        );

        return $this->createJsonResponse(
            [
                'html' => $this->renderer->render('@DemandeAchat/Modification/line/line', [
                    'tabTransport' => (new CreationDemandeAchatService($this->pdo, $this->getTranslationService()))
                        ->getTransportOptions(),
                    'idDA' => $post['NO_DA'],
                    'da' => (new DaEntet($this->pdo))
                        ->find(['NO_DA' => $post['NO_DA']]),
                    'newLine' => $post,
                    'lineParam' => $params,
                    'open' => true,
                    'tabTypeMarchePublic' => $formArray['tabTypeMarchePublic'],
                    'tabPeriodicite' => $formArray['tabPeriodicite'],
                    'tabPeriode' => $formArray['tabPeriode'],
                    'tabJoursAppli' => $formArray['tabJoursAppli'],
                    'initCC' => true,
                    'listeCC' => (new CaracCompl(
                        $this->pdo,
                        $post['ligne_CODE_ART'] ?? '',
                        $post['SSFAM'] ?? '',
                    ))->getListeCCInit(),
                    'hasTp' => (bool) $tpEnt->find(['NUM_CDE' => $post['NO_DA'], 'TYPEOBJ' => 'DA_ENTET'])
                ]),
                'cs' => $this->_initLineCs($post),
            ],
            200
        );
    }

    /**
     * ajaxEditLinePriceAction
     *
     * @return Response
     */
    public function ajaxEditLinePriceAction(
        TpEnt $tpEnt
    ): Response {
        $post   = $this->request->getParsedBody();
        $params = [];

        $this->service->initLineQuantityAndParams($post, $params);

        /* VALUE SELECT */
        $formArray = FormArray::getFormArrays(
            $this->getTranslationService(),
        );

        return $this->createJsonResponse(
            [
                'html' => $this->renderer->render('@DemandeAchat/Modification/line/line', [
                    'tabTransport' => (new CreationDemandeAchatService($this->pdo, $this->getTranslationService()))
                        ->getTransportOptions(),
                    'idDA' => $post['NO_DA'],
                    'da' => (new DaEntet($this->pdo))
                        ->find(['NO_DA' => $post['NO_DA']]),
                    'newLine' => $post,
                    'lineParam' => $params,
                    'open' => true,
                    'tabTypeMarchePublic' => $formArray['tabTypeMarchePublic'],
                    'tabPeriodicite' => $formArray['tabPeriodicite'],
                    'tabPeriode' => $formArray['tabPeriode'],
                    'tabJoursAppli' => $formArray['tabJoursAppli'],
                    'initCC' => true,
                    'listeCC' => (new CaracCompl(
                        $this->pdo,
                        $post['ligne_CODE_ART'] ?? '',
                        $post['SSFAM'] ?? '',
                    ))->getListeCCInit(),
                    'hasTp' => (bool) $tpEnt->find(['NUM_CDE' => $post['NO_DA'], 'TYPEOBJ' => 'DA_ENTET'])
                ]),
                'cs' => $this->_initLineCs($post),
            ],
            200
        );
    }

    /**
     * ajaxEditLineSupplierItemAction
     *
     * @return Response
     */
    public function ajaxEditLineSupplierItemAction(): Response
    {
        $post = $this->request->getParsedBody();
        $cs   = $this->service->initLineCs('ARTFOURN', $post['ligne_COD_FAB'] ?? '', $post['NO_DA'], $post['NO_PO']);
        return $this->createJsonResponse(
            [
                'cs' => $cs,
            ],
            200
        );
    }

    /**
     * ajaxEditLineCodeCompAction
     *
     * @return Response
     */
    public function ajaxEditLineCodeCompAction(): Response
    {
        $post = $this->request->getParsedBody();
        $cs   = $this->service->initLineCs('CODECOMP', $post['ligne_CODE_COMP'] ?? '', $post['NO_DA'], $post['NO_PO']);
        return $this->createJsonResponse(
            [
                'cs' => $cs,
            ],
            200
        );
    }

    /**
     * ajaxEditLineSectImpAction
     *
     * @return Response
     */
    public function ajaxEditLineSectImpAction(): Response
    {
        $post = $this->request->getParsedBody();
        $cs   = $this->service->initLineCs('SECTIMPU', $post['ligne_SECTIMP'] ?? '', $post['NO_DA'], $post['NO_PO']);
        return $this->createJsonResponse(
            [
                'cs' => $cs,
            ],
            200
        );
    }

    /**
     * ajaxEditLineSsCptAnaAction
     *
     * @return Response
     */
    public function ajaxEditLineSsCptAnaAction(): Response
    {
        $post = $this->request->getParsedBody();
        $cs   = $this->service->initLineCs('SSCPTANA', $post['ligne_SSCPTEANA'] ?? '', $post['NO_DA'], $post['NO_PO']);
        return $this->createJsonResponse(
            [
                'cs' => $cs,
            ],
            200
        );
    }

    /**
     * ajaxEditLineSsFamAction
     *
     * @return Response
     */
    public function ajaxEditLineSsFamAction(): Response
    {
        $post        = $this->request->getParsedBody();
        $imputations = $this->service->initLineImputations('SSFAMILL', $post['NO_DA'], $post);
        $cs          = $this->service->initLineCs('SSFAMILL', $post['ligne_SSFAM'] ?? '', $post['NO_DA'], $post['NO_PO']);
        return $this->createJsonResponse(
            [
                'cs' => $cs,
                'imputations' => $imputations,
            ],
            200
        );
    }

    public function ajaxGeneratePlanningAction(): string
    {
        $post = $this->request->getParsedBody();

        Date::dateToSql($post['ligne_DATEDEBCONT']);
        Date::dateToSql($post['ligne_DATEFINCONT']);

        $calculPlanningService = new CalculPlanningService(
            $post['ligne_QTE_DEM'],
            ($post['ligne_CONTRAT_PERIOD'] ?? ''),
            $post['ligne_DATEDEBCONT'],
            $post['ligne_DATEFINCONT'],
            ($post['ligne_FIN_DEB_PER'] ?? ''),
            ($post['ligne_DALI_RECEPAUTO_JOUR'] ?? '')
        );
        $calculPlanningService->calculPlanning('DA');
        $planning = $calculPlanningService->getTableauEcheance();

        return $this->renderer->render('@DemandeAchat/Modification/line/_planning', [
            'planning' => $planning,
            'lockPlanning' => true
        ]);
    }

    public function validationLigneAction()
    {
        $purchaseRequestId = $this->request->getAttribute('idDA');
        $post              = $this->request->getParsedBody();
        $trad              = $this->getTranslationService();

        $validator = new CreationValidator($this->pdo, $trad);

        $validator->validateFormLine($purchaseRequestId, $post);

        $idLigne = $post['LIGNE_NO_PO_MODIF'];

        if (!$validator->isValid()) {
            if ($validator->getError() != '') {
                return $this->createJsonResponse(
                    [
                        'type' => 'error',
                        'popupHtml' => $this->renderer->render('@popup-erreur/ErreurCreation', [
                            'ErreurValid' => $validator->getError(),
                        ]),
                    ],
                    400
                );
            }

            if (!isset($post['confirm'])) {
                return $this->createJsonResponse(
                    [
                        'type' => 'confirm',
                        'popupHtml' => $this->renderer->render('@popup-erreur/simpleWarning', [
                            'content' => $validator->getErrorNonBloquant(),
                        ]),
                    ],
                    400
                );
            }
        }

        $update = $this->service->updatePurchaseRequestLine($purchaseRequestId, $idLigne, $post);

        if (is_array($update) && !empty($update)) {
            return $this->createJsonResponse(
                [
                    'html' => $this->renderer->render('@DemandeAchat/Modification/_items', [
                        'da' => $post + ['NO_DA' => $purchaseRequestId],
                        'ligneDA' => (new DemandeAchat($this->pdo))
                            ->listeLigneDemandeAchat($purchaseRequestId),
                        'newLine' => [],
                        'idDA' => $purchaseRequestId,
                    ]),
                    'da' => [
                        'HT' => $update['new_purchase_request_ht'],
                        'TTC' => $update['new_purchase_request_ttc']
                    ],
                ],
            );
        }

        return $this->renderer->render('@popup-erreur/erreurAlerteEtAvertissement', [
            'params' => [
                'statut' => 'E',
                'alerte' => $trad->t("Erreur lors de l'exécution de l'opération.")
            ],
            'titrePopup' => $trad->t("Erreur"),
        ]);
    }

    public function annulationLigneAction(): string
    {
        $purchaseRequestId = $this->request->getAttribute('idDA');
        $post              = $this->request->getParsedBody();

        $lineId = $post['LIGNE_NO_PO_MODIF'];

        $modifDetail = new ModificationDemandeAchat($this->pdo);
        $ligne       = $modifDetail->getLineDetails($purchaseRequestId, $lineId);

        if ($ligne) {
            return $this->renderer->render('@DemandeAchat/Modification/line/non_editable_line', [
                'ligne' => $ligne,
            ]);
        } else {
            return '';
        }
    }

    public function suppressionLigneAction()
    {
        $post              = $this->request->getParsedBody();
        $purchaseRequestId = $post['NO_DA'];
        $daLigne           = new DaLigne($this->pdo);

        $idLigne = $post['index'];
        $ligne   = $daLigne
            ->find([
                'NO_DA' => $purchaseRequestId,
                'NO_PO' => $idLigne
            ]);

        $codeMemo = $ligne['NM_DCOMP'];

        // Suppression de la ligne
        if (($majOK = $daLigne
                ->delete([
                    'NO_DA' => $purchaseRequestId,
                    'NO_PO' => $idLigne
                ]))
            && $codeMemo != 0
        ) {
            // Suppression de la désignation complémentaire
            $majOK = (new Memos($this->pdo))
                ->delete(['NODEMEMO' => $codeMemo]);
        }

        if ($majOK) {
            // Suppression des CS de la ligne
            $majOK = ChampSupp::deleteCS(
                'DA_LIGNE',
                ChampSupp::autoCompletCodeEnr(
                    $purchaseRequestId,
                    $idLigne,
                    'DA_LIGNE'
                ),
                $this->pdo
            );
        }

        if ($majOK) {
            // Mise à jour des montants de l'entête de la DA
            $montantsLignes = (new ModificationDemandeAchat($this->pdo))
                ->montantsLignes($purchaseRequestId);
            $ht             = 0;
            $ttc            = 0;
            foreach ($montantsLignes as $values) {
                $ht += $values['MNT_LIG'];
                $ttc += $values['MNT_LIG'] * (1 + $values['TVA'] / 100);
            }
            $majOK = (new DaEntet($this->pdo))
                ->update(
                    [
                        'TOTAL_DA' => $ht,
                        'TOTAL_DA_TTC' => $ttc
                    ],
                    $purchaseRequestId
                );

            if ($majOK) {
                return new Response(200, [], (string) \json_encode(['HT' => $ht, 'TTC' => $ttc]));
            } else {
                $trad = $this->getTranslationService();
                return new Response(443, [], $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid' => $trad->t("Erreur lors de la mise à jour des montants sur l'entête de la demande d'achat"),
                    'titrePopup' => $trad->t("Erreur"),
                ]));
            }
        } else {
            $trad = $this->getTranslationService();
            return new Response(443, [], $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => Trad::strBuild($trad->t("Erreur lors de la suppression de la ligne @1@"), $idLigne),
                'titrePopup' => $trad->t("Erreur"),
            ]));
        }
    }

    public function ajaxModificationOrdreAction(): string
    {
        $purchaseRequestId = $this->request->getAttribute('idDA');
        $post              = $this->request->getParsedBody();

        $newPosition = $post['newPosition'];
        $oldPosition = $post['oldPosition'];

        $moveUp = false;
        if ($newPosition < $oldPosition) {
            $moveUp = true;
        }

        $modifDetail = new ModificationDemandeAchat($this->pdo);
        $modifDetail->modificationOrdreLigne($purchaseRequestId, $newPosition, $oldPosition, $moveUp);
        $modifDetail->modificationOrdreLigneCS($purchaseRequestId, $newPosition, $oldPosition, $moveUp);

        return '';
    }

    public function popupPlanningAction(): string
    {
        $idDa    = $this->request->getAttribute('idDa');
        $idLigne = $this->request->getAttribute('idLigne');

        $listePlanning = (new DaPlann($this->pdo))
            ->findAll(
                ['NO_DA' => $idDa, 'NO_PO' => $idLigne],
                [],
                ['tri_DTE_LIV' => 'ASC']
            );

        $ligne = (new DaLigne($this->pdo))
            ->find([
                'NO_DA' => $idDa,
                'NO_PO' => $idLigne
            ]);

        return $this->renderer->render('@Commande/GareDeTriage/popupPlanning', [
            'listPlanning' => $listePlanning,
            'ligne' => $ligne,
        ]);
    }

    /**
     * @return mixed
     */
    public function ajaxAddLignePlanningAction()
    {
        $post = $this->request->getParsedBody();

        return $this->renderer->render('@DemandeAchat/Modification/line/_new_planning_line', [
            'ligne' => $post['noLigne'],
        ]);
    }

    /**
     * _initLineCs
     *
     * @param  array<mixed> $post
     * @return array<mixed>
     */
    private function _initLineCs($post)
    {
        $cs = [];
        $cs = $this->service->initLineCs('ARTICLES', $post['ligne_CODE_ART'] ?? '', $post['NO_DA'], $post['NO_PO']);
        $cs = array_merge($cs, $this->service->initLineCs('SSFAM', $post['SSFAM'] ?? '', $post['NO_DA'], $post['NO_PO']));
        $cs = array_merge($cs, $this->service->initLineCs('SECTIMPU', $post['SECTIMP'] ?? '', $post['NO_DA'], $post['NO_PO']));
        $cs = array_merge($cs, $this->service->initLineCs('CODECOMP', $post['CODE_COMP'] ?? '', $post['NO_DA'], $post['NO_PO']));
        $cs = array_merge($cs, $this->service->initLineCs('SSCPTANA', $post['SSCPTEANA'] ?? '', $post['NO_DA'], $post['NO_PO']));

        return $cs;
    }
}
