<?php
namespace Modules\GlobalApplication\Controller;

use Entity\Model\Contfour;
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\ContactsFournisseur;
use Modules\Ajax\Repository\Listes;
use Modules\RechercheArticles\Repository\Recherche;

class ContactsFournisseurController extends Controller
{

    
    
    public function ajaxListeContactAction() : string
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        $titre_creation_Onglet = $trad->t('Creation contact');
        
        if (isset($post['TYPE_FG']) && $post['TYPE_FG'] == 'G') {
            $liste = new Listes($this->pdo);
            $listeContact = $liste->contactsGroupement(['CODE' => $post['CODE']]);
        } else {
            $liste = new Listes($this->pdo);
            $listeContact = $liste->contactsFournisseur(['CODE_FOU' => $post['CODE']]);
        }
        

        return $this->renderer->render('@GlobalApplication/ModifDaCde/ContactsFournisseur/contacts', [
            //'pathAjoutCtr'          => $adresse,
            'listeContactFou'       => $listeContact,
            'titre_creation_Onglet' => $titre_creation_Onglet,
            'dynamique'             => true,
            
            'CODE'                  => $post['CODE'],
            'idClose'               => $post['idClose'],
            'divCode'               => $post['divCode'],
            'iDivAdd'               => $post['iDivAdd'],
            'iDivReset'             => $post['iDivReset'],
            'idTrigger'             => $post['idTrigger'],
            'idTriggerCreation'     => $post['idTriggerCreation'],
        ]);
    }
    
    public function ajaxAjoutLigneContactAction() : string
    {
        $post = $this->request->getParsedBody();
        $contexte    = $this->request->getAttribute('contexte');
        $IND_FOU = $post['MODIF_CONTACT_FOU']??'';
        $mode = $IND_FOU != '' ? 'modification' : 'creation';
        
        if ($IND_FOU != '') {
            $Contfour = new \Entity\Model\Contfour($this->pdo);
            $Contfour = $Contfour->find(['CODE_FOU' => $post['FOU'], 'IND_FOU' => $IND_FOU]);
        } else {
            $ContactsFournisseur = new ContactsFournisseur($this->pdo);
            $Contfour['IND_FOU'] = (int)$ContactsFournisseur->lastContact($post['FOU'])['MAX_IND_FOU'] + 1;
        }
        
        return $this->renderer->render('@GlobalApplication/ModifDaCde/ContactsFournisseur/nouveauContact', [
            'pathEnregContactFou' => $this->router->generateUri('GlobalApplication.ContactsFournisseur.validationContact', ['contexte' => $contexte, 'codeFou'=> $post['FOU'], 'modeContactFou' => $mode]),
            'detailContact' => $Contfour,
            'modeContactLiv' => $mode,
            'dynamique' => true,
            'CODE'                  => $post['CODE'],
            'idClose'               => $post['idClose'],
            'indFou'                => $IND_FOU,
        ]);
    }

    public function validationContactAction()
    {
        $post       = $this->request->getParsedBody();
        $contexte    = $this->request->getAttribute('contexte');
        $codeFou    = $this->request->getAttribute('codeFou');
        $modeContactFou = $this->request->getAttribute('modeContactFou');
        $IND_FOU = $post['IND_FOU_CONT_FOU'];
        $trad = $this->getTranslationService();

        if (empty($post['COD_ADR_CONT_FOU'])) {
            $post['COD_ADR_CONT_FOU'] = '';
        }
        
        $validator = $this->createValidator();
        $validator->isStringAvecEspace($trad->t('Nom'), $post['NOM_CONT_FOU'], 1, 45);
        $validator->isStringAvecEspace($trad->t('Fonction'), $post['FONCTION_CONT_FOU'], 0, 40);
        $validator->isStringAvecEspace($trad->t('Téléphone'), $post['TEL_CONT_FOU'], 0, 16);
        $validator->isStringAvecEspace($trad->t('Fax'), $post['FAX_CONT_FOU'], 0, 16);
        $validator->isStringAvecEspace($trad->t('Portable'), $post['TELPORT_CONT_FOU'], 0, 16);
        $validator->isStringAvecEspace($trad->t('Email'), $post['EMAIL_CONT_FOU'], 1, 100);
        $validator->isCheck($post['VIBOXAP_CONT_FOU']);
        if ($post['COD_ADR_CONT_FOU'] != '' && $post['COD_ADR_CONT_FOU'] != 'REG') {
            $validator->zoom('Adrfourn', $post['COD_ADR_CONT_FOU'], $trad->t('Code adresse'), $this->pdo, true);
        }
        
        $contactFrs = new Contfour($this->pdo);

        if ($validator->isValid()) {
            if ($modeContactFou == 'creation') {
                $contactFrs->insert([
                    'CODE_FOU'  => $codeFou,
                    'IND_FOU'   => $IND_FOU,
                    'NOM'       => $post['NOM_CONT_FOU'],
                    'FONCTION'  => $post['FONCTION_CONT_FOU'],
                    'TEL'       => $post['TEL_CONT_FOU'],
                    'FAX'       => $post['FAX_CONT_FOU'],
                    'EMAIL'     => $post['EMAIL_CONT_FOU'],
                    'COD_ADR'   => '',
                    'TELPORT'   => $post['TELPORT_CONT_FOU'],
                    'CREE_PAR'  => $_SESSION["Session_Login"],
                    'numerique_VIBOXAP'   => Sql::setBoolSql($post['VIBOXAP_CONT_FOU']),
                ]);
            } else {
                $oldctc = $contactFrs->find(['CODE_FOU'  => $codeFou,'IND_FOU'   => $IND_FOU]);

                $contactFrs->update([
                    'NOM'       => $post['NOM_CONT_FOU'],
                    'FONCTION'  => $post['FONCTION_CONT_FOU'],
                    'TEL'       => $post['TEL_CONT_FOU'],
                    'FAX'       => $post['FAX_CONT_FOU'],
                    'EMAIL'     => $post['EMAIL_CONT_FOU'],
                    'TELPORT'   => $post['TELPORT_CONT_FOU'],
                    'COD_ADR'   => $oldctc['COD_ADR'],
                    'numerique_VIBOXAP'   => Sql::setBoolSql($post['VIBOXAP_CONT_FOU']),
                ], [
                    'CODE_FOU'  => $codeFou,
                    'IND_FOU'   => $IND_FOU,
                ]);
            }
        } else {
            return new Response(443, [
            
            ], $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'titrePopup'  => $trad->t('Erreur'),
            ]));
        }

        $ligne = [
            'NOM'       => $post['NOM_CONT_FOU'],
            'FONCTION'  => $post['FONCTION_CONT_FOU'],
            'TEL'       => $post['TEL_CONT_FOU'],
            'FAX'       => $post['FAX_CONT_FOU'],
            'EMAIL'     => $post['EMAIL_CONT_FOU'],
            'COD_ADR'   => $post['COD_ADR_CONT_FOU'],
            'TELPORT'   => $post['TELPORT_CONT_FOU'],
            'VIBOXAP'   => Sql::setBoolSql($post['VIBOXAP_CONT_FOU']),
        ];
        
        if ($contexte=='panier') {
            $recherche          = new Recherche($this->pdo);
            $listeChampsCtc     = $recherche->getParamContact();

            return $this->renderer->render('@rechercheArticles/Fournisseur/_ligneContact', [
                'listeChampsCtc'    => $listeChampsCtc,
                'codRegroup' => true,
                'ligne'     => $ligne,
                'infoFrs'   => ['CODE' => $codeFou],
                'droit'     => ['HA_FRS_CON' => Roles::droitsUtilisateur($this->pdo, 'HA_FRS_CON')]
            ]);
        } else {
            return $this->renderer->render('@GlobalApplication/ModifDaCde/ContactsFournisseur/detailContact', [
                'ligne'     => $ligne,
            ]);
        }
    }

    /**
     * @return string|Response
     */
    public function suppressionContactAction()
    {
        $post       = $this->request->getParsedBody();
        $codeFou    = $this->request->getAttribute('codeFou');
        $IND_FOU    = $this->request->getAttribute('indFou');

        $contactFrs = new Contfour($this->pdo);
        $retourSql = $contactFrs->delete([
            'CODE_FOU'  => $codeFou,
            'IND_FOU'   => $IND_FOU,
        ]);

        if (!$retourSql) {
            $trad = $this->getTranslationService();
            return new Response(443, [

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