<?php
namespace Modules\Panier\Controller;

use Entity\Model\ImpPanE;
use Entity\Model\ImpPanL;
use Entity\Model\ImpPanR;
use Entity\Model\OxaUserCnt;
use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Fichier\Fichier;
use Helpers\Log\LogSysteme;
use Helpers\Outil\Sql;
use Helpers\Pagination\Paginator;
use Modules\Panier\Repository\ImportPanier;
use Modules\Panier\Service\ImportService;
use Skeleton\Controller\Controller;
use Helpers\Session\ParseBase1;

class ImportLigneController extends Controller
{

    /**
     * @var array<mixed>
     */
    public $listeRef;

    /**
     * @var string
     */
    public $formatFav;

    public function init() :void
    {
        $impPanR = new ImpPanR($this->pdo);
        $this->listeRef = $impPanR->generateArray();

        $result = (new OxaUserCnt($this->pdo))->find([
            'COD_USR'       => $_SESSION["Session_Login"],
            'COD_TYPE'      => 'PROFIL',
            'COD_CHAMP'     => 'IMPORT',
        ]);

        $this->formatFav = $result['VALEUR'];
    }

    public function indexAction() : string
    {
        Ariane::generate(0, 'Import ligne');

        if (!$this->formatFav) {
            $impPanE = new ImpPanE($this->pdo);
            $defaultFormat = $impPanE->find(['PAR_DEF' => 'T']);
        } else {
            $defaultFormat['ID_PROFIL'] = $this->formatFav;
        }

        if ($defaultFormat['ID_PROFIL']) {
            $infoForamt = (new ImportPanier($this->pdo))->getArchitecture($defaultFormat['ID_PROFIL']);
        }

        return $this->renderer->render('@Panier/Import/index', [
            'menuActive'            => 'eproc',
            'menuLeft'              => 'import',
            'defaultFormat'         => $defaultFormat,
            'infoForamt'            => $infoForamt??[],
            'listeRef'              => $this->listeRef,
        ]);
    }

    public function ajaxChangeDefAction() : string
    {
        $post = $this->request->getParsedBody();
        
        $infoForamt = (new ImportPanier($this->pdo))->getArchitecture($post['ID_PROFIL']);

        return $this->renderer->render('@GlobalApplication/Component/_tableImportFormat', [
            'listCol' => array_map(function ($item) {
                return $item + [
                    'label' => $item['NOM_CHAMP'],
                    'mandatory' => Sql::toBool($item['OBLIG']),
                    'format' => $item['ATTRIBUT'],
                    'formatMask' => $item['MASQUE'],
                ];
            }, $infoForamt),
        ]);
    }

    public function listeFormatAction() : string
    {
        $post = $this->request->getParsedBody();

        $impPanE = new ImpPanE($this->pdo);
        $liste = $impPanE->fetchAll([], $post);

        $infoPagination = (new Paginator)->generate($liste, 8, $post, $this->renderer);

        return $this->renderer->render('@Panier/Import/popupListeFormat', [
            'listEntity' => $liste,
            'infoPagination' => $infoPagination,
            'post' => $post,
            'entity' => 'ImpPanE',
            'primaryKey' => $impPanE->getPrimaryKey(),
            'libelleKey' => $impPanE->getLibelle(),
            'fav'        => $this->formatFav,
        ]);
    }

    /**
     * @return Response
     */
    public function updateFavorisFormatAction()
    {
        $idFormat = $this->request->getAttribute('idFormat');

        (new OxaUserCnt($this->pdo))->merge([
            'COD_USR'       => $_SESSION["Session_Login"],
            'COD_TYPE'      => 'PROFIL',
            'COD_CHAMP'     => 'IMPORT',
            'VALEUR'        => $idFormat,
        ]);

        return new Response(200);
    }

    /**
     * @return mixed
     *
     *
     * si panier = vide et societe = societe panier, on importe
     * si panier = vide et societe != societe panier, on change la societe du panier et on importe
     * si panier != vide et societe != societe panier, on crash
     * si panier != vide et societe = societe panier, on importe
     *
     * Si societe != societe du panier et au moins une ligne est importé, on recalcule l'entête du panier
     */
    public function importAction()
    {
        set_time_limit(900);
        ini_set('memory_limit', '5048M');

        $post = $this->request->getParsedBody();
        $file = $this->request->getUploadedFiles();
        $validator = $this->createValidator();
        $trad = $this->getTranslationService();

        if ($file) {
            $file_name = $file['importimport']->getClientFilename();
            $fileSize = $file['importimport']->getSize();
        } else {
            $file_name = null;
            $fileSize = 0;
        }
        
        $validator->isObligatoire($post['ID_PROFIL'], $trad->t('Format de fichier'));
        $validator->fileCheck($trad->t('Fichier'), $file_name, ['csv'], '', $fileSize);

        if ($validator->isValid()) {
            $newPath = Fichier::UploadDocAtt($file_name);

            $filePath = $newPath["racine"].$newPath["new_name"];
            $file['importimport']->moveTo($filePath);

            $importCSV = new ImportService($this->contenaire->get('PDO.oxasql.withoutODBC'), $this->getPdoOxaFT(), $trad, $post['ID_PROFIL']);
            $importCSV->parseExcel($filePath);

            $messageSociete = $importCSV->controleSociete();

            if ($messageSociete) {
                return new Response(400, [], $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid' => $messageSociete,
                    'desactiveRow' => true,
                ]));
            }
            
            $importCSV->controle();

            $guid = null;
            if ($importCSV->getCountLigneError()) {
                $guid = Sql::guidGenerate();
                $fileBaseName = $_SESSION['Session_Login'].'_'.$guid;
                $fileName = Fichier::createExportCsvV2($fileBaseName, $importCSV->getLigneError(), []);
            }
            
            $arrayReport = [
                'nombreLigne'   => $importCSV->getCountLigne(),
                'nombreError'   => $importCSV->getCountLigneError(),
                'idProfil'      => $post['ID_PROFIL'],
                'ligne'         => $importCSV->getLigne(),
                'fileError'     => $fileName??'',
            ];

            if ($guid && isset($post['aff_journal'])) {
                Fichier::createFichierTmp(
                    'import_panier_log_'.$_SESSION['Session_Login'].'_'.$guid.'.txt',
                    (string)json_encode($arrayReport)
                );
            }

            if ($importCSV->getCountLigne() == $importCSV->getCountLigneError()) {
                if ($guid && isset($post['aff_journal'])) {
                    echo "<script>window.open('".$this->router->generateUri('Panier.ImportLigne.journalImport', ['token' => $guid])."','','width=1300px, height=800px,menubar=no, status=no, scrollbars=yes, resizable=yes,location=yes');</script>";
                }

                return new Response(400, [], $this->renderer->render('@popup-erreur/ErreurCreation', [
                    'ErreurValid' => $trad->t('Aucune ligne n\'a pu être importée.'),
                    'desactiveRow' => true,
                ]));
            }

            $importCSV->insertLignePanier();

            return new Response(200, [], (string) json_encode([
                'path' => $this->router->generateUri('Panier.Panier.index'),
                'post' => ['idImportPanier' => $guid]
            ]));
        } else {
            return new Response(400, [], $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'desactiveRow' => true,
            ]));
        }
    }

    /**
     * @return Response|string
     */
    public function journalImportAction()
    {
        $token = $this->request->getAttribute('token');
        $trad = $this->getTranslationService();

        $fileName = 'import_panier_log_'.$_SESSION["Session_Login"].'_'.$token.'.txt';
        $contentFile = file_get_contents((new ParseBase1())->getRep()->tmp.$fileName);
        if ($contentFile === false) {
            LogSysteme::prefixErrorLog('Missing file "'.$fileName.'"');
            return new Response(400, [], 'Invalid token');
        }

        $arrayFile = json_decode((string)$contentFile, true);
        if (! is_array($arrayFile)) {
            LogSysteme::prefixErrorLog('Invalid file value "'.(string)$contentFile.'"');
            return new Response(400, [], 'Invalid token');
        }
        
        $importCSV = new ImportService($this->pdo, $this->getPdoOxaFT(), $trad, $arrayFile['idProfil']);

        return $this->renderer->render('@Panier/Import/journal', [
            'nombreLigne'   => $arrayFile['nombreLigne'],
            'nombreError'   => $arrayFile['nombreError'],
            'infoForamt'    => $importCSV->getArchitecture(),
            'listeLigne'    => $arrayFile['ligne'],
            'fileError'     => $arrayFile['fileError'],
        ]);
    }
}
