<?php

namespace EIS\Component\EIS\Site\Controller;

\defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\MVC\Controller\BaseController;
use Joomla\CMS\Router\Route;
use Joomla\Database\DatabaseDriver;

class DownloadController extends BaseController
{
    public function download()
    {
        $app = \Joomla\CMS\Factory::getApplication();
        $input = $app->input;

        $id = (int) $input->get('id');
        if ($id <= 0) {
            throw new \RuntimeException('Ungültige ID.');
        }

        /** @var \Joomla\Database\DatabaseDriver $db */
        $db = \Joomla\CMS\Factory::getDbo();
        $row = $db->setQuery(
            $db->getQuery(true)
                ->select($db->quoteName(['path', 'name']))
                ->from($db->quoteName('#__eis_documents'))
                ->where($db->quoteName('id') . ' = ' . (int) $id)
                ->where($db->quoteName('is_folder') . ' = 0')
        )->loadAssoc();

        if (!$row) {
            throw new \RuntimeException('Datei nicht gefunden.');
        }

        $filePath = (string) $row['path'];
        $fileName = (string) $row['name'];

        // ------------- Sicherheit: Pfad muss unterhalb von /var/www/pdf liegen
        $baseDir  = '/var/www/pdf'; // <-- DEIN Basisordner (ohne trailing slash!)
        $realFile = realpath($filePath);
        $realBase = realpath($baseDir);

        if (!$realFile || !$realBase || strpos($realFile, $realBase) !== 0 || !is_file($realFile)) {
            throw new \RuntimeException('Ungültiger Pfad.');
        }

        // ------------- Relativpfad (Dateisystem) -> interner Nginx-URI
        // Beispiel: /var/www/pdf/foo/bar.pdf -> /protected-eis/foo/bar.pdf
        $relFs = ltrim(substr($realFile, strlen($realBase)), DIRECTORY_SEPARATOR);
        // URI-sicher kodieren (jedes Segment rawurlencode, Slashes erhalten)
        $segments = $relFs === '' ? [] : explode('/', str_replace('\\', '/', $relFs));
        $encodedRel = implode('/', array_map('rawurlencode', $segments));
        $internalPrefix = '/protected-eis/';  // <-- muss zu Nginx 'location' passen
        $internalUri = $internalPrefix . $encodedRel;

        // ------------- Saubere Header, keine PHP-Ausgabe
        while (ob_get_level()) {
            @ob_end_clean();
        }
        @ini_set('zlib.output_compression', 'Off');

        // Content-Disposition inkl. UTF-8 kompatibel (RFC 5987)
        $dispFilename = basename($fileName);
        $cd = 'inline; filename="' . \Joomla\CMS\Filter\OutputFilter::stringURLSafe($dispFilename) . '"';
        $cd .= "; filename*=UTF-8''" . rawurlencode($dispFilename);

        header('Content-Type: application/pdf');
        header('Content-Disposition: ' . $cd);
        header('X-Accel-Redirect: ' . $internalUri);
        header('X-Content-Type-Options: nosniff');
        // Range/Content-Length/Caching erledigt Nginx automatisch perfekt
        exit;
    }
}
