<?php
namespace Modules\Additional\Specifique\Client151\Modules\Suivi\Controller;

use Entity\Model\CaEntet;
use GuzzleHttp\Psr7\Response;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Outil\Sql;
use Modules\Commande\Repository\CommandeEventRepo;
use Skeleton\Controller\Controller;

class SuiviCdeSpecifiqueController extends Controller
{
    /**
     * @return Response
     */
    public function popupAnnulationGideAction()
    {
        $numCde = $this->request->getAttribute('idCde');
        $trad = $this->getTranslationService();

        $numFix = Sql::dilispec($this->pdo, 'PARNCS0151', 'NCS_CA_ENTET_DTEANNULATION_GIDE');
        $codeEnr = str_pad($numCde, 9, '0', STR_PAD_LEFT);

        $dateMajGide =  ChampSupp::getValueCS('CA_ENTET', $codeEnr, $numFix, $this->pdo);

        if ($dateMajGide && $dateMajGide != '00/00/0000') {
            $date = '00/00/0000';
    
            $codeEvent = 'AGI';
            $commentaire = 'Suppression de la MAJ de l\'annulation de la commande dans GIDE le '.Date('d/m/Y').'.';
        } else {
            $date = date('d/m/Y');
    
            $codeEvent = 'GID';
            $commentaire = 'MAJ annulation de la commande dans GIDE le '.date('d/m/Y').'.';
        }

        ChampSupp::updateChampSupp('CA_ENTET', $codeEnr, $numFix, $date, $this->pdo);
    
        $this->insertEvent($numCde, $codeEvent, $commentaire);

        return new Response(200);
    }

    private function insertEvent(string $noCde, string $code, string $commentaire) : void
    {
        $idMemo = sql::updateMemo($this->pdo, '', $commentaire);

        $infoCde = (new CaEntet($this->pdo))->find($noCde, ['AVENANT']);

        (new CommandeEventRepo($this->pdo))->insertEvent([
            'NO_CDE'    => $noCde,
            'AVENANT'   => $infoCde['AVENANT'],
            'CODE'      => $code,
            'TYP_EVE'   => 'I',
            'NM_COMME' => $idMemo
        ]);
    }
}
