<?php

namespace Modules\Additional\Specifique\Client92\Modules\Controller;

use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Fichier\Fichier;
use Helpers\Trad\Trad;
use Helpers\Validator\Validator;
use Modules\Additional\Specifique\Client92\Modules\Repository\ImportBudget;
use Skeleton\Controller\Controller;
use Helpers\Parametres\Constante;

class ImportBudgetController extends Controller
{
    public function importAction()
    {
        $trad = $this->getTranslationService();

        $listeOption = [
            ''  => $trad->t("choisissez votre mode d'import"),
            '1' => $trad->t('Import ou Remplacement'),
            '2' => $trad->t('Mise à jour')
        ];

        Ariane::generate(0, $trad->t('Import budgetaire'));

        return $this->renderer->render('@Specifique92/Modules/views/Budget/import', [
            'menuActive'        => 'Specifique',
            'menuLeft'          => 'importBudget',
            'listeOption'       => $listeOption,
        ]);
    }

    public function ajaxImportAction()
    {
        $post = $this->request->getParsedBody();

        $trad = $this->getTranslationService();
        $importBudget = new ImportBudget($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();
        $validator->isFalse($post['OPTION'], Trad::strBuild($trad->t('Le champ @1@ ne peut pas être vide.'), 'option'));
        $validator->zoom('Societe', $post['SOCIETE'], $trad->t('Société'), $this->pdo, false);
        $validator->zoom('Periodes', $post['PERIODE'], $trad->t('Période'), $this->pdo, false);
        $validator->fileCheck($trad->t('Fichier d\'import'), $file_name??'', ['xsl', 'xlsx', 'csv'], '', $fileSize);

        $formatArray = [
            0 => 'CENTRE_COUT', // SI
            1 => 'ORDRE_INTERNE', // CDC
            2 => 'DOMANE_ACTIVITE', // SCA
            3 => 'PAYS_LIVRE',
            4 => 'GAMME',
            5 => 'MNT_BUDGET',
            6 => 'RESPONSABLE'
        ];

        if ($validator->isValid()) {
            if ($post['OPTION'] == '1') {
                $importBudget->deleteBudgetBySocPeriode($post['SOCIETE'], $post['PERIODE']);
            }

            $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]] = trim($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_STE'          => $post['SOCIETE'],
                    'CODE_PER'          => $post['PERIODE'],

                    'CENTRE_COUT'       => $ligne['CENTRE_COUT'],
                    'ORDRE_INTERNE'     => $ligne['ORDRE_INTERNE'],
                    'DOMANE_ACTIVITE'   => $ligne['DOMANE_ACTIVITE'],
                    'PAYS_LIVRE'        => $ligne['PAYS_LIVRE'],
                    'GAMME'             => $ligne['GAMME'],
                    'MNT_BUDGET'        => $ligne['MNT_BUDGET'],
                    'RESPONSABLE'       => $ligne['RESPONSABLE'],
                ];
                
                $validatorRow = $this->createValidator();
                $validatorRow->zoom('Sectimpu', $ligne['CENTRE_COUT'], $trad->t('Section d\'imputation'), $this->pdo, false, ['filter_egal_CODE_STE' => $post['SOCIETE']]);
                $arrayError['CENTRE_COUT'] = str_replace('<br />', '', $validatorRow->getError());
                $erreurLigne .= $validatorRow->getError();

                $validatorRow = $this->createValidator();
                $validatorRow->zoom('Codecomp', $ligne['ORDRE_INTERNE'], $trad->t('Code complémentaire'), $this->pdo, false, ['filter_egal_CODE_STE' => $post['SOCIETE']]);
                $arrayError['ORDRE_INTERNE'] = str_replace('<br />', '', $validatorRow->getError());
                $erreurLigne .= $validatorRow->getError();

                $validatorRow = $this->createValidator();
                $validatorRow->zoom('Sscptana', $ligne['DOMANE_ACTIVITE'], $trad->t('Sous-compte d\'analyse'), $this->pdo, false, ['filter_egal_CODE_STE' => $post['SOCIETE']]);
                $arrayError['DOMANE_ACTIVITE'] = str_replace('<br />', '', $validatorRow->getError());
                $erreurLigne .= $validatorRow->getError();

                $validatorRow = $this->createValidator();
                $validatorRow->zoom('Pays', $ligne['PAYS_LIVRE'], $trad->t('Pays livré'), $this->pdo, false);
                $arrayError['PAYS_LIVRE'] = str_replace('<br />', '', $validatorRow->getError());
                $erreurLigne .= $validatorRow->getError();
                
                $ligne['GAMME'] = $ligne['GAMME']??'';
                $validatorRow = $this->createValidator();
                $validatorRow->validatorTSDON($trad->t('Gamme'), $ligne['GAMME'], 'GAMME', $this->pdo, false, $post['SOCIETE']);
                $arrayError['GAMME'] = str_replace('<br />', '', $validatorRow->getError());
                $erreurLigne .= $validatorRow->getError();

                $validatorRow = $this->createValidator();
                $validatorRow->isFloat($trad->t('Montant consommé'), $ligne['MNT_BUDGET'], Constante::formatMontant);
                $arrayError['MNT_BUDGET'] = str_replace('<br />', '', $validatorRow->getError());
                $erreurLigne .= $validatorRow->getError();

                $validatorRow = $this->createValidator();
                $validatorRow->zoom('Hastutil', $ligne['RESPONSABLE'], $trad->t('Responsable'), $this->pdo, false);
                $arrayError['RESPONSABLE'] = 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';
                    
                    if ($importBudget->checkLigneBudget($arrayFinal[$i]['valueInsert'])) {
                        $importBudget->updateLigneBudget($arrayFinal[$i]['valueInsert']);
                    } else {
                        $importBudget->insertLigneBudget($arrayFinal[$i]['valueInsert']);
                    }
                }
                
                $i++;
            }

            return new Response(443, [

            ], (string) \json_encode([
                'statut' => 'O',
                'path' => $this->router->generateUri('Specifique92.ImportBudget.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()
    {
        $post = $this->request->getParsedBody(true);
        
        $arrayFinal = unserialize($post['retour'], ["allowed_classes" => false]);
        
        $trad = $this->getTranslationService();

        Ariane::generate(1, $trad->t('Résultat de l\'import'));

        return $this->renderer->render('@Specifique92/Modules/views/Budget/recapAnomalie', [
            'menuActive'        => 'Specifique',
            'menuLeft'          => 'importBudget',
            'arrayFinal'        => $arrayFinal,
            'post'              => $post,
        ]);
    }
}
