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

$peminjaman_id = intval($_GET['peminjaman_id'] ?? 0);
$doc_index = intval($_GET['index'] ?? 0);

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

$stmt = $db->prepare("SELECT dokumen_history_json, nomor_perkara FROM peminjaman WHERE id = ?");
$stmt->execute([$peminjaman_id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

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

$historyJson = $row['dokumen_history_json'] ?? null;
$documents = $historyJson ? json_decode($historyJson, true) : [];

if (!isset($documents[$doc_index])) {
    die('Dokumen tidak ditemukan');
}

$doc = $documents[$doc_index];
$filePath = $doc['path'];

if (!file_exists($filePath)) {
    die('File dokumen tidak ditemukan');
}

$fileExtension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
$nomorPerkara = preg_replace('/[^a-zA-Z0-9]/', '_', $row['nomor_perkara']);
$fileName = 'dokumen_' . $nomorPerkara . '_' . ($doc_index + 1) . '.' . $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;
