<?php

namespace Modules\Consultation\Service;

use Entity\Model\AoContFour;
use Entity\Model\AoEntet;
use Entity\Model\AoFour;
use Entity\Model\Docatt;
use Entity\Model\Fourniss;
use Entity\Model\Hastutil;
use Entity\Model\Memos;
use Helpers\Outil\Date;
use Helpers\Outil\Mail;
use Helpers\Outil\Outils;
use Helpers\Outil\Sql;
use Helpers\Session\ParseBase1;
use Helpers\Trad\ITrad;
use Helpers\Trad\Trad;
use Modules\Consultation\Repository\AoEvent;
use Modules\Consultation\Repository\Consultation;

class SendEmailService
{
    /**
     * Summary of consultation
     * @var array<mixed>
     */
    private array $consultation;

    public function __construct(
        private \PDO $pdo,
        private ITrad $trad,
        private string $idAO,
    ) {
        $this->consultation = (new AoEntet($this->pdo))->find($idAO);
    }

    /**
     * Summary of newFourniss
     * @param array<mixed> $listeFrs
     * @param bool $accordConf
     * @return \SimpleXMLElement
     */
    public function newFourniss(array $listeFrs, bool $accordConf)
    {
            // Envoi de l'accord de conf via php si existant
        if ($accordConf) {
            // Récupération de l'accord de conf
            $docAtt = new Docatt($this->pdo);
            $idDoc = str_pad($this->idAO, 9, '0', STR_PAD_LEFT);

            $infoDoc = $docAtt->find(['NO_DA' => 'AO_ENTET', 'COD_ENR' => $idDoc, 'NO_ORDRE' => $this->consultation['ACC_CONF_NODOC']]);
            $path_info = pathinfo($infoDoc['NOM_FIC']);

            // Création liste data pour l'email
            $acheteur = (new Hastutil($this->pdo))->find($this->consultation['ACH']);
            $infoMail = [
                'NAO'           => $this->idAO,
                'RS_SOC'        => Outils::convertLibelleGlobal($this->pdo, $this->consultation['TYPE_SG']=='S'? 'Societe':'GrpSociete', '', $this->consultation['CODE_STE']),
                'OBJETAO'       => $this->consultation['OBJET_AO'],
                'NOM_ACH'       => $acheteur['NOM'],
                'DTE_VALID_AO'  => Date::dateConverte($this->consultation['DEL_REP']),
                'URL'           => Sql::paravrac($this->pdo, 'PF_OXALINK', 'URLACCESOXALINK'),
                'DATEREPAO'     => Date::dateConverte($this->consultation['DEL_REP']),
                "TITREAO"       => Sql::getMemo($this->pdo, $this->consultation["NM_TITRE"])
            ];

            foreach ($listeFrs as &$frs) {
                if ($frs["EMAILCONT"] !== "") {
                    $isOxalink = sql::boolSql($frs['GEREPORTAIL']) == true && $frs['ctcOxalinkActif'];
        
                    $new_name = 'Consult_'.$this->idAO.'_'.$frs['CODE_FOU']
                    .'_'.str_replace('t| ', '', $this->trad->t('Accord de Confidentialité'))
                    .'.' . ($path_info['extension'] ?? '');

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

                    copy($oldFic, $newFic);

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

                    Mail::generateMail(
                        $this->pdo,
                        $this->trad,
                        $frs['EMAILCONT'],
                        $isOxalink ? 'EXT_FOU_ACCCONF_LINK' :'AO_FOU_ACCORD_CONF',
                        $frs["COD_LNG"] ?? Trad::getPreferedLang(),
                        $infoMail,
                        [],
                        $isOxalink ? [] : [0 => $frs['sourcePJ']]
                    );

                    $aoEvent = new AoEvent($this->pdo);
                    $aoEvent->rqInsertEventAO(
                        $this->idAO,
                        'ENV',
                        'Demande de signature de l\'accord de confidentialité',
                        $frs['CODE_FOU'],
                        $frs['TYPE_FG']
                    );

                    $aoDaRep = new AoFour($this->pdo);
                    $aoDaRep->update(
                        ['FIC_ACC_CONF_SIGNE' => ''],
                        ['NO_AO' => $this->idAO, 'CODE_FOU' => $frs['CODE_FOU'], 'TYPE_FG' => $frs['TYPE_FG']]
                    );
                }
            }
        }

        foreach ($listeFrs as &$frs) {
            $frs['parMail'] = true;
            $frs['email'] = $frs["EMAILCONT"];
            $frs['formatExcel'] = false;
        }

        // Envoi de la consultation par email en passant via Magic
        $consultWsdl = new \Modules\Consultation\WebService\Consultation();
        $xmlResult = $consultWsdl->sendConsultation($this->idAO, "P", $listeFrs);
        return new \SimpleXMLElement($xmlResult->responseData);
    }

    /**
     * Summary of clotureInfructueuse
     * @return bool
     */
    public function clotureInfructueuse()
    {
        // Création liste data pour l'email
        $acheteur = (new Hastutil($this->pdo))->find($this->consultation['ACH']);
        $infoMail = [
            'NAO'           => $this->idAO,
            'RS_SOC'        => Outils::convertLibelleGlobal($this->pdo, $this->consultation['TYPE_SG']=='S'? 'Societe':'GrpSociete', '', $this->consultation['CODE_STE']),
            'OBJETAO'       => $this->consultation['OBJET_AO'],
            'NOM_ACH'       => $acheteur['NOM'],
            "TITREAO"       => Sql::getMemo($this->pdo, $this->consultation["NM_TITRE"])
        ];

        $AoFour = new AoFour($this->pdo);
        $AoContFour = new AoContFour($this->pdo);
        $Fourniss = new Fourniss($this->pdo);
        $listeFrs = $AoFour->findAll(["NO_AO" => $this->idAO]);

        foreach ($listeFrs as $key => $frs) {
            $allCtct = $AoContFour->findAll(['NO_AO' => $this->idAO, 'CODE_FOUR' => $frs["CODE_FOU"]]);
            // ! Ajout de l'email du contact présent sur AO_FOUR
            $allCtct[] = $frs['EMAILCONT']!=''?['EMAILCONT' => $frs['EMAILCONT']]:[];
            $codLng = $Fourniss->find($frs["CODE_FOU"], ['COD_LNG'])['COD_LNG'];
            $emailList = '';
            foreach ($allCtct as $ctct) {
                if (array_key_first($listeFrs) == $key) {
                    $emailList .= $ctct['EMAILCONT'];
                } else {
                    $emailList .= ', ' . $ctct['EMAILCONT'];
                }
            }
            Mail::generateMail(
                $this->pdo,
                $this->trad,
                str_replace(' ', '', $emailList),
                'AO_CLOT_INFRUCT',
                $codLng ?? Trad::getPreferedLang(),
                $infoMail,
                []
            );
            $aoEvent = new AoEvent($this->pdo);
            $aoEvent->rqInsertEventAO(
                $this->idAO,
                'CLI',
                'Clôture pour consultation infructueuse : email envoyé à ' . $frs["NOM_CTCT"] . ' (fournisseur n°) ' . $frs["CODE_FOU"] . ' : ' . $emailList,
                $frs['CODE_FOU'],
                $frs['TYPE_FG']
            );
        }

        return true;
    }

    /**
     * Summary of dateRepChanged
     * @param mixed $oldDate
     * @return bool
     */
    public function dateRepChanged($oldDate)
    {
        $AoFour = new AoFour($this->pdo);
        $AoContFour = new AoContFour($this->pdo);
        $Fourniss = new Fourniss($this->pdo);
        $listeFrs = $AoFour->findAll(["NO_AO" => $this->idAO]);
        $hastutilEntity = new Hastutil($this->pdo);
        $user = $hastutilEntity->find($this->consultation['ACH']);

        $infoMail = [
            "NAO"           => $this->idAO,
            "OLD_DTE_LREP"  => $oldDate,
            "DTE_LREP"      => Date::dateConverte($this->consultation["DEL_REP"]),
            "NOM_ACH"       => $user["NOM"],
            "TITREAO"       => Sql::getMemo($this->pdo, $this->consultation["NM_TITRE"]),
            'OBJETAO'       => $this->consultation['OBJET_AO'],
            'RS_SOC'        => Outils::convertLibelleGlobal($this->pdo, $this->consultation['TYPE_SG']=='S'? 'Societe':'GrpSociete', '', $this->consultation['CODE_STE']),
        ];

        foreach ($listeFrs as $key => $frs) {
            $allCtct = $AoContFour->findAll(['NO_AO' => $this->idAO, 'CODE_FOUR' => $frs["CODE_FOU"]]);
            // ! Ajout de l'email du contact présent sur AO_FOUR
            $allCtct[] = $frs['EMAILCONT']!='' ? ['EMAILCONT' => $frs['EMAILCONT']] : [];
            $codLng = $Fourniss->find($frs["CODE_FOU"], ['COD_LNG'])['COD_LNG'];
            $emailList = '';
            foreach ($allCtct as $ctct) {
                if (array_key_first($listeFrs) == $key) {
                    $emailList .= $ctct['EMAILCONT'];
                } else {
                    $emailList .= ', ' . $ctct['EMAILCONT'];
                }
            }
            if ($emailList != '') {
                Mail::generateMail(
                    $this->pdo,
                    $this->trad,
                    str_replace(' ', '', $emailList),
                    'AO_DATE_LREP_CHANGED',
                    $codLng ?? Trad::getPreferedLang(),
                    $infoMail
                );
                $aoEvent = new AoEvent($this->pdo);
                $aoEvent->rqInsertEventAO(
                    $this->idAO,
                    'CDL',
                    'Changement de la date limite de réponse du ' . (string) $oldDate . ' au ' . Date::dateConverte($this->consultation["DEL_REP"]) . ' : email envoyé à ' . $frs["NON_CTCT"] . ' (fournisseur n°) ' . $frs["CODE_FOU"] . ' : ' . $emailList,
                    $frs['CODE_FOU'],
                    $frs['TYPE_FG']
                );
            }
        }

        return true;
    }
}
