<?php
namespace Modules\Consultation\Controller;

use Entity\Model\AoEntet;
use Entity\Model\Hastutil;
use Entity\Model\Memos;
use Entity\Model\Paravrac;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Outil\ArrayHelper;
use Helpers\Outil\Date;
use Helpers\Outil\Mail;
use Helpers\Outil\Sql;
use Helpers\Session\Enums\MenuTopEnum;
use Helpers\Session\Session;
use Modules\Ajax\WebService\EnvoiMail;
use Modules\Consultation\Repository\AoEvent;
use Modules\Consultation\Repository\GestionConsultation;
use Skeleton\Controller\Controller;

class RelanceFourController extends Controller
{
    public function indexAction() : string
    {
        $idAO = $this->request->getAttribute('idAO');

        $trad = $this->getTranslationService();
        $repo = new GestionConsultation($this->pdo);

        $listeFourniss = $repo->listeFournisseurConsultation($idAO);

        if (!empty($listeFourniss)) {
            $map = ArrayHelper::indexBy($listeFourniss, 'TYPE_FG');
            $mapContact = $repo->getMapContactAvailable(
                array_column($map['F'] ?? [], 'CODE_FOU'),
                array_column($map['G'] ?? [], 'CODE_FOU')
            );
        }

        // Join listContactChoice
        foreach ($listeFourniss as &$fourniss) {
            $fullId = $fourniss['TYPE_FG'] . $fourniss['CODE_FOU'];

            
            $listContactChoice = array_column(
                $mapContact[ $fullId ] ?? [],
                'NOM',
                'EMAIL'
            );
            if (! empty($fourniss['EMAILCONT'])) {
                $listContactChoice[ $fourniss['EMAILCONT'] ] =
                    empty($fourniss['NOM_CTCT']) ? $trad->t('Inconnu') : $fourniss['NOM_CTCT'];
            } elseif (!empty($listContactChoice)) {
                $listContactChoice[''] = '-';
            }
            $fourniss['listContactChoice'] = $listContactChoice;
        }
        unset($fourniss);

        Ariane::generate(1, $trad->t('Relancer les fournisseurs'));

        $ao = (new AoEntet($this->pdo))->find($idAO);
        $ao['Titre'] = (new Memos($this->pdo))->getValue($ao['NM_TITRE']);
        $acheteur = (new Hastutil($this->pdo))->find($ao['ACH']);

        

        $listeData = [
            'NAO' => $ao['NO_AO'],
            'OBJETAO' => $ao['OBJET_AO'],
            'URL' => (new Paravrac($this->pdo))->getValue('PF_OXALINK', 'URLACCESOXALINK'),
            'DATEREAO' => Date::dateConverte($ao['DEL_REP']),
            'NOMACH' => $acheteur['NOM'],
            'TITREAO' => $ao['Titre'],
            'DATEREPAO' => Date::dateConverte($ao['DEL_REP']),

            // used exclusively for ExtRelfouLink (default email)
            'Fournisseur_GEREPORTAIL' => true,
            'Entete_DEL_REP' => Date::dateConverte($ao['DEL_REP']),
        ];

        $mailData = Mail::getEmailData($this->pdo, $trad, 'EXT_RELFOU_LINK', $_SESSION['Session_Langue'], $listeData, []);

        return $this->renderer->render('@Consultation/RelanceFour/index', [
            'menuActive'        => Session::verifySessionTypeMenuTop(MenuTopEnum::P2P) ? 'eproc':'Consultations',

            'idAO' => $idAO,
            'ao' => $ao,
            'acheteur' => (new Hastutil($this->pdo))->find($ao['ACH']),
            'listeFourniss' => $listeFourniss,
            'defaultEmail' => [
                'sujet' => $mailData['sujet'],
                'message' => $mailData['message']
            ],
        ]);
    }

    public function envoieMailRelanceAction() :Response
    {
        $idAO = $this->request->getAttribute('idAO');
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();

        //___________________
        // Validation

        $listSelection = $post['listFourniss'] ?? [];
        $listSelection = array_filter($listSelection, function ($item) {
            return !empty($item['selected']);
        });
        $listFournissFullId = array_keys($listSelection);
        if (empty($listFournissFullId)) {
            return new Response(400, [], $trad->t('Vous devez sélectionner au moins une ligne.'));
        }

        $validator = $this->createValidator();
        if (isset($post['EMAIL_SUBJECT'])) {
            $validator->isStringAvecEspace(
                $trad->t('Sujet du mail'),
                $post['EMAIL_SUBJECT'],
                1,
                100
            );
        }
        if (isset($post['EMAIL_BODY'])) {
            $validator->isStringAvecEspace(
                $trad->t('Email'),
                $post['EMAIL_BODY'],
                1,
                3000
            );
        }

        foreach ($listSelection as $item) {
            $validator->adresseMail(
                $trad->t('Email'),
                $item['email'],
                1
            );
        }

        if (! $validator->isValid()) {
            return new Response(400, [], $validator->getError());
        }

        //___________________
        // Envoie mail

        $repo = new GestionConsultation($this->pdo);

        $aoInfo = $repo->getInfoAo($idAO);
        $listConsultFour = $repo->listFournissConsultEnvoiMail($idAO, $listFournissFullId);

        $copieCache =
            (Sql::toBool($aoInfo['Acheteur_BCC_MAO']) ?
                $aoInfo['Acheteur_EMAIL'] : null);

        if (isset($post['EMAIL_SUBJECT']) && isset($post['EMAIL_BODY'])) {
            foreach ($listConsultFour as $consultFour) {
                $fullId = $consultFour['TYPE_FG'] . $consultFour['CODE_FOU'];
                $email = $listSelection[ $fullId ]['email'];

                // Fail-safe
                if (empty($email)) {
                    throw new \Exception('Missmatch on '. $fullId);
                }
                
                (new EnvoiMail())->envoiMail([
                    'destinataires' => $email,
                    'sujet' => $post['EMAIL_SUBJECT'],
                    'message' => $post['EMAIL_BODY'],
                    'copie ' => null,
                    'copie_cachee' => $copieCache,
                    'pj' => [],
                ]);
            }
        } else {
            $url = (new Paravrac($this->pdo))->getValue('PF_OXALINK', 'URLACCESOXALINK');
            foreach ($listConsultFour as $consultFour) {
                $lang =
                    $consultFour['Fournisseur']['COD_LNG']
                    ?? $consultFour['GroupFou']['COD_LNG'];
                $tradFou = $trad->copy($lang);

                $fullId = $consultFour['TYPE_FG'] . $consultFour['CODE_FOU'];
                $email = $listSelection[ $fullId ]['email'];

                // Fail-safe
                if (empty($email)) {
                    throw new \Exception('Missmatch on '. $fullId);
                }
    
                $mail = Mail::generateMail(
                    $this->pdo,
                    $trad,
                    $email,
                    'EXT_RELFOU_LINK',
                    $lang,
                    [
                        'NAO' => $aoInfo['NO_AO'],
                        'OBJETAO' => $aoInfo['OBJET_AO'],
                        'URL' => $url,
                        'TITREAO' => $aoInfo['TITRE'],
                        'DATEREAO' => Date::dateConverte($aoInfo['DEL_REP']), // Délai de réponse AO (old)
                        'DATEREPAO' => Date::dateConverte($aoInfo['DEL_REP']), // Délai de réponse AO
                        'NOMACH' => $aoInfo['Acheteur_NOM'],
                        'RAPPEL' => $tradFou->t('Rappel') . $tradFou->colon(),
            
                        // used exclusively for ExtRelfouLink (default email)
                        'Fournisseur_GEREPORTAIL' => Sql::toBool($consultFour['Fournisseur']['GEREPORTAIL']),
                        'Entete_DEL_REP' => $aoInfo['DEL_REP'],
                    ],
                    [],
                    $copieCache
                );

                // TODO : merge query
                // Create event
                (new AoEvent($this->pdo))->rqInsertEvent(
                    $idAO,
                    'REL',
                    $mail['sujet'] . "\r\n"
                    . $mail['message'],
                    $consultFour['TYPE_FG'],
                    $consultFour['CODE_FOU']
                );
            }
        }

        return new Response(200);
    }
}
