<?php
namespace Modules\GlobalApplication\Controller;

use Skeleton\Controller\Controller;
use GuzzleHttp\Psr7\Response;
use Helpers\Outil\Roles;
use Helpers\Outil\Sql;
use Helpers\Trad\Trad;
use Helpers\Validator\Validator;
use Modules\GlobalApplication\Repository\ContactsLivraison;

class ContactsLivraisonController extends Controller
{

    
    
    public function ajaxListeContactAction() : string
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        $titre_creation_Onglet = $trad->t('Création contact');

        $filtre = [];
        if (($post['module']??'') == 'CDE') {
            $filtre = [
                'filter_egal_COD_CTR' => $post['CODE'],
                //'filter_egal_CTC_RCA' => 'T',
            ];
        } else {
            $filtre = [
                'filter_egal_COD_CTR' => $post['CODE'],
            ];
        }
        $contact = new \Entity\Model\CtcCtr($this->pdo);
        $listeContact = $contact->fetchAll([], $filtre);

        $adresse = $adresse = $this->router->generateUri('GlobalApplication.ContactsLivraison.ajaxAjoutLigneContact');
        
        return $this->renderer->render('@GlobalApplication/ModifDaCde/ContactsLivraison/contacts', [
            'pathAjoutCtc'          => $adresse,
            'listeContactLiv'       => $listeContact,
            'titre_creation_Onglet' => $titre_creation_Onglet,
            'dynamique'             => true,

            'droit'                 => [
                'HA_CCTR_CM' => Roles::droitsUtilisateur($this->pdo, 'HA_CCTR_CM')
            ],
            
            'CODE'                  => $post['CODE'],
            'idClose'               => $post['idClose'],
            'divCode'               => $post['divCode'],
            'iDivAdd'               => $post['iDivAdd'],
            'iDivReset'             => $post['iDivReset'],
            'idTrigger'             => $post['idTrigger'],
            'idTriggerCreation'     => $post['idTriggerCreation'],
            'module'                => $post['module'] ?? '',
        ]);
    }
    
    public function ajaxAjoutLigneContactAction() : string
    {
        $post = $this->request->getParsedBody();
            
        $CTC_IND = $post['MODIF_CONTACT'];
        $mode = $CTC_IND != '' ? 'modification' : 'creation';
        
        if ($CTC_IND != '') {
            $CtcCtr = new \Entity\Model\CtcCtr($this->pdo);
            $CtcCtr = $CtcCtr->find(['COD_CTR' => $post['CODE'], 'CTC_IND' => $CTC_IND]);
        } else {
            $ContactsLivraison = new ContactsLivraison($this->pdo);
            $CtcCtr['CTC_IND'] = (int)$ContactsLivraison->lastContact($post['CODE'])['MAX_CTR_IND'] + 1;
        }

        $Centre = new \Entity\Model\Centre($this->pdo);
        $Centre = $Centre->find($post['CODE']);
        
        $param['CTC_REN_LOCK'] = Sql::boolSql($Centre['TRS_INTER']);
        $param['CTC_DARDA_LOCK'] = $param['CTC_ROP_LOCK'] = Sql::boolSql($Centre['LIVRAISON']);
        
        return $this->renderer->render('@GlobalApplication/ModifDaCde/ContactsLivraison/nouveauContact', [
            'pathEnregContactLiv'   => $this->router->generateUri('GlobalApplication.ContactsLivraison.validationContact', ['modeContactLiv' => $mode]),
            'detailContact'         => $CtcCtr,
            'modeContactLiv'        => $mode,
            'dynamique'             => true,
            'CODE'                  => $post['CODE'],
            'idClose'               => $post['idClose'],
            'param'                 => $param,
        ]);
    }

    public function validationContactAction()
    {
        $post       = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        
        $modeContactLiv = $this->request->getAttribute('modeContactLiv');
        
        $CTC_IND = $post['CTC_IND_CONT_LIV'];

        $CtcCtr = new \Entity\Model\CtcCtr($this->pdo);
        $validator = $this->createValidator();
        $validator->isStringAvecEspace($trad->t('Nom'), $post['CTC_NOM_CONT_LIV'], 0, 25);
        $validator->isStringAvecEspace($trad->t('Fonction'), $post['CTC_NOM_CONT_LIV'], 0, 40);
        $validator->isStringAvecEspace($trad->t('Téléphone'), $post['CTC_TEL_CONT_LIV'], 0, 16);
        $validator->isStringAvecEspace($trad->t('Fax'), $post['CTC_FAX_CONT_LIV'], 0, 16);
        $validator->isStringAvecEspace($trad->t('Portable'), $post['CTC_GSM_CONT_LIV'], 0, 16);
        $validator->isStringAvecEspace($trad->t('Email'), $post['CTC_MAIL_CONT_LIV'], 0, 100);
        $validator->isCheck($post['CTC_REN_CONT_LIV']);
        $validator->isCheck($post['CTC_RCA_CONT_LIV']);
        $validator->isCheck($post['CTC_ROP_CONT_LIV']);
        $validator->isCheck($post['CTC_DARDA_CONT_LIV']);
        $validator->isStringAvecEspace($trad->t('Maquette Etat Navette'), $post['CTC_CMQ_CONT_LIV'], 0, 10);
        $validator->isCheck($post['PERETNV_CONT_LIV0']);
        $validator->isCheck($post['PERETNV_CONT_LIV1']);
        $validator->isCheck($post['PERETNV_CONT_LIV2']);
        $validator->isCheck($post['PERETNV_CONT_LIV3']);
        $validator->isCheck($post['PERETNV_CONT_LIV4']);
        $validator->isCheck($post['PERETNV_CONT_LIV5']);
        $validator->isCheck($post['PERETNV_CONT_LIV6']);
        
        if ($validator->isValid()) {
            $PERETNV = '';
            if ($post['CTC_REN_CONT_LIV']) {
                $matches  = str_replace("PERETNV_CONT_LIV", "", preg_grep('/^PERETNV_CONT_LIV/', array_keys($post)));
                foreach ($matches as $id) {
                    if ($post['PERETNV_CONT_LIV'.$id]) {
                        $jour = 'O';
                    } else {
                        $jour = 'N';
                    }
                    $PERETNV .= $jour;
                }
            }
            
            $insert['VALUES'] = [
                'COD_CTR' => $post['CTR_LIV']??$post['LIV_CTR'],
                'CTC_IND' => $CTC_IND,
                'CTC_NOM' => $post['CTC_NOM_CONT_LIV'],
                'CTC_FCT' => $post['CTC_FCT_CONT_LIV'],
                'CTC_TEL' => $post['CTC_TEL_CONT_LIV'],
                'CTC_FAX' => $post['CTC_FAX_CONT_LIV'],
                'CTC_GSM' => $post['CTC_GSM_CONT_LIV'],
                'CTC_MAIL' => $post['CTC_MAIL_CONT_LIV'],
                'numerique_CTC_REN' => sql::setBoolSql($post['CTC_REN_CONT_LIV']),
                'CTC_CMQ' => $post['CTC_CMQ_CONT_LIV'],
                'numerique_CTC_RCA' => sql::setBoolSql($post['CTC_RCA_CONT_LIV']),
                'numerique_CTC_ROP' => sql::setBoolSql($post['CTC_ROP_CONT_LIV']),
                'PERETNV' => $PERETNV,
                'numerique_CTC_DARDA' => sql::setBoolSql($post['CTC_DARDA_CONT_LIV']),
            ];
            if ($modeContactLiv == 'creation') {
                $retourSql = $CtcCtr->insert($insert['VALUES']);
            } else {
                $update['VALUES'] = [
                    'CTC_NOM' => $post['CTC_NOM_CONT_LIV'],
                    'CTC_FCT' => $post['CTC_FCT_CONT_LIV'],
                    'CTC_TEL' => $post['CTC_TEL_CONT_LIV'],
                    'CTC_FAX' => $post['CTC_FAX_CONT_LIV'],
                    'CTC_GSM' => $post['CTC_GSM_CONT_LIV'],
                    'CTC_MAIL' => $post['CTC_MAIL_CONT_LIV'],
                    'PERETNV' => $PERETNV,
                    'numerique_CTC_REN' => sql::setBoolSql($post['CTC_REN_CONT_LIV']),
                    'numerique_CTC_RCA' => sql::setBoolSql($post['CTC_RCA_CONT_LIV']),
                    'numerique_CTC_ROP' => sql::setBoolSql($post['CTC_ROP_CONT_LIV']),
                    'numerique_CTC_DARDA' => sql::setBoolSql($post['CTC_DARDA_CONT_LIV']),
                ];
                $update['WHERE'] = ['COD_CTR' => $post['CTR_LIV']??$post['LIV_CTR'], 'CTC_IND'=> $CTC_IND];
                $retourSql = $CtcCtr->update($update['VALUES'], $update['WHERE']);
            }
            if (!$retourSql) {
                return new Response(443, [
    
                ], $trad->t("Erreur lors de l'enregistrement"));
            }
        } else {
            return new Response(443, [
            
            ], $validator->getError());
        }
        
        return $this->renderer->render('@GlobalApplication/ModifDaCde/ContactsLivraison/detailContact', [
            'droit'     => [
                'HA_CCTR_CM' => Roles::droitsUtilisateur($this->pdo, 'HA_CCTR_CM')
            ],
            'ligne'     => $insert['VALUES'],
        ]);
    }

    public function suppressionContactAction()
    {
        $post       = $this->request->getParsedBody();
        $typeModule = $post['TYPEMODULE'] ?? '';
        
        if ($typeModule == 'DA') {
            $codeCentre = $post['CTR_LIV'];
        } else {
            $codeCentre = $post['CODE'];
        }
                
        
        $CtcCtr = new \Entity\Model\CtcCtr($this->pdo);
        $retourSql = $CtcCtr->delete(['COD_CTR' => $codeCentre, 'CTC_IND'=> $post['MODIF_CONTACT_LIV']]);
        
        if (!$retourSql) {
            $trad = $this->getTranslationService();
            return new Response(443, [

            ], $trad->t("Erreur lors de la suppression"));
        }
        
        return '';
    }
}
