<?php
namespace Modules\RechercheArticles\Controller;

use Entity\Model\Contfour;
use Entity\Model\Fourniss;
use Entity\Model\OxaUserPanierFour;
use Entity\Model\OxaUserPanierFourContact;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\ChampsSupplementaire\ChampSupp;
use Helpers\Outil\Roles;
use Helpers\Outil\Sql;
use Helpers\Parametres\Constante;
use Helpers\Securite\Securite;
use Modules\Ajax\Repository\Listes;
use Modules\GlobalApplication\Repository\DocumentsRattaches;
use Modules\Panier\Repository\PanierEntete;
use Modules\Panier\Repository\PanierFrs;
use Modules\RechercheArticles\Repository\Recherche;
use Skeleton\Controller\Controller;

class FournisseurController extends Controller
{
    public function init():void
    {
        Securite::setHeaderContentSecurityPolicyWithoutSelf();
    }
    
    public function ficheAction() : string
    {
        $post = $this->request->getParsedBody();
        $idFourn = $this->request->getAttribute('idFourn');
        $codRegroup = $this->request->getAttribute('codRegroup');
        $popupFrs = $post['popupFrs']??false;

        $idRegroup = str_replace(Constante::oxaPipe, '|', $codRegroup);

        $trad = $this->getTranslationService();

        $droits = [
            'HA_CDE_ADR'    =>  Roles::droitsUtilisateur($this->pdo, 'HA_CDE_ADR'),
            'HA_FRS_ADR'    => false,
            'HA_FRS_CON'    => false
        ];

        if (!$popupFrs) {
            $droits['HA_FRS_CON'] =  Roles::droitsUtilisateur($this->pdo, 'HA_FRS_CON');
            $droits['HA_FRS_ADR'] =  Roles::droitsUtilisateur($this->pdo, 'HA_FRS_ADR');
        }

        $recherche          = new Recherche($this->pdo);
        $listeChamps        = $recherche->getParamFicheFournisseur();
        $listeChampsCtc     = $recherche->getParamContact();

        $listeAjax          = new Listes($this->pdo);

        $fourniss           = new Fourniss($this->pdo);
        $infoFrs            = $fourniss->find($idFourn);

        if ($codRegroup) {
            //@rechercheArticles/Fournisseur/Fiche.twig
            $template = '@Panier/General/fullTemplate';
            //todo ici pour récuperé les info du fournisseur depuis le panier.

            $oxauserCtc = (new OxaUserPanierFourContact($this->pdo))->find([
                'ID_PANIER' => $_SESSION['id_panier'],
                'ID_USER' => $_SESSION['id_user'],
                'CRITERE_REGROUP' => $idRegroup,
                'CTC_TYPE' => 'fournisseur',
            ]);

            $ctcPrincipal = [
                'NOM'       => $oxauserCtc['CTC_NOM'],
                'FONCTION'  => $oxauserCtc['CTC_FCT'],
                'TEL'       => $oxauserCtc['CTC_TEL'],
                'EMAIL'     => $oxauserCtc['CTC_MAIL'],
                'TELPORT'   => $oxauserCtc['CTC_GSM'],
                'FAX'       => $oxauserCtc['CTC_FAX'],
            ];

            $oxaUserFou = (new OxaUserPanierFour($this->pdo))->find([
                'id_panier' => $_SESSION['id_panier'],
                'id_user' => $_SESSION['id_user'],
                'CRITERE_REGROUP' => $idRegroup,
            ], ['CODE_PAYS', 'CPOSTAL', 'VILLE1', 'ADR']);

            $adressePrincipal = [
                'ADRESSE' => $oxaUserFou['ADR'],
                'CPOSTAL' => $oxaUserFou['CPOSTAL'],
                'VILLE1'  => $oxaUserFou['VILLE1'],
                'CODPAYS' => $oxaUserFou['CODE_PAYS'],
            ];

            $adresse = $listeAjax->adresseFournisseur([
                'filter_egal_CODE' => $idFourn,
                'ADR_COMMANDE' => 0x54,
            ], false, false, [
                'ADR' => $oxaUserFou['ADR'],
                'CPOSTAL' => $oxaUserFou['CPOSTAL'],
                'VILLE1'  => $oxaUserFou['VILLE1'],
                'CODPAYS' => $oxaUserFou['CODE_PAYS'],
            ]);

            $adressePrincipal['COD_ADR'] = $adresse[0]['COD_ADR'];

            Ariane::generate(2, $trad->t('Fournisseur'));
        } else {
            $template = '@rechercheArticles/Fournisseur/fiche';
            
            $adressePrincipal   = $listeAjax->adresseFournisseur(['filter_egal_CODE' => $idFourn,'filter_egal_COD_ADR' => 'ADR_FOU'])[0]??[];
        }
        
        foreach ($listeChamps as $key => &$champs) {
            if (strpos($champs['CODE_CHP'], 'CS|') === 0) {
                $infoCS = explode('|', $champs['CODE_CHP']);

                $infoFrs[$champs['CODE_CHP']] = (new ChampSupp($this->pdo))->getInfoValueCs('ARTICLE', $infoFrs['CODE'], $infoCS[1])['VALEUR']??'';
            }
        }

        $listeCtc           = (new PanierFrs($this->pdo))->getListeCtcByCodAdr($idFourn, $adressePrincipal['COD_ADR']);
        
        if (!$codRegroup) {
            $ctcPrincipal       = $listeCtc[0]??[];
        }

        $panierEntete = (new PanierEntete($this->pdo))->getEntetePanier($_SESSION['id_panier'], $_SESSION['id_user']);
        $centre = $panierEntete['LIV_CTR'];
        $zoneGeoActive = (new Recherche($this->pdo))->zoneGeoActive($centre)['active'];

        if ($droits['HA_FRS_ADR'] || $droits['HA_CDE_ADR']) {
            $listeAdresse = $listeAjax->adresseFournisseur([
                'filter_egal_CODE' => $idFourn,
            ]+($codRegroup? [
                'ADR_COMMANDE' => 0x54,
            ]:[]), ($zoneGeoActive ? $centre:false));
        }

        $docAtt = new DocumentsRattaches($this->pdo);
        $listeDoc = $docAtt->detail($idFourn, ['NO_DA' => 'FOURNISS', 'tri_TYPE_PJ' => 'asc']);

        $listeBDD = $recherche->getBDDFrs($idFourn);

        return $this->renderer->render($template, [
            'template'          => 'frs',

            'idFourn'             => $idFourn,

            'infoFrs'           => $infoFrs,
            'panier'            => $panierEntete,
            'listeChamps'       => $listeChamps,
            'ctcPrincipal'      => $ctcPrincipal,
            'listeChampsCtc'    => $listeChampsCtc,
            'adressePrincipal'  => $adressePrincipal,

            'listeAdresses'     => $listeAdresse??[],
            'listeContactFou'   => $listeCtc,
            'listeDocument'     => $listeDoc,
            'listeBDD'          => $listeBDD,
            'droit'             => $droits,

            'codRegroup'        => str_replace('|', Constante::oxaPipe, $codRegroup),
            'validatorCtc'      => $this->validatorContactFrs(),
            'rand'              => rand(),

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

    /**
     * @return Response
     */
    public function ajaxRefreshListeContactAction(
        PanierFrs $panierFrs,
        Listes $liste,
    ) {
        $post               = $this->request->getParsedBody();
        $idFourn            = $this->request->getAttribute('idFourn');

        $listeCtc           = (new PanierFrs($this->pdo))->getListeCtcByCodAdr($idFourn, $post['COD_ADR']);

        $recherche          = new Recherche($this->pdo);
        $listeChampsCtc     = $recherche->getParamContact();

        //$infoCtc            = (new PanierFrs($this->pdo))->getInfoCtcAdresse($idFourn, $post['COD_ADR']);

        $infoCtc = $panierFrs->getInfoCtcAdresse($idFourn, $post['COD_ADR']);

        if (Sql::paravrac($this->pdo, 'PARAMGEN', 'CHOIX_INIT_FAXMAILFOUR_SUR_CDE') == 'O') {
            $adresse = $liste->adresseFournisseur([
                'filter_egal_CODE'    => $idFourn,
                'filter_egal_COD_ADR' => $post['COD_ADR'],
            ])[0] ?? [];

            $infoCtc['CTC_FAX']  = $adresse['FAX'] ?? '';
            $infoCtc['CTC_MAIL'] = $adresse['EMAIL'] ?? '';
        }


        return new Response(200, [], (string)json_encode([
            'listeCtc' => $this->renderer->render('@rechercheArticles/Fournisseur/_contact', [
                'listeChampsCtc'    => $listeChampsCtc,
                'listeContactFou'   => $listeCtc,
            ]),
            'ctcAdresse'    =>  $infoCtc,
        ]));
    }

    public function popupConfirmationSuppresionAction() : string
    {
        $post       = $this->request->getParsedBody();
        $path       = $post['Path'];
        $message    = $post['Message'];
        $idRemove   = $post['div'];

        return $this->renderer->render('@rechercheArticles/Fournisseur/popupDelete', [
            'message'   => $message,
            'pathURL'   => $path,
            'idRemove'  => $idRemove,
        ]);
    }

    /**
     * @return Response
     */
    public function ajaxValidatorAction()
    {
        $codRegroup = $this->request->getAttribute('codRegroup');
        $post       = $this->request->getParsedBody();
        $validator  = $this->createValidator();

        $idRegroup = str_replace(Constante::oxaPipe, '|', $codRegroup);

        $recherche          = new Recherche($this->pdo);
        $listeChampsCtc     = $recherche->getParamContact();

        $listeValidatorCtc = $this->validatorContactFrs();
        
        $updateCtc = [];
        foreach ($listeChampsCtc as $ctc) {
            $valid = $listeValidatorCtc[$ctc['CODE_CHP']];
            if ($valid['pathValidator'] == $this->router->generateUri('Ajax.validator.adresseMail')) {
                $validator->adresseMail(
                    $ctc['LIB_CHP'],
                    $post[$ctc['CODE_CHP']],
                    $valid['min'],
                    $valid['max'],
                );
            } else {
                $validator->isStringAvecEspace(
                    $ctc['LIB_CHP'],
                    $post[$ctc['CODE_CHP']],
                    $valid['min'],
                    $valid['max'],
                );
            }
            $updateCtc[$valid['BDD']] = $post[$ctc['CODE_CHP']];
        }

        if ($validator->isValid()) {
            $backPath = Ariane::getBackPath();
            $backPost = Ariane::getBackPost();

            (new OxaUserPanierFourContact($this->pdo))->update($updateCtc, [
                'ID_PANIER' => $_SESSION['id_panier'],
                'ID_USER' => $_SESSION['id_user'],
                'CRITERE_REGROUP' => $idRegroup,
                'CTC_TYPE' => 'fournisseur',
            ]);

            (new OxaUserPanierFour($this->pdo))->update([
                'CODE_PAYS' => $post['CODPAYS'],
                'CPOSTAL' => $post['CPOSTAL'],
                'VILLE1' => $post['VILLE1'],
                'ADR' => $post['ADRESSE']
            ], [
                'id_panier' => $_SESSION['id_panier'],
                'id_user' => $_SESSION['id_user'],
                'CRITERE_REGROUP' => $idRegroup,
            ]);

            return new Response(443, [], (string) json_encode(['path' => $backPath, 'post' => $backPost]));
        } else {
            return new Response(200, [], $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'desactiveRow' => true,
            ]));
        }
    }


    /**
     * @return array<mixed>
     */
    private function validatorContactFrs()
    {
        return [
            'NOM' => [
                'pathValidator' => $this->router->generateUri('Ajax.validator.isStringAvecEspace'),
                'paramValidator' => "{'sizeMin' : '0', 'sizeMax' : '25'}",
                'min' => 0,
                'max' => 25,
                'BDD' => 'CTC_NOM',
            ],
            'FONCTION' => [
                'pathValidator' => $this->router->generateUri('Ajax.validator.isStringAvecEspace'),
                'paramValidator' => "{'sizeMin' : '0', 'sizeMax' : '25'}",
                'min' => 0,
                'max' => 25,
                'BDD' => 'CTC_FCT',
            ],
            'TEL' => [
                'pathValidator' => $this->router->generateUri('Ajax.validator.isStringAvecEspace'),
                'paramValidator' => "{'sizeMin' : '0', 'sizeMax' : '16'}",
                'min' => 0,
                'max' => 16,
                'BDD' => 'CTC_TEL',
            ],
            'FAX' => [
                'pathValidator' => $this->router->generateUri('Ajax.validator.isStringAvecEspace'),
                'paramValidator' => "{'sizeMin' : '0', 'sizeMax' : '16'}",
                'min' => 0,
                'max' => 16,
                'BDD' => 'CTC_FAX',
            ],
            'TELPORT' => [
                'pathValidator' => $this->router->generateUri('Ajax.validator.isStringAvecEspace'),
                'paramValidator' => "{'sizeMin' : '0', 'sizeMax' : '16'}",
                'min' => 0,
                'max' => 16,
                'BDD' => 'CTC_GSM',
            ],
            'EMAIL' => [
                'pathValidator' => $this->router->generateUri('Ajax.validator.adresseMail'),
                'paramValidator' => "{'sizeMin' : '0', 'sizeMax' : '100'}",
                'min' => 0,
                'max' => 100,
                'BDD' => 'CTC_MAIL',
            ],
        ];
    }
}
