<?php
/**
 * (c) ININOUT & PYXIS. All Rights Reserved.
 * Wszelkie modyfikacje tego pliku wymagaja zgloszenia oraz zgody autorow.
 * Any modifications to this file require notification and consent of the authors.
 */
/**
 * i-BOK 5 - Bezpieczne pobieranie plików PDF
 *
 * Źródło 1: BLOB z bazy danych (MagazynBlob2, Fv, Fvk) — auto-detekcja kolumn
 * Źródło 2: Plik z dysku (data/{client_id}/{filename}.pdf) — fallback
 */

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/inc/session.php';
require_once __DIR__ . '/inc/security.php';
require_once __DIR__ . '/inc/db_config.php';
require_once __DIR__ . '/inc/auth.php';
require_once __DIR__ . '/inc/functions.php';

// Sprawdź autoryzację (klient lub admin)
$is_client = is_client_logged_in();
$is_admin = is_admin_logged_in();

if (!$is_client && !$is_admin) {
    header('HTTP/1.0 403 Forbidden');
    exit('Access denied');
}

// Parametry
$client_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$filename = $_GET['file'] ?? '';

// Walidacja
if (empty($client_id) || empty($filename)) {
    header('HTTP/1.0 400 Bad Request');
    exit('Missing parameters');
}

// Klient może pobierać tylko swoje pliki
if ($is_client && (string)$client_id !== (string)$_SESSION['client_id']) {
    header('HTTP/1.0 403 Forbidden');
    exit('Access denied');
}

$safe_filename = basename($filename);

// --- Źródło 1: BLOB z bazy danych ---
if (function_exists('db_get_pdo')) {
    require_once __DIR__ . '/inc/db_mysql.php';

    $blob_data = db_get_document_pdf($safe_filename, $client_id, $is_admin);

    if ($blob_data !== null && strlen($blob_data) > 0) {
        $dl_name = $safe_filename;
        if (strtolower(pathinfo($dl_name, PATHINFO_EXTENSION)) !== 'pdf') {
            $dl_name .= '.pdf';
        }

        header('Content-Type: application/pdf');
        header('Content-Disposition: inline; filename="' . $dl_name . '"');
        header('Content-Length: ' . strlen($blob_data));
        header('Cache-Control: private, max-age=3600');
        header('X-Content-Type-Options: nosniff');

        echo $blob_data;
        exit;
    }
}

// --- Źródło 2: Plik z dysku (fallback) ---
$client_dir = IBOK_DATA_DIR . '/' . $client_id;
$filepath = $client_dir . '/' . $safe_filename;

if (!file_exists($filepath)) {
    header('HTTP/1.0 404 Not Found');
    exit('File not found');
}

$real_path = realpath($filepath);
$real_client_dir = realpath($client_dir);

if ($real_path === false || $real_client_dir === false) {
    header('HTTP/1.0 404 Not Found');
    exit('File not found');
}

// Upewnij się, że plik jest w katalogu klienta
if (strpos($real_path, $real_client_dir) !== 0) {
    header('HTTP/1.0 403 Forbidden');
    exit('Access denied');
}

// Sprawdź rozszerzenie
$ext = strtolower(pathinfo($safe_filename, PATHINFO_EXTENSION));
if ($ext !== 'pdf') {
    header('HTTP/1.0 403 Forbidden');
    exit('Only PDF files allowed');
}

// Wyślij plik
$filesize = filesize($filepath);

header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' . $safe_filename . '"');
header('Content-Length: ' . $filesize);
header('Cache-Control: private, max-age=3600');
header('X-Content-Type-Options: nosniff');

readfile($filepath);
exit;
