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

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

class ImportDocumentController extends AbstractController
{


    public function imageFactureAction(
        string $fileName = '',
        int $size = 0,
        string $sourceFile = ''
    ):Response {
        $file       = $this->request->getUploadedFiles();
        $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,
        ]));
    }
}
