<?php

namespace Modules\Additional\Specifique\Client114\Modules\Facture\Controller;

use GuzzleHttp\Psr7\Response;
use Skeleton\Controller\Controller;
use Helpers\Outil\Sql;
use Helpers\Trad\Trad;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Parametres\Constante;

// use Modules\Additional\Specifique\Client114\Modules\Facture\Repository\CreationFacture;

class BapPartielController extends Controller
{

    
    public function bapPartielAction()
    {
        $post = $this->request->getParsedBody();
       
        
        $trad = $this->getTranslationService();
        
        $numFixe = Sql::dilispec($this->pdo, 'PARNCS0114', 'NCS_FAC_ENT_BAP_PARTIEL');

        return new Response(200, [
            
        ], $this->renderer->render('@Specifique114Facture/bap-partiel/bap-partiel', [
            'post' => $post,
            'numFixe' => $numFixe,
            'titrePopup' => Trad::strBuild($trad->t("Litige pour la facture N° @1@"), $post['numFact']),
        ]));
    }

    public function validationAction()
    {
        $post = $this->request->getParsedBody();
        $numFact  = $this->request->getAttribute('numFact');
       
        
        $trad = $this->getTranslationService();
        
        $numFixe = Sql::dilispec($this->pdo, 'PARNCS0114', 'NCS_FAC_ENT_BAP_PARTIEL');
        $factEnt = new \Entity\Model\FactEnt($this->pdo);
        $factEnt = $factEnt->find($numFact);
        $spliter = Constante::spliter;
        $keyCS = 'CS_EXTENTION'.$spliter.'FAC_ENT'.$spliter.''.$spliter.$numFixe;
        
        $validator = $this->createValidator();
        $validator->validatorCS('FAC_ENT', '', $post, $this->pdo);
        if ($validator->isValid()) {
            $validator->isTrue($post[$keyCS] > $factEnt['TOTAL_TTC'], $trad->t("Le montant de BAP partiel ne peut pas être supérieur au montant de la facture, veuillez le modifier."));
        }
        
        if ($validator->isValid()) {
            $champSupp = new ChampSupp($this->pdo);
            $retourSQL = $champSupp->updateChampSupp('FAC_ENT', $champSupp::autoCompletCodeEnr($numFact), $numFixe, $post[$keyCS], $this->pdo);

            if ($retourSQL) {
                return new Response(200, [
                    
                ], json_encode(['statut' => 'O']));
            } else {
                return new Response(200, [
                        
                ], json_encode(['erreur' => $trad->t("Erreur lors de l'enregistrement du montant de BAP Partiel"), 'statut' => 'E']));
            }
        } else {
            return new Response(200, [
                    
            ], json_encode(['erreur' => $validator->getError(), 'statut' => 'E']));
        }
    }
}
