<?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 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));

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

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