<?php

namespace Modules\Consultation\Service;

use Entity\Model\AoDocAttendus;
use Entity\Model\AoPijo;
use Entity\Model\Fourniss;
use Entity\Model\Grpfou;
use Entity\Model\ParamDico;
use Helpers\Fichier\Fichier;
use Helpers\Outil\Date;
use Helpers\Outil\Mail;
use Helpers\Outil\Sql;
use Helpers\Trad\ITrad;
use Modules\Consultation\Repository\AoEvent;
use Modules\Consultation\Repository\ExportExcel;
use Modules\Consultation\Repository\Reponse;
use Skeleton\Router;
use Helpers\Session\ParseBase1;

class EnvoieExcelService
{
    private \PDO $pdo;
    private ITrad $trad;
    private router $router;

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

    /**
     * Undocumented function
     *
     * @param string $idAO
     * @param array<mixed> $excel
     * @param array<mixed> $consultation
     * @param array<mixed> $user
     * @return array<mixed>|void|string
     */
    public function generationEnvoieExcel($idAO, $excel, $consultation, $user, ?string $token = null, bool $onlyFileName = false)
    {
        $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();
        $aoPijo = new AoPijo($this->pdo);

        $attachements = $aoPijo->findAll(['NO_AO' => $idAO]);
        $attachementsList = [];


        foreach ($attachements as $doc) {
            $file =
                (new ParseBase1())->getRep()->pj
                . DIRECTORY_SEPARATOR
                . ltrim($doc['NOM_FIC'], '\\/');
            if (is_file($file)) {
                Fichier::copyFile(
                    $file,
                    $dest = (new ParseBase1())->getRep()->tmp . $doc['NOM_ORI']
                );
                $attachementsList[] = $dest;
            }
        }

        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']) {
            $listeDocument = (new AoDocAttendus($this->pdo))->findAll(['NO_AO' => $idAO, 'OBLIGATOIRE' => 0x54]);
            $listeDocument = array_column($listeDocument, 'TITRE_DOC', 'TITRE_DOC');

            if (is_array($listeDocument)) {
                $listeDocument = implode("\r\n", $listeDocument);
            }

            $infoMail = [
                'N°AO'              => $idAO,
                'DATEREPATT'        => Date::dateConverte($consultation['DEL_REP']),
                'NOM_ACH'           => $user['NOM'],
                'FONCTION'          => $user['FONCTION'],
                'LSTDOCATTENDUS'    => $listeDocument,
            ];

            if ($excel['TYPE_FG'] == 'G') {
                $infoFrs = (new Grpfou($this->pdo))->find($excel['CODE_FOU']);
            } else {
                $infoFrs = (new Fourniss($this->pdo))->find($excel['CODE_FOU']);
            }


            $fileTmp = (new ParseBase1())->getRep()->tmp.$fileName;
            $attachementsList[] = $fileTmp;
            Mail::generateMail(
                $this->pdo,
                $this->trad,
                $excel['emails'],
                'AO_SEND',
                $infoFrs['COD_LNG'],
                $infoMail,
                [],
                $attachementsList
            );
            
            (new AoEvent($this->pdo))->rqInsertEventAO($idAO, 'ENV', '', $excel['CODE_FOU'], $excel['TYPE_FG']);
        } else {
            if ($onlyFileName) {
                return $fileName;
            }
            $url = $fileName;

            $urlJS = $this->router->generateUri('GlobalApplication.ChargeDocument.chargeDocument', [
                'emplacement' => 'tmp',
                'urlFichier' => $url,
                'modeAffichage' => 0
            ]);

            $listeUrl [] = $urlJS;
        }

        return $listeUrl;
    }
}
