<?php
namespace Modules\Consultation\Controller;

use Helpers\Fichier\Fichier;
use Skeleton\Controller\Controller;
use GuzzleHttp\Psr7\Response;
use Modules\Consultation\Service\ImportExcelService;

class ImportExcelController extends Controller
{
    public function popupImportAction() :string
    {
        $idAO = $this->request->getAttribute('idAO');
        return $this->renderer->render('@Consultation/ImportExcel/popupImport', [
            'idAO' => $idAO,
        ]);
    }

    public function importAction() :Response
    {
        $idAO = $this->request->getAttribute('idAO');
        $post = $this->request->getParsedBody();

        $validator = $this->createValidator();

        $file = $this->request->getUploadedFiles();

        if ($file) {
            $file_name = $file['importimport']->getClientFilename();
            $fileSize = $file['importimport']->getSize();
        } else {
            $file_name = null;
            $fileSize = 0;
        }
        $validator->fileCheck("Excel", $file_name??'', [], '', $fileSize);

        if (! $validator->isValid()) {
            return new Response(400, [], $validator->getError());
        }
        
        $newPath = Fichier::UploadDocAtt($file_name);
        $filePath = $newPath["racine"].$newPath["new_name"];
        $file['importimport']->moveTo($filePath);

        $importService = new ImportExcelService(
            $this->pdo,
            $this->getTranslationService(),
            $this->renderer
        );

        return $importService->importConsultation(
            $idAO,
            $filePath,
            boolval($post['confirm'] ?? false),
            isset($post['bddart99_ignore']) ? boolval($post['bddart99_ignore']) : null
        );
    }
}
