<?php
declare(strict_types=1);

require_once __DIR__ . '/admin_bootstrap.php';

$pdo = admin_get_pdo();
admin_require_auth($pdo);

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    http_response_code(400);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Nieprawidłowe ID';
    exit;
}

$inline = isset($_GET['inline']) ? (int)$_GET['inline'] : 0;

try {
    $stmt = $pdo->prepare('SELECT file_name, file_mime, file_size, file_data FROM admin_chat_messages WHERE id = :id LIMIT 1');
    $stmt->execute([':id' => $id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row || empty($row['file_data'])) {
        http_response_code(404);
        header('Content-Type: text/plain; charset=utf-8');
        echo 'Brak pliku';
        exit;
    }

    $name = (string)($row['file_name'] ?? 'plik');
    $mime = (string)($row['file_mime'] ?? 'application/octet-stream');

    header('Content-Type: ' . $mime);
    $dispType = $inline ? 'inline' : 'attachment';
    header('Content-Disposition: ' . $dispType . '; filename="' . str_replace('"', '', $name) . '"');
    if (!empty($row['file_size'])) {
        header('Content-Length: ' . (string)$row['file_size']);
    }

    echo $row['file_data'];
    exit;
} catch (Throwable $e) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Błąd pobierania pliku';
    exit;
}
