<?php
// download_document.php - Dokument herunterladen
require_once 'db.php';
require_once 'helpers.php';
requireLogin();

define('DOCUMENTS_DIR', __DIR__ . '/documents/');

$doc_id = filter_var($_GET['id'] ?? 0, FILTER_VALIDATE_INT);

if (!$doc_id) {
    die('Ungültige ID');
}

try {
    $doc = $db->selectOne("SELECT * FROM dokumente WHERE id = ?", [$doc_id]);
    
    if (!$doc) {
        die('Dokument nicht gefunden');
    }
    
    $filepath = DOCUMENTS_DIR . $doc['dateiname'];
    
    if (!file_exists($filepath)) {
        die('Datei nicht gefunden');
    }
    
    // Prüfe ob Ansicht oder Download
    $view = isset($_GET['view']) && $_GET['view'] == 1;
    
    Security::logSecurityEvent($view ? 'document_viewed' : 'document_downloaded', [
        'doc_id' => $doc_id,
        'filename' => $doc['original_name']
    ]);
    
    // Header setzen
    header('Content-Type: ' . $doc['dateityp']);
    
    if ($view) {
        // Ansicht im Browser (inline)
        header('Content-Disposition: inline; filename="' . $doc['original_name'] . '"');
    } else {
        // Download
        header('Content-Disposition: attachment; filename="' . $doc['original_name'] . '"');
    }
    
    header('Content-Length: ' . filesize($filepath));
    header('Pragma: no-cache');
    header('Expires: 0');
    
    readfile($filepath);
    exit;
    
} catch (PDOException $e) {
    Security::logSecurityEvent('document_download_error', [
        'doc_id' => $doc_id,
        'error' => $e->getMessage()
    ]);
    die('Fehler beim Laden');
}
?>
