<?php
namespace Modules\GlobalApplication\Controller;

use Entity\Model\AoContFour;
use Entity\Model\AoFour;
use Entity\Model\Contfour;
use Entity\Model\ContGF;
use Entity\Model\Fourniss;
use Entity\Model\OxalinkUser;
use Modules\Fournisseur\Outil\DroitUtilisateur;
use Modules\Fournisseur\Repository\GestFourniss;
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('Création 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,
            'droit' => [
                'HA_FRS_CON' => Roles::droitsUtilisateur($this->pdo, 'HA_FRS_CON')
            ],

            '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,
        ]);
    }

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

        if (isset($post['TYPE_FG']) && $post['TYPE_FG'] == 'G') {
            $liste        = new Listes($this->pdo);
            $listeContact = $liste->contactsGroupement(['CODE' => $post['CODE']]);
            $prospect     = false;
        } else {
            $liste        = new Listes($this->pdo);
            $listeContact = $liste->contactsFournisseur(['CODE_FOU' => $post['CODE']]);
            $prospect     = Sql::toBool((new Fourniss($this->pdo))->find(['CODE' => $post['CODE']], ['PROSPECT'])['PROSPECT']);
        }
        
        foreach ($listeContact as $key => $contact) {
            if (isset($contact['NOM']) && $contact['NOM'] == '' && isset($contact['EMAIL']) && $contact['EMAIL'] == '') {
                unset($listeContact[$key]);
            }
        }
        
        if (($post['module'] ?? '') == "consultation" && count($listeContact) > 0) {
            $AoFour                    = new AoFour($this->pdo);
            $aoFourContact = $AoFour->find([
                'NO_AO' => $post['idAO'],
                'CODE_FOU' => $post['CODE'],
                'TYPE_FG' => $post['TYPE_FG'] ?? 'F'
            ], ['EMAILCONT']);
            $AoContFour                = new AoContFour($this->pdo);
            $allAoContFourContactEmail = array_map(
                fn($array) => $array['EMAILCONT'],
                $AoContFour->findAll([
                    'NO_AO' => $post['idAO'],
                    'CODE_FOUR' => $post['CODE'],
                    'TYPE_FG' => $post['TYPE_FG'] ?? 'F',
                ], ['EMAILCONT'])
            );
            $allAoContFourContactEmail[] = $aoFourContact['EMAILCONT'];

            $selectedContact = [];
            foreach ($listeContact as $contact) {
                if (in_array($contact['EMAIL'] ?? '', $allAoContFourContactEmail)) {
                    $selectedContact[] = $contact['IND_FOU'];
                }
            }
        }

        return $this->renderer->render('@GlobalApplication/ModifDaCde/ContactsFournisseur/multicontact', [
            'listeContactFou' => $listeContact,
            'titre_creation_Onglet' => $titre_creation_Onglet,
            'dynamique' => true,
            'droit' => [
                'HA_FRS_CON' => Roles::droitsUtilisateur($this->pdo, 'HA_FRS_CON'),
                'HA_PRO_CON' => Roles::droitsUtilisateur($this->pdo, 'HA_PRO_CON')
            ],
            'pathSave' => $post['pathSave'],
            'pathBack' => $post['pathBack'],
            'idAO' => $post['idAO'],
            'CODE' => $post['CODE'],
            'RS' => $post['RS'] ?? '',
            'WF_ATTENT' => $post['WF_ATTENT'] ?? '',
            'typeFG' => $post['TYPE_FG'] ?? 'F',
            'idClose' => $post['idClose'],
            'divCode' => $post['divCode'],
            'iDivAdd' => $post['iDivAdd'],
            'iDivReset' => $post['iDivReset'],
            'idTrigger' => $post['idTrigger'],
            'idTriggerCreation' => $post['idTriggerCreation'],
            'fromConsultation' => $post['fromConsultation'] ? true : false,
            'selectedContact' => $selectedContact ?? [],
            'prospect' => $prospect
        ]);
    }

    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 != '') {
            if (($post['TYPE_FG']??'') != 'F') {
                $post['FOU'] = $post['CODE'];
                $ContGF = new ContGF($this->pdo);
                $Contfour = $ContGF->find(['CODE_GF' => $post['FOU'], 'IND_FOU' => $IND_FOU]);
            } else {
                $Contfour = new Contfour($this->pdo);
                $Contfour = $Contfour->find(['CODE_FOU' => $post['FOU'], 'IND_FOU' => $IND_FOU]);
            }
        } else {
            $ContactsFournisseur = new ContactsFournisseur($this->pdo);
            if (($post['TYPE_FG']??'') != 'F') {
                $Contfour['IND_FOU'] = (int) $ContactsFournisseur->lastContactContGF($post['FOU'])['MAX_IND_FOU'] + 1;
            } else {
                $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, 'typeFG' => $post['TYPE_FG']??'F']),
            'detailContact' => $Contfour,
            'modeContactLiv' => $mode,
            'dynamique' => true,
            'CODE' => $post['CODE'] ?? '',
            'RS' => $post['RS'] ?? '',
            'idClose' => $post['idClose'],
            'fromConsultation' => $post['fromConsultation'],
            'indFou' => $IND_FOU,
            'typeFG' => $post['TYPE_FG'] ?? 'F',
            'contexte' => $contexte
        ]);
    }

    public function validationContactAction()
    {
        $post           = $this->request->getParsedBody();
        $contexte       = $this->request->getAttribute('contexte');
        $codeFou        = $this->request->getAttribute('codeFou');
        $modeContactFou = $this->request->getAttribute('modeContactFou');
        $typeFG         = $this->request->getAttribute('typeFG');
        $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, 25);
        $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']);
        $validator->isCheck($post['CTC_CONSULT_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);
        }

        if ($typeFG=='F') {
            $contactFrs = new Contfour($this->pdo);
        } else {
            $contGF = new ContGF($this->pdo);
        }
        if ($validator->isValid()) {
            if ($modeContactFou == 'creation') {
                if ($typeFG=='F') {
                    // @phpstan-ignore-next-line
                    $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"],
                        'OXALINK_ID' => '',
                        'numerique_VIBOXAP' => Sql::setBoolSql($post['VIBOXAP_CONT_FOU']),
                        'numerique_CTC_CONSULT' => Sql::setBoolSql($post['CTC_CONSULT_CONT_FOU']),
                    ]);
                } else {
                    // @phpstan-ignore-next-line
                    $contGF->insert([
                        'CODE_GF' => $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'],
                        'TELPORT' => $post['TELPORT_CONT_FOU'],
                        'numerique_CTC_CONSULT' => Sql::setBoolSql($post['CTC_CONSULT_CONT_FOU']),
                    ]);
                }
            } else {
                if ($typeFG=='F') {
                    // @phpstan-ignore-next-line
                    $oldctc = $contactFrs->find(['CODE_FOU' => $codeFou, 'IND_FOU' => $IND_FOU]);
                    // @phpstan-ignore-next-line
                    $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']),
                        'numerique_CTC_CONSULT' => Sql::setBoolSql($post['CTC_CONSULT_CONT_FOU']),
                    ], [
                        'CODE_FOU' => $codeFou,
                        'IND_FOU' => $IND_FOU,
                    ]);
                } else {
                    // @phpstan-ignore-next-line
                    $contGF->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'],
                        'numerique_CTC_CONSULT' => Sql::setBoolSql($post['CTC_CONSULT_CONT_FOU']),
                    ], [
                        'CODE_GF' => $codeFou,
                        'IND_FOU' => $IND_FOU,
                    ]);
                }
            }
        } else {
            return new Response(443, [

            ], $this->renderer->render('@popup-erreur/ErreurCreation', [
                            'ErreurValid' => $validator->getError(),
                            'titrePopup' => $trad->t('Erreur'),
                        ]));
        }

        $ligne = $typeFG == 'F'
                        // @phpstan-ignore-next-line
                        ? $contactFrs->find([
                            "CODE_FOU" => $codeFou,
                            "IND_FOU" => $IND_FOU
                        ])
                        // @phpstan-ignore-next-line
                        :  $contGF->find([
                            "CODE_GF" => $codeFou,
                            "IND_FOU" => $IND_FOU
                        ]);

        $ligne["ISOXALINK"] = $ligne["OXALINK_ID"] !== '' ? true : false;

        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 {
            $ligne += [
                'IND_FOU' => $IND_FOU,
                'CODE_FOU' => $codeFou
            ];
            if ($contexte == 'consultMulti') {
                $prospect = Sql::toBool((new Fourniss($this->pdo))->find(['CODE' => $codeFou], ['PROSPECT'])['PROSPECT']);

                return $this->renderer->render('@GlobalApplication/ModifDaCde/ContactsFournisseur/detailMultiContact', [
                    'ligne' => $ligne,
                    'fromConsultation' => true,
                    'prospect' => $prospect,
                    'droit' => [
                        'HA_FRS_CON' => Roles::droitsUtilisateur($this->pdo, 'HA_FRS_CON'),
                        'HA_PRO_CON' => Roles::droitsUtilisateur($this->pdo, 'HA_PRO_CON')
                    ],
                ]);
            } else {
                return $this->renderer->render('@GlobalApplication/ModifDaCde/ContactsFournisseur/detailContact', [
                    'ligne' => $ligne,
                    'droit' => ['HA_FRS_CON' => Roles::droitsUtilisateur($this->pdo, 'HA_FRS_CON')]
                ]);
            }
        }
    }

    /**
     * @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 '';
    }
}
