<?php

namespace Modules\Consultation\Service;

use Entity\Model\AoEntet;
use Entity\Model\Hastutil;
use Helpers\ExportTo\Generate;
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 Helpers\User\User;
use Modules\Consultation\Repository\AoEvent;
use Modules\Consultation\Repository\Consultation;
use Modules\Consultation\Repository\QuestionReponseRepo;
use PhpOffice\PhpSpreadsheet\IOFactory;

class ExportReponseService
{

    private string $typeFG;
    private string $codeFrs;
    private string $idAO;

    /**
     * @var array<mixed>
     */
    private array $reponseSelected;

    public function __construct(
        private \PDO $pdo,
        private ITrad $trad,
        private QuestionReponseRepo $questionReponseRepo,
        private Hastutil $hastutil,
        private User $user,
        private AoEntet $aoEntet,
        private AoEvent $aoEvent,
        private Consultation $consultationRepo
    ) {
        $this->reponseSelected = [];
    }

    public function setidAO(string $idAO):void
    {
        $this->idAO = $idAO;
    }

    public function setFrs(string $typeFG, string $codeFrs):void
    {
        $this->typeFG = $typeFG;
        $this->codeFrs = $codeFrs;
    }

    /**
     * @param array<mixed> $reponseSelected
     * @return void
     */
    public function setReponseSelected(array $reponseSelected):void
    {
        $this->reponseSelected = $reponseSelected;
    }

    public function sendReponse(bool $all = false):void
    {
        $listeReponse = $this->questionReponseRepo->listeReponseSend($this->idAO, $this->codeFrs, $this->typeFG, $this->reponseSelected, $all);

        if (!$listeReponse) {
            return;
        }

        $allCtcts = $this->consultationRepo->getAllCtcWithCheckIfOxalinkAccess($this->idAO, $this->codeFrs, $this->typeFG);

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

        //todo si fournisseur oxalink, envoie un mail pour lui indiqué de voir les réponses sur le portail.
        
        $fileName = 'AO_'.str_pad((string)$this->idAO, 9, '0', STR_PAD_LEFT).$this->codeFrs;

        $excel = new Generate($fileName, 'excel', $listeReponse, [$this->trad->t('Numéro'), $this->trad->t('Question'), $this->trad->t('Réponse')]);
        $fileName = (new ParseBase1())->getRep()->tmp.$excel->getExcel();

        $this->questionReponseRepo->updateSending($this->idAO, $this->codeFrs, $this->typeFG, $this->reponseSelected, $all);

        $consultation = $this->aoEntet->find($this->idAO);
        $user = $this->hastutil->find($this->user->getCodeUser());

        $infoMailNonOxalink = [
            'NAO' => $this->idAO,
            'TITREAO' => Sql::getMemo($this->pdo, $consultation['NM_TITRE']),
            'OBJETAO' => $consultation['OBJET_AO'],
            'NOM_ACH' => $user['NOM'],
            'RS_SOC' => Outils::convertLibelleGlobal($this->pdo, $consultation['TYPE_SG'] == 'S' ? 'Societe' : 'GrpSociete', '', $consultation['CODE_STE']),
        ];

        $infoMailOxalink = [
            'NAO' => $this->idAO,
            'TITREAO' => sql::getMemo($this->pdo, $consultation['NM_TITRE']),
            'OBJETAO' => $consultation['OBJET_AO'],
            'NOM_ACH' => $user['NOM'],
            'RS_SOC' => Outils::convertLibelleGlobal($this->pdo, $consultation['TYPE_SG'] == 'S' ? 'Societe' : 'GrpSociete', '', $consultation['CODE_STE']),
            'URL'   => Sql::paravrac($this->pdo, 'PF_OXALINK', 'URLACCESOXALINK'),
        ];

        foreach ($listeNonOxalink as $ctct) {
            Mail::generateMail(
                $this->pdo,
                $this->trad,
                $ctct['EMAILCONT'],
                'EXT_AO_FQR_REP_TAB',
                $ctct['COD_LNG'],
                $infoMailNonOxalink,
                [],
                [$fileName]
            );
        }

        foreach ($listeOxalink as $ctct) {
            Mail::generateMail(
                $this->pdo,
                $this->trad,
                $ctct['EMAILCONT'],
                'EXT_AO_FQR_REP_LINK',
                $ctct['COD_LNG'],
                $infoMailOxalink,
                [],
            );
        }

        $this->aoEvent->rqInsertEventAO($this->idAO, 'QRE', '', $this->codeFrs, $this->typeFG);
    }
}
