<?php

namespace Modules\Systeme\Controller;

use Entity\Model\Langues;
use Entity\Model\TxtATrad;
use Entity\Model\TxtTrad;
use GuzzleHttp\Psr7\Response;
use Helpers\Session\ParseBase1;
use Helpers\Trad\ExtractionTrad;
use Skeleton\Controller\Controller;

class TraductionSystemeController extends Controller
{
    public function tradAction(): string
    {

        $typeTrad  = $this->request->getAttribute('name');

        $file      = fopen(__DIR__ . '../../../../../extraction_libelle_global_V2.txt', 'r');

        $fieldTrad = [];
        $render = '';

        if ($typeTrad == 'tradBDD') {
            $txtTrad      = new TxtTrad($this->pdo);
            $langue = new Langues($this->pdo);
            $lng = $langue->fetchAll();

            foreach ($lng as $lngV) {
                if ($file !== false) {
                    $txtCompareBDD = [];
                    $txtBDD = $txtTrad->findAll(
                        [
                            'COD_LNG' => $lngV['COD_LNG'],
                            'COD_PROD' => $this->contenaire->get('PRODUCT_CODE')
                        ]
                    );
                    foreach ($txtBDD as $value) {
                        $txtCompareBDD[$value['TXT']] = 1;
                    }
                    

                    $file      = fopen(__DIR__ . '../../../../../extraction_libelle_global_V2.txt', 'r');
                    if ($file) {
                        while (($line = fgetcsv($file)) !== false) {
                            $chaine = str_replace('""', '$$$', (string)mb_convert_encoding(explode(';', $line[0])[1], 'UTF-8', 'ISO-8859-1'));
                            $chaine = str_replace('"', '', $chaine);
                            $chaine = str_replace('$$$', '"', $chaine);
        
                            if (!key_exists($chaine, $txtCompareBDD)) {
                                $fieldTrad[$lngV['LIBELLE']][$chaine] = '"' . $chaine . '"';
                            }
                        }
                    }
                }
            }

            $render = $this->renderer->render('@Systeme/errorTrad', [
                'menuActive' => 'Systeme',
    
                'fieldNoTrad' => $fieldTrad
            ]);
        } elseif ($typeTrad == 'tradENV') {
            $txtATrad      = new TxtATrad($this->pdo);
            if ($file !== false) {
                $txtCompareFile = [];
    
                $txtEnv = $txtATrad->findAll(
                    [
                        'COD_PROD' => $this->contenaire->get('PRODUCT_CODE')
                    ]
                );
    
                foreach ($txtEnv as $value) {
                    $txtCompareFile[$value['TXT']] = 1;
                }
    
                while (($line = fgetcsv($file)) !== false) {
                    $chaine = str_replace('""', '$$$', (string)mb_convert_encoding(explode(';', $line[0])[1], 'UTF-8', 'ISO-8859-1'));
                    $chaine = str_replace('"', '', $chaine);
                    $chaine = str_replace('$$$', '"', $chaine);
    
                    if (!key_exists($chaine, $txtCompareFile)) {
                        $fieldTrad[] = '"' . $chaine . '"';
                    }
                }
            }
            $render = $this->renderer->render('@Systeme/errorTradEnv', [
                'menuActive' => 'Systeme',
    
                'fieldNoTrad' => $fieldTrad
            ]);
        }
        if ($file) {
            fclose($file);
        }

        return $render;
    }


    /**
     * Summary of extractionTraductionAction
     * @return string
     */
    public function extractionTraductionAction()
    {
        return $this->renderer->render('@Systeme/extractionTexte', [
            'menuActive' => 'Systeme',
        ]);
    }


    /**
     * @return Response
     */
    public function ajaxExtractionTraductionAction()
    {
        $path = "./../src";
        $scandir = scandir($path);

        $version = $this->contenaire->get('version');
        $version = substr($version, 0, 7);

        $fileName = 'extraction_libelle_global_'.date('Ymd').'_'.rand().'.txt';
        $pathFile = (new ParseBase1())->getRep()->tmp.$fileName;

        $tradExtract = new ExtractionTrad($version, $pathFile);

        // on delete l'ancien fichier
        $myfile = fopen($pathFile, "w");
        $tradExtract->exploreFolder($myfile, $path, $scandir);
        
        //on rajoute l'extraction des textes OXA.LINK au fichier
        //!! ATTENTION IL FAUT BIEN AVOIR LE OXALINK A JOURS SUR LA MEME RACINE
        $path = "../../oxalink/src";
        $scandir = scandir($path);
        $tradExtract->exploreFolder($myfile, $path, $scandir);

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

        return new Response(200, [], (string)json_encode([
            'STATUT'    => 'O',
            'file'      => $fileDL,
        ]));
    }
}
