<?php
namespace Modules\Panier\Controller;

use Entity\Model\Fourniss;
use Entity\Model\OxaUserPanier;
use Entity\Model\OxaUserPanierLigne;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Outil\Sql;
use Modules\Panier\Repository\PanierEntete;
use Modules\Panier\Repository\PanierLigne;
use Modules\Panier\Service\PanierService;
use Modules\Panier\Service\TransferePanierService;
use Modules\RechercheArticles\Repository\Recherche;
use Modules\RechercheArticles\Service\OutilRechercheService;
use Skeleton\Controller\Controller;

class CommandeRegulController extends Controller
{
    private function ctrlSsPeriode():bool
    {
        $ctrlBR  = Sql::paravrac($this->pdo, 'PARAMGEN', 'CTRL_SSPERIODE_BR');
        $ctrlCDE = sql::paravrac($this->pdo, 'PARAMGEN', 'CTRL_SSPERIODE_CDE');
        return ($ctrlBR == 'O' || $ctrlCDE == 'O');
    }

    public function commandeRegulAction():string
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        Ariane::generate(0, $trad->t('Commande de régularisation'));

        $listeModele[''] = $trad->t('Votre choix');
        $listeModeleTmp = false;
        if (isset($post['CODE_FOU']) && $post['CODE_FOU']) {
            $listeModeleTmp = (new PanierEntete($this->pdo))->getPanierModeleForRegul($post['CODE_FOU']);
        }

        if ($listeModeleTmp) {
            $listeModele += array_column($listeModeleTmp, 'lib_panier', 'id_panier');
        }

        
        $outilRechercheService = new OutilRechercheService($this->pdo);
        $centre         = $outilRechercheService->getCentreRecherche();
        
        $param = [
            'ZONE_GEO_ACTIVE'                   => (new Recherche($this->pdo))->zoneGeoActive($centre)['active']? true:false,
            'centreZoneGeo'                     => $centre,
        ];

        return $this->renderer->render('@Panier/General/CommandeRegul', [
            'menuActive'                => 'eproc',
            'date'              => date('Ymd'),
            'ctrlSsPeriode'     => $this->ctrlSsPeriode(),
            'listeModele'       => $listeModele,
            'param'             => $param,
        ]);
    }

    /**
     * @return Response
     */
    public function ajaxCreateRegulAction()
    {
        $confirm = $this->request->getAttribute('confirm');
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        $validator = $this->createValidator();

        $validator->zoom('Fourniss', $post['CODE_FOU'], $trad->t('fournisseur'), $this->pdo);

        if ($this->ctrlSsPeriode()) {
            $validator->isDateOuverte($trad->t('Date période'), $post['DATE_PERIODE'], $_SESSION["Session_SocUsr"], 'CDE', false);
        }

        if ($validator->isValid()) {
            $codfrs = $post['CODE_FOU'];
            $datePeriode = $post['DATE_PERIODE'];

            $nombreLigne = (new PanierLigne($this->pdo))->getNbLignePanier(0, $_SESSION['id_user']);

            if ($nombreLigne && !$confirm) {
                return new Response(200, [], $this->renderer->render('@Panier/General/confirmationLoad', [
                    'path' => $this->router->generateUri('Panier.CommandeRegul.ajaxCreateRegul', ['confirm' => 1]),
                    'message' => $trad->t('Le panier en cours n\'est pas vide et son contenu sera perdu, voulez-vous poursuivre ?'),
                ]));
            }

            
            $_SESSION['sys_panier'] = 'SYS';
            $_SESSION['id_panier'] = 0;

            $idModele = $post['MODELE']??'';
            (new PanierService($this->pdo))->delete('0', $trad, false);

            if ($idModele) {
                $paramInit = Sql::getParamUser($this->pdo, $_SESSION["Session_Login"], 'SESSION', 'INIT_IMPUT');

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

                $initImput = ($paramInit == 'INITIALISER');
                $societeIdentique = ($infoPanierModele['CODE_STE'] == $_SESSION["Session_SocUsr"]);

                $transferePanier = new TransferePanierService($this->pdo, $idModele, $_SESSION['id_user']);
                $transferePanier->importPanierModele($this->pdoOxaFT, $initImput, $societeIdentique, 0);
            }

            $champ_specTmp = "REGUL|codfrs=".$codfrs.($datePeriode?"|dateperiode=".$datePeriode : '');
            
            (new OxaUserPanier($this->pdo))->update([
                'CHIF_EXEC' => 'E',
                'CHIF_EXEC_LOCK' => '1',
                'CHPSPECCLT' => $champ_specTmp,
                'lib_panier' => $trad->t('REGUL').' - '.$trad->t('FRS:').' '.$codfrs,
                'IS_INITIALIZED' => '1',
            ], [
                'id_user' => $_SESSION['id_user'],
                'id_panier' => 0
            ]);

            $infoFrs = (new Fourniss($this->pdo))->find($codfrs, ['CODE', 'RS']);
            if ($infoFrs) {
                // Comme l'on peut avoir dans ce panier des lignes de ce fournisseur et des lignes sans fournisseur
                // Il faut donc que toutes les lignes sans code fournisseur soit update a la valeur du code fournisseur
                (new OxaUserPanierLigne($this->pdo))->update([
                    'COD_FOURN' => $infoFrs['CODE'],
                    'RS_FOURN' => $infoFrs['RS'],
                    'DATELIVR' => date('Ymd')
                ], [
                    'id_user' => $_SESSION['id_user'],
                    'id_panier' => 0
                ]);
            }
            
            $backPath = $this->router->generateUri('RechercheArticles.RechercheArticles.recherche');
            return new Response(443, [], (string) json_encode(['path' => $backPath, 'post' => []]));
        } else {
            return new Response(200, [], $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'desactiveRow' => true,
            ]));
        }
    }
}
