<?php
session_start();
if (empty($_SESSION['admin_logged_in'])) {
    http_response_code(403);
    exit('Yetkisiz erişim');
}

require_once __DIR__ . '/db.php';

$id = (int)($_GET['id'] ?? 0);
if (!$id) { http_response_code(400); exit('Geçersiz ID'); }

$db   = getDB();
$stmt = $db->prepare("SELECT dekont_path FROM reservations WHERE id=:id");
$stmt->bindValue(':id', $id);
$row  = $stmt->execute()->fetchArray(SQLITE3_ASSOC);

if (!$row || empty($row['dekont_path'])) {
    http_response_code(404);
    exit('Dekont bulunamadı');
}

$file = __DIR__ . '/../' . $row['dekont_path'];
if (!file_exists($file)) {
    http_response_code(404);
    exit('Dosya bulunamadı: ' . $row['dekont_path']);
}

$ext  = strtolower(pathinfo($file, PATHINFO_EXTENSION));
$mimes = [
    'pdf'  => 'application/pdf',
    'png'  => 'image/png',
    'jpg'  => 'image/jpeg',
    'jpeg' => 'image/jpeg',
    'gif'  => 'image/gif',
    'webp' => 'image/webp',
];
$mime = $mimes[$ext] ?? 'application/octet-stream';

header('Content-Type: ' . $mime);
header('Content-Disposition: inline; filename="dekont_' . $id . '.' . $ext . '"');
header('Content-Length: ' . filesize($file));
readfile($file);
