<?php
namespace Modules\Parametrage\Facture\Controller;

use GuzzleHttp\Psr7\Response;
use Skeleton\Controller\Controller;
use Helpers\Ariane\Ariane;
use Helpers\Ariane\ArianeSub;
use Helpers\Fichier\Fichier;
use Helpers\Outil\Roles;
use Helpers\Trad\Trad;
use Helpers\Validator\Validator;
use Modules\Parametrage\Facture\Repository\ParametrageLAD;

class ParametrageLADFournImportController extends Controller
{
    /**
     * @var string $menuActive
     */
    public $menuActive = '';

    /**
     * @var string $menuLeft
     */
    public $menuLeft = '';

    /**
     * @var int $indexAriane
     */
    public $indexAriane = 0;
    
    public function init() : void
    {
        if (($_SESSION['ariane'][0]['path']??null) == $this->router->generateUri('Parametrage.Parametrage.index')) {
            $this->indexAriane = 1;
            $this->menuActive = 'Parametrage';
            $this->menuLeft = 'Parametrage';
        } else {
            $this->indexAriane = 0;
            $this->menuActive = 'Facture';
            $this->menuLeft = 'Parametrage';
        }
    }

    public function importAction() : string
    {
        $trad = $this->getTranslationService();

        Ariane::generate($this->indexAriane, $trad->t('Gestion des paramétrages LAD'), []);
        ArianeSub::init();
        ArianeSub::generate(0, 1, $trad->t('Paramétrage LAD'), $this->router->generateUri('Parametrage.ParametrageLAD.LAD'), 0);
        if ($_SESSION["Session_Login"]=='OXAUSER' || Roles::GetALL()) {
            ArianeSub::generate(0, 2, $trad->t('Signature'), $this->router->generateUri('Parametrage.ParametrageFlexi.signature'), 0);
        }
        ArianeSub::generate(0, 3, $trad->t('Paramétrage Fournisseur'), $this->router->generateUri('Parametrage.ParametrageLAD.fournisseur'), 0);
        ArianeSub::generate(0, 4, $trad->t('Import'), $this->router->generateUri('Parametrage.ParametrageLADFournImport.import'), 1);

        return $this->renderer->render('@ParamFac/ImportFournisseurArticle/import', [
            'menuActive'        => $this->menuActive,
            'menuLeft'          => $this->menuLeft,
            ]);
    }

    /**
     * @return Response|string
     */
    public function ajaxImportAction()
    {
        // @phpstan-ignore-next-line TODO MSA ini_set() attend un string en 2e argument, reçoit un int
        ini_set("display_errors", 1);

        $post = $this->request->getParsedBody();

        $trad = $this->getTranslationService();
        $parametrageRepository = new ParametrageLAD($this->pdo);
        

        $file = $this->request->getUploadedFiles();
            
        if ($file) {
            $file_name = $file['importfile']->getClientFilename();
            $fileSize = $file['importfile']->getSize();
        } else {
            $file_name = null;
            $fileSize = 0;
        }
        
        $validator = $this->createValidator();
        /** @phpstan-ignore-next-line */
        $validator->fileCheck($trad->t('Fichier d\'import'), $file_name??'', ['xsl', 'xlsx', 'csv'], '', $fileSize);

        $formatArray = [
            0 => 'CODE_FOURNISSEUR',
            1 => 'CODE_ARTICLE',
        ];

        if ($validator->isValid()) {
            $newPath = Fichier::UploadDocAtt($file_name);
            $file['importfile']->moveTo($newPath["racine"].$newPath["new_name"]);
            $newName = $newPath["racine"].$newPath["new_name"];
           
            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($newName);
            $feuilleReponse = $spreadsheet->getSheet(0);
            $nombreTotalRow = $feuilleReponse->getHighestRow();

            $arrayImport = [];

            $rowCount = 0;
            foreach ($feuilleReponse->getRowIterator(1, $nombreTotalRow) as $row) {
                $cellCount = 0;
                foreach ($row->getCellIterator() as $cell) {
                    $value = $cell->getCalculatedValue();
                    $arrayImport[$rowCount][$formatArray[$cellCount]] = $value;
                    $cellCount++;
                }
                $rowCount++;
            }

            $arrayFinal = [];
            $i = 0;

            $rowAdd = 0;
            $rowError = 0;
            
            foreach ($arrayImport as $ligne) {
                if (count(array_filter($ligne)) === 0) {
                    $nombreTotalRow--;
                    continue;
                }

                $arrayError = [];
                $erreurLigne = '';

                $arrayFinal[$i]['valueInsert'] = [
                    'CODE'                  => $ligne['CODE_FOURNISSEUR'],
                    'ARTICLE_INIT_FAC_LAD'  => $ligne['CODE_ARTICLE'],
                ];
                
                $validatorRow = $this->createValidator();
                $validatorRow->zoom('Fourniss', ($ligne['CODE_FOURNISSEUR']??''), $trad->t('Code fournisseur'), $this->pdo);
                $arrayError['MOTIF'] = str_replace('<br />', '', $validatorRow->getError());
                $erreurLigne .= $validatorRow->getError();

                $validatorRow = $this->createValidator();
                $validatorRow->zoom('Articles', ($ligne['CODE_ARTICLE']?? ''), $trad->t('Code article'), $this->pdo, true, ['filter_egal_GENRERIQUE' => 'T']);
                $arrayError['MOTIF'] .= str_replace('<br />', ' ', $validatorRow->getError());
                $erreurLigne .= $validatorRow->getError();
                
                if ($erreurLigne) {
                    $rowError++;
                    $arrayFinal[$i]['error'] = $arrayError;
                    $arrayFinal[$i]['statut'] = 'E';
                } else {
                    $rowAdd++;
                    $arrayFinal[$i]['statut'] = 'O';
                    
                    $parametrageRepository->updateFournisseurArticle($arrayFinal[$i]['valueInsert']);
                }
                
                $i++;
            }

            return new Response(443, [

            ], (string) \json_encode([
                'statut' => 'O',
                'path' => $this->router->generateUri('Parametrage.ParametrageLADFournImport.recapAnomalie'),
                'postGestion' => ['retour' => serialize($arrayFinal), 'totalRow' => $nombreTotalRow,'rowError' => $rowError,'rowAdd' => $rowAdd],
            ]));
        } else {
            return $this->renderer->render('@popup-erreur/ErreurCreation', [
                'ErreurValid' => $validator->getError(),
                'desactiveRow' => true,
            ]);
        }
    }

    public function recapAnomalieAction() : string
    {
        $post = $this->request->getParsedBody();
        
        $arrayFinal = unserialize($post['retour'], ["allowed_classes" => false]);
        
        $trad = $this->getTranslationService();

        Ariane::generate($this->indexAriane, $trad->t('Gestion des paramétrages LAD'), []);
        ArianeSub::generate(0, 1, $trad->t('Paramétrage LAD'), $this->router->generateUri('Parametrage.ParametrageLAD.LAD'), 0);
        ArianeSub::generate(0, 2, $trad->t('Paramétrage Fournisseur'), $this->router->generateUri('Parametrage.ParametrageLAD.fournisseur'), 0);
        ArianeSub::generate(0, 3, $trad->t('Import'), $this->router->generateUri('Parametrage.ParametrageLADFournImport.import'), 0);
        ArianeSub::generate(0, 4, $trad->t('Résultat de l\'import'), $this->router->generateUri('Parametrage.ParametrageLADFournImport.recapAnomalie'), 1);

        return $this->renderer->render('@ParamFac/ImportFournisseurArticle/recapAnomalie', [
            'menuActive'        => $this->menuActive,
            'menuLeft'          => $this->menuLeft,
            'arrayFinal'        => $arrayFinal,
            'post'              => $post,
        ]);
    }
}
