<?php

namespace Modules\Consultation\Controller;

use GuzzleHttp\Psr7\Response;
use Helpers\Ariane\Ariane;
use Helpers\Ariane\ArianeSub;
use Helpers\Fichier\Fichier;
use Helpers\Trad\ITrad;
use Helpers\Trad\Trad;
use Modules\Consultation\Repository\ImportInfo;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Skeleton\Controller\Controller;
use Helpers\Session\Enums\MenuTopEnum;
use Helpers\Session\Session;

class ImportContributeurController extends Controller
{
    /**
     * ImportindexAction
     *
     * @return string
     */
    public function contributorsImportIndexAction(): string
    {
        $idAO = $this->request->getAttribute('idAO');

        return $this->renderer->render(
            '@Consultation/Import/Contributors/import',
            [
                'idAO'              => $idAO,
                'pathBack'          => Ariane::getBackPath(),
            ]
        );
    }

    /**
     * contributorsImportAction
     *
     * @return  string|Response
     */
    public function contributorsImportAction()
    {
        $idAO = $this->request->getAttribute('idAO');
        $trad = $this->getTranslationService();
        $file = $this->request->getUploadedFiles();

        return $this->_processImport($idAO, $trad, $file);
    }

    public function contributorsImportSummaryAction(): string
    {
        $post = $this->request->getParsedBody();
        $trad = $this->getTranslationService();
        $idAO = $this->request->getAttribute('id');

        $data = $this->_processDataSummary($post, $trad, $idAO);

        return $this->renderer->render('@Evaluation/Campaign/detail', [
            'menuActive' => 'Consultations',
            'menuLeft' => 'ratings',
            'tab' => 'Import/Contributors/summary',
            'missingContributors' => $data['missingContributors'],
            'alreadyRegisteredContributors' => $data['alreadyRegisteredContributors'],
            'message' => $data['message'],
            'id' => $idAO,
            'campaign' => $data['campaign'],
        ]);
    }

    /**
     * _processDataSummary
     *
     * @param  array<mixed> $post
     * @param  ITrad $trad
     * @param  int $idAO
     * @return array<mixed>
     */
    private function _processDataSummary(array $post, ITrad $trad, int $idAO): array
    {
        $alreadyRegisteredRaters = $post['alreadyRegisteredRaters'] ?? [];
        $missingRaters = $post['missingRaters'] ?? [];
        $missingGroups = $post['missingGroups'] ?? [];
        $missingSuppliers = $post['missingSuppliers'] ?? [];
        $totalImportedRaters = $post['totalImportedRaters'];

        if ($totalImportedRaters > 0) {
            $message = Trad::strBuild($trad->t('Contributeurs importés depuis le fichier : @1@'), $totalImportedRaters);
        } else {
            $message = $trad->t('Aucun contributeur n\'a été importé.');
        }

        ArianeSub::generate(1, 0, $trad->t('Récapitulatif import'), $this->router->generateUri('Evaluation.ImportEvaluateur.raterImportSummary', ['id' => $idAO]), 1);

        return [
            'missingRaters' => $missingRaters,
            'missingGroups' => $missingGroups,
            'missingSuppliers' => $missingSuppliers,
            'alreadyRegisteredRaters' => $alreadyRegisteredRaters,
            'message' => $message,
            'id' => $idAO,
        ];
    }

    /**
     * _processImport
     *
     * @param  string $idAO
     * @param  ITrad $trad
     * @param  array<mixed> $file
     * @return string
     */
    private function _processImport(string $idAO, ITrad $trad, array $file)
    {
        if ($file) {
            $filename = $file['importFile']->getClientFilename();
            $fileSize = $file['importFile']->getSize();
        } else {
            $filename = null;
            $fileSize = 0;
        }

        $validator = $this->createValidator();
        $validator->fileCheck($trad->t('Fichier d\'import'), $filename ?? '', ['xls', 'xlsx', 'csv'], '', $fileSize);

        if ($validator->isValid()) {
            // on enregistre le fichier d'import dans les fichiers temporaires
            $newPath = Fichier::UploadDocAtt($filename);
            $file['importFile']->moveTo($newPath["racine"] . $newPath["new_name"]);
            $newName = $newPath["racine"] . $newPath["new_name"];

            $arrayImport = $this->_getArrayImport($newName);

            // on vérifie les contributeurs reçus et on retourne le compte de contributeurs OK, la liste des contributeurs qui n'existent pas et la liste des contributeurs qui étaient déjà enregistrés dans la campagne
            $import = (new ImportInfo($this->pdo, $this->pdoStorage))->importContributors($idAO, $arrayImport);
            $missingContributors = $import['missingContributors'] ?? [];
            $alreadyRegisteredContributors = $import['alreadyRegisteredContributors'] ?? [];
            $totalImportedContributors = $import['count'] ?? [];

            if ($totalImportedContributors > 0) {
                $message = Trad::strBuild($trad->t('Contributeurs importés depuis le fichier : @1@'), $totalImportedContributors);
            } else {
                $message = $trad->t('Aucun contributeur n\'a été importé.');
            }
        } else {
            $message = $validator->getError();
        }

        return $this->renderer->render(
            '@Consultation/Import/Contributors/summary',
            [
                'idAO' => $idAO,
                'valid' => $validator->isValid(),
                'pathBack' => Ariane::getBackPath(),
                'message' => $message,
                'missingContributors' => $missingContributors ?? [],
                'alreadyRegisteredContributors' => $alreadyRegisteredContributors ?? [],
                'totalImportedContributors' => $totalImportedContributors ?? 0,
            ]
        );
    }
    
    /**
     * _getArrayImport
     *
     * @param  string $fileName
     * @return array<mixed>
     */
    private function _getArrayImport(string $fileName): array
    {
        // on récupère les valeurs des colonnes qui nous intéressent (ici la première uniquement)
        $spreadsheet = IOFactory::load($fileName);
        $sheet = $spreadsheet->getSheet(0);
        $totalRows = $sheet->getHighestRow();
        
        $arrayImport = [];
        foreach ($sheet->getRowIterator(1, $totalRows) as $row) {
            foreach ($row->getCellIterator('A', 'A') as $cell) {
                $value = $cell->getCalculatedValue();
                $arrayImport[] = $value;
            }
        }

        return $arrayImport;
    }
}
