<?php

namespace Modules\Consultation\Service;

use Entity\Model\Fourniss;
use Entity\Model\ParamDico;
use Helpers\Outil\Date;
use Helpers\Outil\Mail;
use Helpers\Outil\Sql;
use Helpers\Trad\ITrad;
use Modules\Consultation\Repository\ExportExcel;

class EnvoieExcelService
{
    private \PDO $pdo;
    private ITrad $trad;
    private string $base;

    public function __construct(\PDO $pdo, ITrad $trad, string  $base)
    {
        $this->pdo = $pdo;
        $this->trad = $trad;
        $this->base = $base;
    }

    /**
     * Undocumented function
     *
     * @param string $idAO
     * @param array<mixed> $excel
     * @param array<mixed> $consultation
     * @param array<mixed> $user
     * @return array<mixed>|void
     */
    public function generationEnvoieExcel($idAO, $excel, $consultation, $user, string $token = null)
    {
        $listeUrl = [];
        $exportExcelRepo = new ExportExcel($this->pdo);

        $idForm = $exportExcelRepo->insertEnvoieExcel(
            $idAO,
            $excel['CODE_FOU'],
            $excel['TYPE_FG'],
            $excel['typeFormatExcel'],
            $excel['versionFormat']
        );
        
        $exportExcelService = new ExportExcelService($this->pdo, $idForm, $this->trad);
        $fileName = $exportExcelService->generateExcel();

        if ($token) {
            (new ParamDico($this->pdo))->update([
                'ALPHA7' => $fileName
            ], [
                'TYPEDICO'  => 'MAGIC_HTTP_RELAIS_PHP',
                'ID1'       => $token,
                'ID2'       => 'ENVOI_CONSULT',
                'ALPHA1'    => $idAO,
                'ALPHA2'    => $excel['CODE_FOU'],
                'ALPHA3'    => $excel['TYPE_FG'],
            ]);
            return;
        }

        if ($excel['parMail']) {
            $infoMail = [
                'N°AO'          => $idAO,
                'DATEREPATT'    => Date::dateConverte($consultation['DEL_REP']),
                'NOM_ACH'       => $user['NOM'],
                'FONCTION'      => $user['FONCTION'],
            ];
            $fourniss = new Fourniss($this->pdo);
            $infoFrs = $fourniss->find($excel['CODE_FOU']);

            $fileTmp = $_SESSION['dir_tmp'].$fileName;
            Mail::generateMail(
                $this->pdo,
                $this->trad,
                $excel['email'],
                'AoSend',
                $infoFrs['COD_LNG'],
                $infoMail,
                [],
                [0 => $fileTmp]
            );
        } else {
            $url = $fileName;
            $param = '?uniq=' . Sql::guidGenerate();
            $param .= '&token=' . password_hash($_SESSION['Session_Login'].session_id(), PASSWORD_DEFAULT);
            $urlJS = $this->base. 'charge_document.php'.$param.'&EmplacementFichier=tmp&UrlFichier='.$url;

            $listeUrl [] = $urlJS;
        }

        return $listeUrl;
    }
}
