<?php
namespace Modules\API\APIInterne\Document\Controller;

use GuzzleHttp\Psr7\Response;
use Helpers\Fichier\Fichier;
use Helpers\Session\ParseBase1;
use Helpers\Trad\Trad;
use Modules\API\APIInterne\Magic\Controller\AbstractController;

class ImportDocumentController extends AbstractController
{
    public function uploadFileTmpAction() :Response
    {
        $file = $this->request->getUploadedFiles()['file'] ?? null;
        $trad = $this->getTranslationService();
        
        if (! $file) {
            return $this->createJsonResponse([
                'Error' => Trad::strBuild($trad->t('Le fichier @1@ est obligatoire.'), 'file')
            ], 400);
        }
        
        $validator = $this->createValidator();
        $validator->fileCheck(
            'file',
            $file->getClientFilename(),
            [],
            '',
            $file->getSize()
        );

        if (! $validator->isValid()) {
            return new Response(400, [], (string)json_encode([
                'Error' => $validator->getErrorJson(),
            ]));
        }

        //______________
        
        $dir = Fichier::getDirExport();
        $tmpPath =
            tempnam($dir, 'tmp')
            . '.' . (string) pathinfo($file->getClientFilename(), PATHINFO_EXTENSION);
        $file->moveTo($tmpPath);
        
        return $this->createJsonResponse([
            // Note we replace fic_pj with a placeholder currently interpreted by magic
            'Id' => str_replace(trim(Fichier::getDirPj(), '\\/'), '%fic_pj%', $tmpPath),
        ]);
    }

    public function imageFactureAction(
        string $fileName = '',
        int $size = 0,
        string $sourceFile = ''
    ) :Response {
        $post       = $this->request->getParsedBody(true);
        $file       = $this->request->getUploadedFiles();
        $idDocument = $post['numFact'];
        
        if ($file) {
            $fileName = uniqid().$file['imageFacture']->getClientFilename();
            $size = $file['imageFacture']->getSize();
            $sourceFile = (new ParseBase1())->getRep()->tmp.$fileName;
        }
        
        $validator = $this->createValidator();
        $validator->fileCheck("Image Facture", $fileName, ['pdf'], '', $size);

        if ($validator->isValid() && $size) {
                $file['imageFacture']->moveTo($sourceFile);
                $res = \Modules\Facture\WebService\PopupFacture::rattacherImage($idDocument, 'C', $fileName);
                $res = new \SimpleXMLElement($res->responseData);
                $statut = $res->Statut;
            if ($statut == 'O') {
                return new Response(200, [], (string)json_encode(['Statut' => '200', 'MsgErreur' => '']));
            } else {
                return new Response(415, [], (string)json_encode([
                    'Error' => $res->MsgErreur,
                ]));
            }
        }

        $messageErreur = $validator->getError();
        if (strpos($messageErreur, '<br />') === 0) {
            $messageErreur = substr($messageErreur, 6);
        }

        return new Response(415, [], (string)json_encode([
            'Error' => $messageErreur,
        ]));
    }
}
