<?php
namespace Modules\GlobalApplication\Controller;

use Skeleton\Controller\Controller;
use GuzzleHttp\Psr7\Response;
use Helpers\Trad\Trad;
use Helpers\Validator\Validator;
use Modules\Ajax\Repository\Listes;
use Entity\Model\AdrFourn;
use Helpers\Outil\Outils;
use Helpers\Outil\Roles;
use Helpers\Outil\Sql;

class AdressesController extends Controller
{

 
    
    public function ajaxListeAdressesAction() : string
    {
        $post = $this->request->getParsedBody();
        $TYPE_ADRESSE = $this->request->getAttribute('TYPE_ADRESSE');
        $trad = $this->getTranslationService();
        
        $adresse = $this->router->generateUri('GlobalApplication.Adresses.ajaxAjoutLigneAdresses', [ 'TYPE_ADRESSE' => $TYPE_ADRESSE]);
        $titre_creation_Onglet = $trad->t('Creation adresse');
        $liste = new Listes($this->pdo);
        
        
        if ($TYPE_ADRESSE=='FOU') {
            $listeAdresse = $liste->adresseFournisseur($post+['filter_egal_CODE' => $post['CODE']], false, false, []);
            $adresse = '';
        } elseif ($TYPE_ADRESSE=='CENTRE') {
            $listeAdresse = $liste->adresseCentre($post+['filter_egal_CODE_CTR' => $post['CODE']]);
        }

        return $this->renderer->render('@GlobalApplication/ModifDaCde/Adresses/adresses', [
            'pathAjoutAdr'          => $adresse,
            'listeAdresses'         => $listeAdresse,
            'titre_creation_Onglet' => $titre_creation_Onglet,
            'dynamique'             => true,
            'TYPE_ADRESSE'          => $TYPE_ADRESSE,
            'post'                  => $post,

            'CODE'                  => $post['CODE'],
            'idClose'               => $post['idClose'],
            'divCode'               => $post['divCode'],
            'iDivAdd'               => $post['iDivAdd'],
            'iDivReset'             => $post['iDivReset'],
            'idTrigger'             => $post['idTrigger'],
            'idTriggerCreation'     => $post['idTriggerCreation'],
            'fromConsultation'      => $post['fromConsultation'] ? true : false,
            'pathBack'              => $post['pathBack'] ?: ''
        ]);
    }
    
    public function ajaxAjoutLigneAdressesAction() : string
    {
        $post           = $this->request->getParsedBody();
        $TYPE_ADRESSE   = $this->request->getAttribute('TYPE_ADRESSE');
        $contexte   = $this->request->getAttribute('contexte');
        
        $COD_ADR        = $post['MODIF_COD_ADR']??'';
        
        $modeAdresse = $COD_ADR ? 'modification' : 'creation';
        
        if ($COD_ADR != '') {
            if ($TYPE_ADRESSE == 'FOU') {
                $listeAjax = new Listes($this->pdo);
                $adresse = $listeAjax->adresseFournisseur(['filter_egal_CODE' => $post['CODE'],'filter_egal_COD_ADR' => $COD_ADR])[0]??[];
                
                $param = ['TELEX_ACTIF' => true];
            } else {
                $AdrCtr = new \Entity\Model\AdrCtr($this->pdo);
                $adresse = $AdrCtr->find(['COD_CTR' => $post['CODE'], 'COD_ADR' => $COD_ADR]);
            }
        } else {
            if ($TYPE_ADRESSE == 'FOU') {
                $param = ['TELEX_ACTIF' => true];
            }
        }
        
        return $this->renderer->render('@GlobalApplication/ModifDaCde/Adresses/nouvelleAdresse', [
            'tabPays'               => (new \Entity\Model\Pays($this->pdo))->listChoice(),
            'modeAdresse'           => $COD_ADR ? 'modification' : 'creation',
            'TYPE_ADRESSE'          => $TYPE_ADRESSE,
            'param'                 => $param ?? [],
            'dynamique'             => true,
            'detailAdresse'         => $adresse??'',
            'pathEnregAdr'          => $this->router->generateUri('GlobalApplication.Adresses.validationAdresses', ['contexte' => $contexte, 'TYPE_ADRESSE' => $TYPE_ADRESSE, 'modeAdresse' => $modeAdresse]),
            
            'CODE'                  => $post['CODE'],
            'idClose'               => $post['idClose'],
        ]);
    }

    public function validationAdressesAction()
    {
        $post           = $this->request->getParsedBody();
        $contexte    = $this->request->getAttribute('contexte');

        $trad = $this->getTranslationService();
        
        $modeAdresse    = $this->request->getAttribute('modeAdresse');
        $TYPE_ADRESSE   = $this->request->getAttribute('TYPE_ADRESSE');
        
        $typeModule     = $post['TYPEMODULE'] ?? '';
        
        $tabPays = (new \Entity\Model\Pays($this->pdo))->listChoice();
        $validator = $this->createValidator();

        $post['COD_ADR'] = $post['NEW_COD_ADR'];
        $COD_ADR = $post['COD_ADR'];

        if ($modeAdresse == 'creation') {
            if ($validator->isStringSansEspace($trad->t('Code'), $post['COD_ADR'], 1, 3)) {
                switch ($TYPE_ADRESSE) {
                    case 'LIV':
                    case 'CENTRE':
                        $AdrCtr = new \Entity\Model\AdrCtr($this->pdo);
                        $params = ['COD_CTR' => $post['CTR_LIV'], 'COD_ADR'=> $COD_ADR];
                        $validator->isTrue(is_array($AdrCtr->find($params)), '<br />'.$trad->t('Le code saisi existe déjà.'));
                        break;
                }
            }
        }
        $validator->isStringAvecEspace($trad->t('Libellé'), $post['LIBELLE'], 0, 45);
        $validator->isStringAvecEspace($trad->t('Adresse'), $post['ADRESSE'], 0, 90);
        $validator->contentInArray($trad->t('Pays'), $post['CODPAYS'], $tabPays);
        $validator->isCodePostal($trad->t('Code postal'), $post['CPOSTAL'], $post['CODPAYS']);
        $validator->isStringAvecEspace($trad->t('Ville'), $post['VILLE1'], 0, 35);
        $validator->isStringAvecEspace($trad->t('Téléphone'), $post['TELEPHONE'], 0, 16);
        $validator->isStringAvecEspace($trad->t('Email'), $post['EMAIL'], 0, 100);
        $validator->isStringAvecEspace($trad->t('Fax'), $post['FAX'], 0, 16);
        if (isset($post['TELEX'])) {
            $validator->isStringAvecEspace($trad->t('Telex'), $post['TELEX'], 0, 16);
        }

        if ($validator->isValid()) {
            if ($typeModule == 'DA') {
                $code = $post['CTR_LIV'];
            } else {
                $code = $post['CODE_DEST'];
            }
            
            switch ($TYPE_ADRESSE) {
                case 'FOU':
                    $adresseFou = new AdrFourn($this->pdo);
                    $post['NOMPAYS'] = Outils::convertLibelleGlobal($this->pdo, 'Country', '', $post['CODPAYS']);
                    if ($modeAdresse == 'creation') {
                        $adresseFou->insert([
                            'COD_FOU' => $code,
                            'COD_ADR' => $COD_ADR,
                            'LIBELLE' => $post['LIBELLE'],
                            'ADRESSE' => $post['ADRESSE'],
                            'VILLE' => $post['CPOSTAL'].' '.$post['VILLE1'],
                            'CODPAYS' => $post['CODPAYS'],
                            'TELEPHONE' => $post['TELEPHONE'],
                            'FAX' => $post['FAX'],
                            'EMAIL' => $post['EMAIL'],
                            'CPOSTAL' => $post['CPOSTAL'],
                            'VILLE1' => $post['VILLE1'],
                            'TELEX' => $post['TELEX']??'',
                            'numerique_ADR_COMMANDE' => Sql::setBoolSql($post['ADR_COMMANDE']),
                        ]);
                    } else {
                        $adresseFou->update([
                            'LIBELLE' => $post['LIBELLE'],
                            'ADRESSE' => $post['ADRESSE'],
                            'VILLE' => $post['CPOSTAL'].' '.$post['VILLE1'],
                            'CODPAYS' => $post['CODPAYS'],
                            'TELEPHONE' => $post['TELEPHONE'],
                            'FAX' => $post['FAX'],
                            'EMAIL' => $post['EMAIL'],
                            'CPOSTAL' => $post['CPOSTAL'],
                            'VILLE1' => $post['VILLE1'],
                            'TELEX' => $post['TELEX']??'',
                            'numerique_ADR_COMMANDE' => Sql::setBoolSql($post['ADR_COMMANDE']),
                        ], [
                            'COD_FOU' => $code,
                            'COD_ADR' => $COD_ADR,
                        ]);
                    }
                    
                    break;

                case 'LIV':
                case 'CENTRE':
                    $AdrCtr = new \Entity\Model\AdrCtr($this->pdo);
                    if ($modeAdresse == 'creation') {
                        $insert['VALUES'] = [
                            'COD_CTR' => $code,
                            'COD_ADR' => $COD_ADR,
                            'LIBELLE' => $post['LIBELLE'],
                            'ADRESSE' => $post['ADRESSE'],
                            'VILLE' => $post['CPOSTAL'].' '.$post['VILLE1'],
                            'CODPAYS' => $post['CODPAYS'],
                            'TELEPHONE' => $post['TELEPHONE'],
                            'FAX' => $post['FAX'],
                            'EMAIL' => $post['EMAIL'],
                            'CPOSTAL' => $post['CPOSTAL'],
                            'VILLE1' => $post['VILLE1'],
                        ];
                        $retourSql = $AdrCtr->insert($insert['VALUES']);
                    } else {
                        $update['VALUES'] = [
                            'LIBELLE' => $post['LIBELLE'],
                            'ADRESSE' => $post['ADRESSE'],
                            'VILLE' => $post['CPOSTAL'].' '.$post['VILLE1'],
                            'CODPAYS' => $post['CODPAYS'],
                            'TELEPHONE' => $post['TELEPHONE'],
                            'FAX' => $post['FAX'],
                            'EMAIL' => $post['EMAIL'],
                            'CPOSTAL' => $post['CPOSTAL'],
                            'VILLE1' => $post['VILLE1'],
                        ];

                        $update['WHERE'] = ['COD_CTR' => $code, 'COD_ADR'=> $COD_ADR];
                        $retourSql = $AdrCtr->update($update['VALUES'], $update['WHERE']);
                    }
                    if (!$retourSql) {
                        return new Response(443, [
            
                        ], $trad->t('Erreur lors de l\'enregistrement'));
                    }
                    

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

        if ($contexte=='panier') {
            return $this->renderer->render('@rechercheArticles/Fournisseur/_ligneAdresse', [
                'codRegroup' => true,
                'ligne'     => $post,
                'infoFrs'   => ['CODE' => $code],
                'droit'     => ['HA_FRS_ADR' => Roles::droitsUtilisateur($this->pdo, 'HA_FRS_ADR')]
            ]);
        } else {
            return $this->renderer->render('@GlobalApplication/ModifDaCde/Adresses/detailAdresse', [
                'ligne'     => $post,
                'divCode'   => $post['divCode'],
                'idClose'   => $post['idClose'],
                'idTrigger' => $post['idTrigger'],
                'iDivReset' => $post['iDivReset'],
            ]);
        }
    }

    public function suppressionAdressesAction()
    {
        $post           = $this->request->getParsedBody();
        $TYPE_ADRESSE   = $this->request->getAttribute('TYPE_ADRESSE');
        $codeFou    = $this->request->getAttribute('codeFou');
        $codAdr    = $this->request->getAttribute('codAdr');

        $typeModule     = $post['TYPEMODULE'] ?? '';
        $trad = $this->getTranslationService();

        switch ($TYPE_ADRESSE) {
            case 'FOU':
                $adrFou = new AdrFourn($this->pdo);
                $adrFou->delete(['COD_FOU' => $codeFou, 'COD_ADR' => $codAdr]);
                
                break;
            case 'LIV':
            case 'CENTRE':
                if ($typeModule == 'DA') {
                    $codeDelete = $post['CTR_LIV'];
                } else {
                    $codeDelete = $post['CODE'];
                }
                
                $AdrCtr = new \Entity\Model\AdrCtr($this->pdo);
                $retourSql = $AdrCtr->delete(['COD_CTR' => $codeDelete, 'COD_ADR'=> $post['MODIF_COD_ADR']]);
                
                if (!$retourSql) {
                    return new Response(443, [
                    ], $trad->t('Erreur lors de la suppression'));
                }
               
                break;
        }

        
        
        // if($typeModule == 'DA'){
            
        //     $Pays = new \Entity\Model\Pays($this->pdo);
        //     $listePays = $Pays->fetchAll();
        //     for($i=0; $i<count($listePays); $i++)
        //     {
        //         $tabPays[str_replace(' ','',$listePays[$i]['CODE_PAYS'])]=str_replace(' ', '',$listePays[$i]['LIBELLE']);
        //     }
            
        //     $listeAdrFourniss = $liste->adresseFournisseur(['filter_egal_CODE' => $post['FOU']]);
        //     $listeAdrLivraison = $liste->adresseCentre(['filter_egal_CODE_CTR' => $post['CTR_LIV']]);
            
        //     return $this->renderer->render('@DemandeAchat/Creation/DetailEntete', [
        //         'tabPays' => $tabPays,
        //         'TYPE' => $TYPE_ADRESSE,
        //         'listeAdrFourniss' => $listeAdrFourniss,
        //         'listeAdrLivraison' => $listeAdrLivraison,
                
        //         // params concernant la DA
        //         'param' => [],
        //         'numDA' => $post['numDA'],
        //         'mode' => $post['mode'],
        //         'MODULE' => $post['MODULE'],
        //     ]);
        // }
        // else
        // {
            return '';
        // }
    }
}
