<?php
namespace Modules\Panier\Controller;

use Entity\Model\Bdd;
use Entity\Model\Messstan;
use Entity\Model\OxaUserPanier;
use Entity\Model\OxaUserPanierFour;
use Entity\Model\OxaUserPanierFourClause;
use Entity\Model\OxaUserPanierFourDoc;
use Entity\Model\OxaUserPanierFourPj;
use Entity\Model\OxaUserPanierLigne;
use Entity\Model\PJTypes;
use GuzzleHttp\Psr7\Response;
use Helpers\Fichier\Fichier;
use Helpers\Outil\Outils;
use Helpers\Outil\Roles;
use Helpers\Outil\Sql;
use Helpers\Parametres\Constante;
use Modules\Panier\Repository\PanierFrs;
use Modules\Panier\Repository\PanierLigne;
use Modules\Panier\Service\OutilPanierService;
use Modules\Panier\Service\PanierFrsService;
use Modules\Panier\Service\PanierLigneService;
use Skeleton\Controller\Controller;

class TabBlocFrsController extends Controller
{
    /**
     * @var array<mixed> $parametrage
     */
    public $parametrage;

    public function init() : void
    {
        $trad = $this->getTranslationService();

        $this->parametrage = OutilPanierService::parametragePanier($this->pdo, $trad);
    }

    public function chargeTabFrsAction() : string
    {
        $trad = $this->getTranslationService();
        $tab        = $this->request->getAttribute('tab');
        $idBlocfrsSave  = $this->request->getAttribute('idBlocFrs');

        $panierLigneRepo = new PanierLigne($this->pdo);
        $panierFrsRepo = new PanierFrs($this->pdo);

        $panier = (new OxaUserPanier($this->pdo))->find([
            'id_user' => $_SESSION['id_user'],
            'id_panier' => $_SESSION['id_panier']
        ]);

        $idBlocfrs = str_replace(Constante::oxaPipe, '|', $idBlocfrsSave);

        $infoBloc = (new OxaUserPanierFour($this->pdo))->find([
            'id_user' => $_SESSION['id_user'],
            'id_panier' => $_SESSION['id_panier'],
            'CRITERE_REGROUP' => $idBlocfrs
        ]);

        $explodeID = explode('|', $idBlocfrs);

        $messageErreur = '';

        switch ($tab) {
            case 'clauses':
                if (!Sql::boolSql($infoBloc['flg_add_clause']) && $infoBloc['COD_FOURN'] != '') {
                    (new PanierFrsService($this->pdo))->initClause($infoBloc, $panier['CODE_STE'], $infoBloc['TYP_ACH']);
                }

                $clauses = (new OxaUserPanierFourClause($this->pdo))->findAll([
                    'id_user'           => $_SESSION['id_user'],
                    'id_panier'         => $_SESSION['id_panier'],
                    'CRITERE_REGROUP'   => $idBlocfrs
                ]);
                break;
            case 'livraison':
            case 'imputation':
                $listeLigne = $panierLigneRepo->getListeLigneForLivraisonImputation($idBlocfrs);

                $modeTransport = false;
                foreach ($listeLigne as $ligne) {
                    if (Sql::boolSql($ligne['TRS_INTER'])) {
                        $modeTransport = true;
                    }
                }
                break;
            case 'info_frs':
                $listeBDD = (new Bdd($this->pdo))->getAllBDD('Fournisseur', $explodeID[0], 'F');
                break;
            case 'instruction_frs':
                $infoFrs = (new OxaUserPanierFour($this->pdo))->find([
                    'id_user'           => $_SESSION['id_user'],
                    'id_panier'         => $_SESSION['id_panier'],
                    'CRITERE_REGROUP'   => $idBlocfrs
                ]);

                $codMessage = (new Messstan($this->pdo))->fetch(['TOP 1 CODE_MSG'], \PDO::FETCH_ASSOC);
                break;
            case 'pieces_jointes':
                if (!Sql::boolSql($infoBloc['flg_add_pj'])) {
                    $panierFrsService = new PanierFrsService($this->pdo);

                    $panierFrsService->initDoc(
                        $infoBloc,
                        $panier['CODE_STE'],
                        $explodeID[2],
                        $panier['OUPA_CENTRE_EMETTEUR'],
                        $explodeID[0],
                        $messageErreur
                    );

                    $panierFrsService->initPjTypeAchat(
                        $infoBloc,
                        $panier['CODE_STE'],
                        $infoBloc['TYP_ACH'],
                        $messageErreur
                    );
                }

                if ($messageErreur != '') {
                    $messageErreur = $trad->t('Erreur dans l\'initialisation des pièces jointes. Les fichiers des documents suivants n\'ont pas pu être recopiés :') . "\n" . $messageErreur;
                }

                $listePj = (new OxaUserPanierFourPj($this->pdo))->findAll([
                    'id_user'           => $_SESSION['id_user'],
                    'id_panier'         => $_SESSION['id_panier'],
                    'CRITERE_REGROUP'   => $idBlocfrs
                ]);
                break;
            case 'documents':
                $listeDoc = (new OxaUserPanierFourDoc($this->pdo))->getListeDoc($_SESSION['id_user'], $_SESSION['id_panier'], $idBlocfrs);
                break;
            case 'liste_articles':
                break;
        }

        if ($messageErreur) {
            $messageErreur = $this->renderer->render('@popup-erreur/information', [
                'message' => $messageErreur,
            ]);
        }

        return $this->renderer->render('@Panier/Panier/tab_frs/_'.$tab, [
            'parametrage'   => $this->parametrage,
            'idBlocfrs'     => $idBlocfrsSave,
            'panier'        => $panier,

            //livraison
            //imputation
            'listeLigne'    => $listeLigne??[],
            'modeTransport' => $modeTransport??false,

            //instruction_frs
            'infoFrs'       => $infoFrs??[],
            'codMessage'    => $codMessage??'',
            'droit'         => [
                'HA_DA_COND'            => Roles::droitsUtilisateur($this->pdo, 'HA_DA_COND'),
                'HA_DA_TTCT'            => roles::droitsUtilisateur($this->pdo, 'HA_DA_TTCT'),
            ],

            //clauses
            'clauses'       => $clauses??[],

            //PJ
            'listePJ'       => $listePj??[],

            //doc
            'listeDoc'      => $listeDoc??[],

            //infoFrs
            'listeBDD'      => $listeBDD??[],

            'messageErreur' => $messageErreur,
            
        ]);
    }

    /* ********************
        ACTION TAB CLAUSE
       ********************
    */

    public function ajaxAddClauseAction():string
    {
        $idBlocfrsSave  = $this->request->getAttribute('idBlocFrs');

        $idBlocfrs = str_replace(Constante::oxaPipe, '|', $idBlocfrsSave);

        $infoBloc = (new OxaUserPanierFour($this->pdo))->find([
            'id_user' => $_SESSION['id_user'],
            'id_panier' => $_SESSION['id_panier'],
            'CRITERE_REGROUP' => $idBlocfrs
        ]);

        $oxaUserPanierFourClause = new OxaUserPanierFourClause($this->pdo);

        $insertClause = [
            'id_user'               => $_SESSION['id_user'],
            'id_panier'             => $_SESSION['id_panier'],
            'CRITERE_REGROUP'       => $idBlocfrs,

            'COD_FOURN'             => $infoBloc['COD_FOURN'],
            'CONTENU'               => '',
            'TYP_ACH'               => '',
            'numerique_VERROU'      => sql::FALSE,
            'numerique_CLAU_FIX'    => sql::FALSE,
        ];
        $oxaUserPanierFourClause->insert($insertClause);

        $lastId = $oxaUserPanierFourClause->getLastInsertId('oxa_users_panier_four_clause', 'num_lig');
        return $this->renderer->render('@Panier/Panier/tab_frs/_ligne_clause', [
            'clause' => $insertClause+[
                'num_lig' => $lastId
            ]
        ]);
    }

    /**
     * @return Response
     */
    public function ajaxRemoveClauseAction()
    {
        $idClause  = $this->request->getAttribute('idClause');

        (new OxaUserPanierFourClause($this->pdo))->delete($idClause);
     
        return new Response(200);
    }
    

    /* ********************
        ACTION TAB DOC
       ********************
    */


    /**
     * @return Response
     */
    public function ajaxRemoveDocAction()
    {
        $idBlocfrsSave  = $this->request->getAttribute('idBlocFrs');
        $idBlocfrs = str_replace(Constante::oxaPipe, '|', $idBlocfrsSave);

        $numDoc  = $this->request->getAttribute('numDoc');

        $oxauserDoc = new OxaUserPanierFourDoc($this->pdo);

        $doc = $oxauserDoc->find([
            'ID_PANIER' => $_SESSION['id_panier'],
            'ID_USER' => $_SESSION['id_user'],
            'CRITERE_REGROUP' => $idBlocfrs,
            'NUM_DOC' => $numDoc
        ]);

        Fichier::deleteFichierPj($doc['NOM_FIC_FINAL']);

        $oxauserDoc->delete([
            'ID_PANIER' => $_SESSION['id_panier'],
            'ID_USER' => $_SESSION['id_user'],
            'CRITERE_REGROUP' => $idBlocfrs,
            'NUM_DOC' => $numDoc
        ]);
     
        return new Response(200);
    }

    /* ********************
        ACTION TAB PJ
       ********************
    */

    public function ajaxAddPjAction():string
    {
        $idBlocfrsSave  = $this->request->getAttribute('idBlocFrs');

        $listeTmpPJ = (new PJTypes($this->pdo))->fetchAll();
        $tableauPJ = array_column($listeTmpPJ, 'PJLIBELLE', 'PJ_TYPE');

        $pj = (new PJTypes($this->pdo))->find('PJ');

        $param = sql::paravrac($this->pdo, 'PARAMGEN', 'PJ_DA_IMPRIMER_TITRE');
        if ($param) {
            $impTitre = $param=='O';
        } else {
            $impTitre = false;
        }

        $pj['TYPE_PJ']      = 'PJ';
        $pj['LECTURE']      = sql::boolSql($pj['OUVRABLE']);
        $pj['IMP_PJ']       = sql::boolSql($pj['IMPRIMABL']);
        $pj['IMP_TITRE']    = $impTitre;

        $pathEnreg = $this->router->generateUri('GlobalApplication.AjaxPiecesJointes.enregistrementCreationPJ', [
            'MODULE' => 'PANIER',
            'id' => $idBlocfrsSave,
            'action' => 'creation'
        ]);

        return $this->renderer->render('@Panier/Panier/tab_frs/_add_pj', [
            'tableau_pj'            => $tableauPJ,
            'idBlocfrsSave'         => $idBlocfrsSave,
            'pathEnregistrement'    => $pathEnreg,
            'pj'                    => $pj,
        ]);
    }

    public function ajaxEditPJAction():string
    {
        $idBlocfrsSave  = $this->request->getAttribute('idBlocFrs');
        $idPJ = $this->request->getAttribute('idPJ');

        $listeTmpPJ = (new PJTypes($this->pdo))->fetchAll();
        $tableauPJ = array_column($listeTmpPJ, 'PJLIBELLE', 'PJ_TYPE');

        $pathEnreg = $this->router->generateUri('GlobalApplication.AjaxPiecesJointes.enregistrementCreationPJ', [
            'MODULE' => 'PANIER',
            'id' => $idBlocfrsSave,
            'action' => 'modification'
        ]);

        $pj = (new OxaUserPanierFourPj($this->pdo))->find($idPJ);
        $pj['TYPE_PJ'] = $pj['PJ_TYPES'];

        return $this->renderer->render('@Panier/Panier/tab_frs/_add_pj', [
            'tableau_pj'            => $tableauPJ,
            'idBlocfrsSave'         => $idBlocfrsSave,
            'pathEnregistrement'    => $pathEnreg,
            'pj'                    => $pj,
            'mode'                  => 'modification'
        ]);
    }

    /**
     * @return Response
     */
    public function ajaxRemovePJAction()
    {
        $idPJ  = $this->request->getAttribute('idPJ');

        $oxaPj = new OxaUserPanierFourPj($this->pdo);

        $pj = $oxaPj->find($idPJ);

        if (!sql::boolSql($pj['LIEN_FICHIER'])) {
            Fichier::deleteFichierPj($pj['nom_piece_sys']);
        }

        $oxaPj->delete($idPJ);
     
        return new Response(200);
    }

    /* ********************
        ACTION TAB imputation
       ********************
    */

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

        $oxaUserPanierLigne = (new OxaUserPanierLigne($this->pdo))->find($idLigne, ['qte', 'DES_ART', 'CRITERE_REGROUP', 'COD_UNIT']);

        return $this->renderer->render('@Panier/Panier/tab_frs/popupActionImpu', [
            'action' => $action,
            'idLigne' => $idLigne,
            'infoLigne' => $oxaUserPanierLigne,
            'idBlocfrs' => str_replace('|', Constante::oxaPipe, $oxaUserPanierLigne['CRITERE_REGROUP']),
        ]);
    }

    /**
     * @return Response
     */
    public function ajaxActionImpuAction()
    {
        $action = $this->request->getAttribute('action');
        $idLigne = $this->request->getAttribute('idLigne');

        $post = $this->request->getParsedBody();
        $validator = $this->createValidator();
        $trad = $this->getTranslationService();

        $maxValue = null;
        if ($action == 'split') {
            $oxaUserPanierLigne = (new OxaUserPanierLigne($this->pdo))->find($idLigne, ['qte', 'COD_UNIT']);
            $maxValue = $oxaUserPanierLigne['qte'];
            $formatUnite = Outils::getUniteDecimal($this->pdo, $oxaUserPanierLigne['COD_UNIT']);
            $validator->isFloat($trad->t('Quantité'), $post['QTE'], Constante::qteEntier.'.'.$formatUnite, true, $maxValue);
        } else {
            $oxaUserPanierLigne['qte'] = 0;
            $validator->isInteger($trad->t('Quantité'), $post['QTE']);
        }

        if ($validator->isValid()) {
            $panierLigne = new PanierLigneService($this->pdo, $this->pdoOxaFT, 'panier');

            $arrayDuplicate = [
                'idPanier'  => $_SESSION['id_panier'],
                'idUser'    => $_SESSION['id_user'],
                'idLigne'   => $idLigne,
            ];

            if ($action == 'split') {
                $arrayDuplicate += [
                    'qte' => $post['QTE'],
                ];

                $panierLigne->duplicateLigne($arrayDuplicate, true);

                $newQte = ((float)$oxaUserPanierLigne['qte'])-((float)$post['QTE']);
                (new OxaUserPanierLigne($this->pdo))->update([
                    'qte' => $newQte
                ], [
                    'id_panier'     => $_SESSION['id_panier'],
                    'id_user'       => $_SESSION['id_user'],
                    'id_lig'        => $idLigne,
                ]);
            } else {
                for ($i=0; $i<$post['QTE']; $i++) {
                    $panierLigne->duplicateLigne($arrayDuplicate, true);
                }
            }

            return new Response(200);
        } else {
            return new Response(400, [], $validator->getError());
        }
    }
}
