<?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 dh.*, p.nomor_perkara FROM dokumen_history dh LEFT JOIN peminjaman p ON dh.peminjaman_id = p.id WHERE dh.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));
$nomorPerkara = preg_replace('/[^a-zA-Z0-9]/', '_', $row['nomor_perkara']);
$fileName = 'dokumen_' . $nomorPerkara . '_' . date('Ymd_His', strtotime($row['uploaded_at'])) . '.' . $fileExtension;

// Set appropriate headers for download
if ($fileExtension === 'pdf') {
    header('Content-Type: application/pdf');
} elseif (in_array($fileExtension, ['jpg', 'jpeg'])) {
    header('Content-Type: image/jpeg');
} elseif ($fileExtension === 'png') {
    header('Content-Type: image/png');
}

header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
exit;
