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

header('Content-Type: application/json');

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

if ($id <= 0) {
    echo json_encode(['success' => false, 'message' => 'ID tidak valid']);
    exit;
}

try {
    // Get dokumen history from JSON field
    $stmt = $db->prepare("SELECT dokumen_history_json FROM peminjaman WHERE id = ?");
    $stmt->execute([$id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$row) {
        echo json_encode(['success' => false, 'message' => 'Data tidak ditemukan']);
        exit;
    }
    
    $historyJson = $row['dokumen_history_json'] ?? null;
    $documents = $historyJson ? json_decode($historyJson, true) : [];
    
    // Format data
    $formattedDocs = [];
    foreach ($documents as $index => $doc) {
        $uploadDate = new DateTime($doc['uploaded_at']);
        $fileExtension = strtolower(pathinfo($doc['path'], PATHINFO_EXTENSION));
        
        $formattedDocs[] = [
            'id' => $index, // Use array index as ID
            'file_path' => $doc['path'],
            'file_extension' => $fileExtension,
            'keterangan' => $doc['keterangan'] ?? '',
            'uploaded_by' => $doc['uploaded_by'] ?? 'Unknown',
            'uploaded_at' => $doc['uploaded_at'],
            'uploaded_at_formatted' => $uploadDate->format('d M Y, H:i')
        ];
    }
    
    // Reverse to show newest first
    $formattedDocs = array_reverse($formattedDocs);
    
    echo json_encode([
        'success' => true,
        'documents' => $formattedDocs,
        'count' => count($formattedDocs),
        'peminjaman_id' => $id
    ]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
