<?php
require_once __DIR__ . '/../../vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/..' . '/../');
$dotenv->safeLoad();

use App\Auth;
use App\Database;

Auth::init();
Auth::requireRole(['admin','staff']);
$pdo = Database::getConnection();

$doc_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($doc_id <= 0) {
  http_response_code(400);
  die('Geçersiz belge ID');
}

// Belge bilgisi
$st = $pdo->prepare('SELECT d.*, p.first_name, p.last_name FROM patient_documents d JOIN patients p ON p.id = d.patient_id WHERE d.id = :id');
$st->execute([':id' => $doc_id]);
$doc = $st->fetch();

if (!$doc) {
  http_response_code(404);
  die('Belge bulunamadı');
}

$filePath = __DIR__ . '/../uploads/documents/' . $doc['file_name'];

if (!file_exists($filePath)) {
  http_response_code(404);
  die('Dosya bulunamadı');
}

// Güvenli dosya indirme
$fileSize = filesize($filePath);
$mimeType = $doc['file_type'] ?: 'application/octet-stream';

// Tarayıcıda açılabilir türler için inline, diğerleri için attachment
$disposition = 'attachment';
if (in_array($mimeType, ['application/pdf', 'image/jpeg', 'image/png', 'image/jpg'])) {
  $disposition = 'inline';
}

header('Content-Type: ' . $mimeType);
header('Content-Disposition: ' . $disposition . '; filename="' . $doc['original_name'] . '"');
header('Content-Length: ' . $fileSize);
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
header('X-Content-Type-Options: nosniff');

readfile($filePath);
exit;
