<?php
require 'db.php';
require 'auth.php';
require_login();

$id = intval($_GET['id'] ?? 0);

if ($id <= 0) {
    die('ID tidak valid');
}

$stmt = $db->prepare("SELECT * FROM dokumen_history WHERE id = ?");
$stmt->execute([$id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$row) {
    die('Data tidak ditemukan');
}

if (empty($row['dokumen_path']) || !file_exists($row['dokumen_path'])) {
    die('File dokumen tidak ditemukan');
}

$filePath = $row['dokumen_path'];
$fileExtension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));

// Set appropriate headers based on file type
if ($fileExtension === 'pdf') {
    header('Content-Type: application/pdf');
    header('Content-Disposition: inline; filename="dokumen_' . $id . '.pdf"');
} elseif (in_array($fileExtension, ['jpg', 'jpeg'])) {
    header('Content-Type: image/jpeg');
    header('Content-Disposition: inline; filename="dokumen_' . $id . '.jpg"');
} elseif ($fileExtension === 'png') {
    header('Content-Type: image/png');
    header('Content-Disposition: inline; filename="dokumen_' . $id . '.png"');
}

header('Content-Length: ' . filesize($filePath));
readfile($filePath);
exit;
