<?php declare(strict_types=1);

namespace API\Batch\Consultation;

use API\Batch\BatchDefault;
use Entity\Model\AoEntet;
use Entity\Model\AoExcFofo;
use Entity\Model\Docatt;
use Entity\Model\Hastutil;
use Helpers\Outil\Date;
use Helpers\Outil\Mail as HelperMail;
use Helpers\Outil\Outils;
use Helpers\Outil\Sql;
use Helpers\Session\ParseBase1;
use Modules\Consultation\Repository\AoEvent;
use Modules\Consultation\Repository\Consultation;
use Modules\Consultation\Repository\Contributor;
use Modules\Consultation\Repository\GestionConsultation;
use Modules\Consultation\WebService\Consultation as ConsultWSDL;
use Modules\Consultation\Service\EnvoieExcelService;

class Mail extends BatchDefault
{

    public function envoieMailFournisseur(
        AoEntet $aoEntet,
        Hastutil $hastutil,
        Consultation $consultRepo,
        AoEvent $aoEvent,
        ParseBase1 $parseBase1,
        Docatt $docAtt,
        AoExcFofo $AoExcFofo,
        EnvoieExcelService $envoieExcelService,
        ConsultWSDL $consultWsdl
    ): void {
        // --- récupération des paramètres ---
        $args = $this->getParsedBody();
        $idAO = $args['idAO'];

        // --- traitement ---
        $consultation = $aoEntet->find($idAO);
        $acheteur     = $hastutil->find($consultation['ACH'])['NOM'] ?? '';

        $infoMail = [
            'NAO' => $idAO,
            'TITREAO' => Sql::getMemo($this->pdo, $consultation['NM_TITRE']),
            'RS_SOC' => Outils::convertLibelleGlobal($this->pdo, $consultation['TYPE_SG'] == 'S' ? 'Societe' : 'GrpSociete', '', $consultation['CODE_STE']),
            'OBJETAO' => $consultation['OBJET_AO'],
            'NOM_ACH' => $acheteur,
            'DTE_VALidAO$idAO_AO' => Date::dateConverte($consultation['DTE_VALidAO$idAO_AO']),
            'DTE_LANCEMENT' => Date::dateConverte($consultation['DTE_LANCEMENT']),
            'URL' => Sql::paravrac($this->pdo, 'PF_OXALINK', 'URLACCESOXALINK'),
            'DATEREPAO' => Date::dateConverte($consultation['DEL_REP']),
            'NOMACH' => $acheteur,
        ];

        $listeOxalink    = [];
        $listeNonOxalink = [];

        $allCtcts = $consultRepo->getAllCtcWithCheckIfOxalinkAccess($idAO);

        foreach ($allCtcts as $currentCtct) {
            if ($currentCtct['fourHasContactWithOxalinkAccess']) {
                $listeOxalink[] = $currentCtct;
            } else {
                $listeNonOxalink[] = $currentCtct;
            }
        }

        foreach ($listeOxalink as $ctct) {
            if (Sql::boolSql($consultation['ACC_CONF']) == true) {
                HelperMail::generateMail(
                    $this->pdo,
                    $this->trad,
                    $ctct['EMAILCONT'],
                    'EXT_FOU_ACCCONF_LINK',
                    $ctct['COD_LNG'],
                    $infoMail,
                    [],
                );
            } else {
                $infoMail['NOM_ACH'] = $infoMail['NOMACH'];
                HelperMail::generateMail(
                    $this->pdo,
                    $this->trad,
                    $ctct['EMAILCONT'],
                    'EXT_FOU_INFOAO_LINK',
                    $ctct['COD_LNG'],
                    $infoMail,
                    [],
                );
            }

            $message = Sql::boolSql($consultation['ACC_CONF']) == true
                ? 'Demande de signature de l\'accord de confidentialité'
                : '';
            $aoEvent->rqInsertEventAO($idAO, 'ENV', $message, $ctct['CODE_FOUR'], $ctct['TYPE_FG']);
            
            if (Sql::boolSql($consultation['ACC_CONF']) == true) {
                $infoDoc   = $docAtt->find([
                    'NO_DA' => 'AO_ENTET',
                    'COD_ENR' => str_pad($idAO, 9, '0', STR_PAD_LEFT),
                    'NO_ORDRE' => $consultation['ACC_CONF_NODOC']
                ]);
                $path_info = pathinfo($infoDoc['NOM_FIC']);
                foreach ($listeNonOxalink as $ctctNonOxalink) {
                    $new_name = 'Consult_' . $idAO . '_' . $ctctNonOxalink['CODE_FOUR']
                        . '_' . str_replace('t| ', '', $this->trad->t('Accord de Confidentialité'))
                        . '.' . ($path_info['extension'] ?? '');

                    $oldFic = $parseBase1->getRep()->pj . $infoDoc['NOM_FIC'];
                    $newFic = $parseBase1->getRep()->tmp . $new_name;

                    copy($oldFic, $newFic);

                    $ctctNonOxalink['pj']       = $new_name;
                    $ctctNonOxalink['sourcePJ'] = $newFic;

                    HelperMail::generateMail(
                        $this->pdo,
                        $this->trad,
                        $ctctNonOxalink['EMAILCONT'],
                        'AO_FOU_ACCORD_CONF',
                        $ctctNonOxalink['COD_LNG'],
                        $infoMail,
                        [],
                        [$ctctNonOxalink['sourcePJ']]
                    );

                    $aoEvent->rqInsertEventAO($idAO, 'ENV', 'Demande de signature de l\'accord de confidentialité', $ctctNonOxalink['CODE_FOUR'], $ctctNonOxalink['TYPE_FG']);
                }
            } else {
                $listeFrs = [];
                foreach ($listeNonOxalink as $ctctNonOxalink) {
                    if (!isset($listeFrs[$ctctNonOxalink['CODE_FOUR']])) {
                        $listeFrs[$ctctNonOxalink['CODE_FOUR']] = [
                            'CODE_FOU' => $ctctNonOxalink['CODE_FOUR'],
                            'TYPE_FG' => $ctctNonOxalink['TYPE_FG'],
                            'parMail' => 'true',
                            'emails' => $ctctNonOxalink['EMAILCONT']
                        ];

                        // TODO : merge queries
                        $paramExcelByfrs  = $AoExcFofo->find([
                            'SOCIETE' => $consultation['CODE_STE'],
                            'CTRE' => $consultation['EMETTEUR'],
                            'CODE_FOU' => $ctctNonOxalink['CODE_FOUR']
                        ]);
                        $paramExcelDefaut = $AoExcFofo->getForm($consultation);

                        if ($paramExcelByfrs) {
                            $listeFrs[$ctctNonOxalink['CODE_FOUR']]['typeFormatExcel'] = $paramExcelByfrs['CODEFORM'] ?? '';
                            $listeFrs[$ctctNonOxalink['CODE_FOUR']]['versionFormat']   = $paramExcelByfrs['VERSFORM'] ?? '';
                        } else {
                            $listeFrs[$ctctNonOxalink['CODE_FOUR']]['typeFormatExcel'] = $paramExcelDefaut['CODEFORM'] ?? '';
                            $listeFrs[$ctctNonOxalink['CODE_FOUR']]['versionFormat']   = $paramExcelDefaut['VERSFORM'] ?? '';
                        }
                    } else {
                        $listeFrs[$ctctNonOxalink['CODE_FOUR']]['emails'] .= ',' . $ctctNonOxalink['EMAILCONT'];
                    }
                }

                foreach ($listeFrs as $key => &$frs) {
                    if ($frs['typeFormatExcel'] !== '' && $frs['versionFormat'] !== '') {
                        $envoieExcelService->generationEnvoieExcel(
                            $idAO,
                            $frs,
                            $consultation,
                            $acheteur
                        );
                        unset($listeFrs[$key]);
                    }
                }

                $consultWsdl->sendConsultation($idAO, "P", $listeFrs);
            }
        }
    }

    public function envoieMailContrib(
        Contributor $contributorRepo,
        GestionConsultation $repo
    ): void {
        // --- récupération des paramètres ---
        $args = $this->getParsedBody();
        $idAO = $args['idAO'];

        $aoInfo = $repo->getInfoAo($idAO);
        $copieCache = (Sql::toBool($aoInfo['Acheteur_BCC_MAO'])
            ? $aoInfo['Acheteur_EMAIL']
            : null);


        $contributorsList = $contributorRepo->getAllRfxContributors($idAO);
        foreach ($contributorsList as $contributor) {
            $lang = $contributor['COD_LNG'];

            // Fail-safe
            if (empty($contributor['email'])) {
                throw new \Exception('Missmatch on '. $contributor['contrib']);
            }

            HelperMail::generateMail(
                $this->pdo,
                $this->trad,
                $contributor['email'],
                'AO_CONTRIB_REL',
                $lang,
                [
                    'NO_AO' => $idAO,
                    'NOM_CONTRIB' => $contributor['NOM'],
                    'DTE_DEBUT_NOTATION' => Date::dateConverte($aoInfo['DEL_REP']),
                    'DTE_FIN_NOTATION' => Date::dateConverte($aoInfo['DTE_LIMIT_CONTRIB']),
                    'NOM_ACH' => $aoInfo['Acheteur_NOM'],
                ],
                [],
                $copieCache
            );
        }
    }
}
