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

use Entity\Model\Paravrac;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\Utils;
use Helpers\Fichier\Fichier;
use Skeleton\Controller\Controller;
use Modules\API\APIInterne\Document\Repository\ChargeDocumentExterne;
use Helpers\Outil\Roles;
use Helpers\Session\ParseBase1;

class ChargeDocumentExterneController extends Controller
{
    use \Traits\Menu\Droit;

    /**
     * @return Response|string
     */
    public function chargeDocumentExterneAction()
    {
        $qbParavrac = (new Paravrac($this->pdo));
        $trad = $this->getTranslationService();
        

        if (empty($_SESSION['Session_Login'])) {
            $_SESSION['redirect'] = $_SERVER['REQUEST_URI'];
            
            if ($qbParavrac->getGeneric('CNX_SSO') != 'O') {
                return $this->redirect('Connexion.Connexion.connexion', ['redirect' => 'redirect']);
            }
            
            $typeSso = $qbParavrac->getGeneric('TYPE_SSO') ?? '';
            return $this->renderer->render('@APIInterneDocument/ChargeDocumentExterne/portail', [
                'typeSso' => $typeSso,
                'ssoActiv' => 1,
                'lienInterne' => $this->router->generateUri(
                    'Connexion.Connexion.connexion',
                    ['redirect' => 'redirect']
                ),
                'lienSSO' => ($typeSso == 'ADFS' ?
                    $this->router->generateUri('Connexion.Connexion.connexion', ['redirect' => 'mwSAML2']) :
                    $this->contenaire->get('urlOxaprocSso').'/index.php'
                ),
            ]);
        }
    
        // Gestion des extensions
        $idDocument = $this->request->getAttribute('idDoc');
        $type = $this->request->getAttribute('type');
        $extension = $this->request->getAttribute('extension');
        $tokenConstruct = $this->request->getAttribute('token');

    
        // gestion des droits
        $export = '';
        $facture = '';
        $idDocumentSQL = '';

        switch ($type) {
            case 'facture':
                // Gestion des extensions, ici on va rajouter les extensions qu'on utilisera pour le téléchargement
                $extensionListe = ['pdf', 'doc'];

                if (strtolower(hash('sha256', $extension.$idDocument)) != strtolower($tokenConstruct)) {
                    echo '   erreur de token';
                    @exit;
                }

                if ($extension == '') {
                    foreach ($extensionListe as $l) {
                        if (strpos($idDocument, $l) !== false) {
                            $extension = $l;
                        }
                    }
                }

                if (! (
                        $_SESSION['AcessFacture']
                        && Roles::droitsUtilisateur($this->pdo, 'HA_FA_VISU')
                        && Roles::droitsUtilisateur($this->pdo, 'U8zXaa77yt')
                    ) && ! $this->getAll()
                ) {
                    return $trad->t('Vous ne disposez pas des droits de visualisation de facture.');
                }
                
                $idDocumentSQL = str_replace('$', '\\', $idDocument);

                // TODO identify facture by its ID and not by its FIC_LAD
                $facture = new ChargeDocumentExterne($this->pdo);
                $facture = $facture->findFicLad($idDocumentSQL.'.'.$extension);
                if (empty($facture)) {
                    return new Response(404, [], 'File not found');
                }
                
                $a = explode('$', $facture['FIC_LAD']);

                return new Response(200, [
                    'Content-type' => 'application/pdf',
                    'Content-Disposition' => 'inline; filename="Image_Facture_' . str_replace('.pdf', '', end($a)).'.'.$extension . '"',
                    'Content-Transfer-Encoding' => 'binary',
                    'Accept-Ranges' => 'bytes',
                ], Utils::streamFor(fopen(
                    Fichier::filterTraversal(
                        (new ParseBase1())->getRep()->pj,
                        $facture['FIC_LAD']
                    ),
                    'r'
                )));
                
            case 'exportVolume':
                if (strtolower(hash('sha256', $extension.$idDocument)) != strtolower($tokenConstruct)
                    && strtolower(hash('sha256', $extension.$idDocument.$_SESSION["Session_Login"])) != strtolower($tokenConstruct)
                ) {
                    echo '   erreur de token';
                    @exit;
                }

                $export = str_replace('$', '\\', $idDocument);

                $filename = Fichier::getDirExport() . Fichier::filterFileName($export . '.'.$extension);
                
                return new Response(200, [
                    'Content-type' => 'application/x-download',
                    'Content-Disposition' => 'attachment; filename="'.$export.'.'.$extension.'"',
                    'Pragma' => 'no-cache',
                    'Cache-Control' => 'no-cache, must-revalidate',
                ], Utils::streamFor(fopen($filename, 'r')));

            default:
                return $this->redirect('Connexion.Connexion.connexion');
        }
    }
}
