<?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 all documents for this peminjaman
    $stmt = $db->prepare("
        SELECT 
            id,
            dokumen_path,
            dokumen_keterangan,
            uploaded_by,
            uploaded_at
        FROM dokumen_history 
        WHERE peminjaman_id = ? 
        ORDER BY uploaded_at DESC
    ");
    $stmt->execute([$id]);
    $documents = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format data
    $formattedDocs = [];
    foreach ($documents as $doc) {
        $uploadDate = new DateTime($doc['uploaded_at']);
        $fileExtension = strtolower(pathinfo($doc['dokumen_path'], PATHINFO_EXTENSION));
        
        $formattedDocs[] = [
            'id' => $doc['id'],
            'file_path' => $doc['dokumen_path'],
            'file_extension' => $fileExtension,
            'keterangan' => $doc['dokumen_keterangan'],
            'uploaded_by' => $doc['uploaded_by'],
            'uploaded_at' => $doc['uploaded_at'],
            'uploaded_at_formatted' => $uploadDate->format('d M Y, H:i')
        ];
    }
    
    echo json_encode([
        'success' => true,
        'documents' => $formattedDocs,
        'count' => count($formattedDocs)
    ]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
