<?php
namespace Modules\GlobalApplication\Controller;

use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Outil\Outils;
use Helpers\Trad\Trad;
use Helpers\Validator\Validator;
use Modules\Commande\Repository\Commande;
use Skeleton\Controller\Controller;
use Entity\Model\OxaBrEntet;

/**
 * @see \Modules\GlobalApplication\Rules\CS
 */
class CSController extends Controller
{
    public function editCSAction() : string
    {
        $module = $this->request->getAttribute('MODULE');
        $id = $this->request->getAttribute('id');
        $trad = $this->getTranslationService();

        $modeModif = true;
        $titreAriane = '';
        if ($module == 'AO_ENTET') {
            $menuActif = $_SESSION['typeMenu'] == 'P2P'? 'eproc':'Consultations';
            $menuLeft = 'gestionAO';
            $titre = $trad->t('Consultations');
            $titreAriane = $trad->t('Modification champs supplémentaires');
            $subTitle = trad::strBuild(
                $trad->t('Modification champs supplémentaires de la consultation @1@'),
                $id
            );
            $idCS = ChampSupp::autoCompletCodeEnr($id, '', 'AO');
            $postVal = true;
        } elseif ($module == 'BR_OXAPROC') {
            $oxaBrEntet = new OxaBrEntet($this->pdo);
            $enteteBr = $oxaBrEntet->find(['login' => $id]);
            
            $menuActif = 'BR';
            $menuLeft = 'eproc';
            $titreAriane = $trad->t('Champs supplémentaires');
            $subTitle = Trad::strBuild(
                $trad->t('Champs supplémentaires du BR de la commande @1@'),
                $enteteBr['no_cde']
            );
            $idCS = $id;
            $postVal = false;
        } elseif ($module == 'CA') {
            $post       = $this->request->getParsedBody();
            $menuActif = '';
            $menuLeft = null;
            $commandeRep = new Commande($this->pdo);
            $commande = $commandeRep->commandeFourniss($id);

            $titreAriane = $trad->t('Modification des CS');
            $subTitle =  Trad::strBuild(
                $trad->t('Modification des CS pour la commande @1@ du fournisseur @2@'),
                $id,
                Outils::convertLibelleGlobal($this->pdo, 'FOURNISS', '', $commande['CODE_FOU'], true)
            );
            $postVal = true;
            $idCs = $id;
            $commandeRep = new Commande($this->pdo);
            
            $ligneItem = $commandeRep->listeLigneCommande($idCs, $post['all']??false);
        } elseif ($module == 'PANIER') {
            $post       = $this->request->getParsedBody();
            $menuActif = '';
            $menuLeft = null;

            $postVal = null;

            $titreAriane = $trad->t('Modification des CS');
            $subTitle =  $trad->t('Modification des CS d\'entête de panier');
        } else {
            $postVal = null;
        }
        
        Ariane::generate(1, $titreAriane);
       
        return $this->renderer->render('@GlobalApplication/ChampSupp/EditCS', [
            'menuActive' => $menuActif??'',
            'menuLeft' => $menuLeft??'',
            'module' => $module??'',
            'titre' => $titre??'',
            'subTitle' => $subTitle??'',
            'modeModif' => $modeModif,
            'id'  => $id??null,
            'idCS' => $idCS??'',
            'postVal' => $postVal,
            'lignes' => $ligneItem??[]
        ]);
    }

    /**
     * @return mixed
     */
    public function validateCSAction()
    {
        $module = $this->request->getAttribute('MODULE');
        $id = $this->request->getAttribute('id');
        $post       = $this->request->getParsedBody();

        $idCS = '';
        $brV1 = false;
        if ($module=='AO_ENTET') {
            $idCS = ChampSupp::autoCompletCodeEnr($id, '', 'AO');
        } elseif ($module=='BR_OXAPROC') {
            $idCS = str_replace('.', '_', $id);
            $module = 'BR_RECEP';
            $brV1 = true;
        } elseif ($module == 'CA') {
            $idCS = ChampSupp::autoCompletCodeEnr($id);
            $module = ['CA_ENTET', 'CA_LIGNE'];
        }

        $validator = $this->createValidator();
        if (is_array($module)) {
            foreach ($module as $mod) {
                $postVal = ($mod == 'CA_ENTET' || $mod == 'CA_LIGNE');
                $validator->validatorCS($mod, $idCS, $post, $this->pdo, '', 0, '', false, null, '', null, $postVal);
            }
        } elseif ($module == 'PANIER') {
            $validator->validatorCS('DA_ENTET', '', $post, $this->pdo);
        } elseif ($module == 'AO_ENTET') {
            $validator->validatorCS($module, $idCS, $post, $this->pdo, '', 0, '', false, null, '', null, true);
        } else {
            $validator->validatorCS($module, $idCS, $post, $this->pdo);
        }

        if ($validator->isValid()) {
            if ($module == 'PANIER') {
                ChampSupp::mergeCSpanier($post, $this->pdo, 'DA_ENTET');
            } else {
                ChampSupp::updateCS($post, $this->pdo, $brV1, $id);
            }

            return new Response(443, [

            ], (string) \json_encode([
                'statut' => 'O',
                'redirectType' => $brV1? 'V1':'',
                'path' => $_SESSION['ariane'][0]['path'],
                'post' => $_SESSION['ariane'][0]['post'],
            ]));
        } else {
            return $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'desactiveRow' => true,
            ]);
        }
    }
}
