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

use Entity\Model\FactEnt;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Utils;
use Helpers\Fichier\Fichier;
use Helpers\Session\ParseBase1;
use Modules\API\APIInterne\Magic\Controller\AbstractController;

class ChargeDocumentAPIController extends AbstractController
{
    /**
     * chargeDocumentAction
     *
     */
    public function chargeDocumentAction(): Response
    {
        $idDocument = $this->request->getAttribute('idDoc');
        $type = $this->request->getAttribute('type');

        switch ($type) {
            case 'facture':
                $FacEnt = new FactEnt($this->pdo);
                $facture = $FacEnt->find($idDocument);
                if (!isset($facture["FIC_LAD"]) || $facture["FIC_LAD"] === "") {
                    return new Response(404, [], json_encode(['Error' => 'File not found']) ?: null);
                }
                
                return new Response(200, [
                    'Content-type' => 'application/pdf',
                    'Content-Disposition' => 'attachment; filename="' . uniqid("Facture_" . ($facture['NUM_FACT'] ? $facture['NUM_FACT'] . '_' : '')) .'.pdf"',
                    'Content-Transfer-Encoding' => 'binary',
                    'Access-Control-Expose-Headers' => 'Content-Disposition',
                    'Accept-Ranges' => 'bytes',
                ], Utils::streamFor(fopen(
                    Fichier::filterTraversal(
                        (new ParseBase1())->getRep()->pj,
                        $facture['FIC_LAD']
                    ),
                    'r'
                )));
            default:
        }
        return new Response(404, [], json_encode(['Error' => 'Not found']) ?: null);
    }
}
