<?php
session_start();
header('Content-Type: text/html; charset=utf-8');

include '../layouts/dbconn.php';

// Check authentication
if (!isset($_SESSION['user_id'])) {
    echo '<div class="alert alert-danger">Unauthorized access</div>';
    exit();
}

if (!isset($_POST['patient_id'])) {
    echo '<div class="alert alert-danger">Missing patient ID</div>';
    exit();
}

$patient_id = intval($_POST['patient_id']);

// Get documents for this patient
$query = "SELECT 
    md.*,
    u.full_name as uploaded_by_name,
    c.consultation_id,
    c.consultation_date
FROM medical_documents md
INNER JOIN users u ON md.uploaded_by = u.user_id
LEFT JOIN consultations c ON md.consultation_id = c.consultation_id
WHERE md.patient_id = ?
ORDER BY md.uploaded_at DESC";

$stmt = $conn->prepare($query);
$stmt->bind_param("i", $patient_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows == 0) {
    echo '<div class="alert alert-info">No documents found for this patient.</div>';
    exit();
}
?>

<div class="table-responsive">
    <table class="table table-hover align-middle">
        <thead class="table-light">
            <tr>
                <th>Document Name</th>
                <th>Type</th>
                <th>Category</th>
                <th>Upload Date</th>
                <th>Uploaded By</th>
                <th>Size</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php while ($document = $result->fetch_assoc()): ?>
            <tr>
                <td>
                    <i class="<?php 
                        $ext = strtolower(pathinfo($document['file_name'], PATHINFO_EXTENSION));
                        echo ($ext == 'pdf') ? 'ri-file-pdf-line text-danger' : 
                             (in_array($ext, ['jpg', 'jpeg', 'png', 'gif']) ? 'ri-image-line text-primary' : 
                             (in_array($ext, ['doc', 'docx']) ? 'ri-file-word-line text-info' : 'ri-file-line'));
                    ?> me-2"></i>
                    <strong><?php echo htmlspecialchars($document['document_title']); ?></strong>
                    <br>
                    <small class="text-muted"><?php echo htmlspecialchars($document['file_name']); ?></small>
                </td>
                <td>
                    <span class="badge bg-secondary"><?php echo htmlspecialchars($document['document_type']); ?></span>
                </td>
                <td>
                    <?php echo htmlspecialchars($document['category'] ?: 'General'); ?>
                </td>
                <td>
                    <?php echo date('M d, Y', strtotime($document['uploaded_at'])); ?>
                    <br>
                    <small class="text-muted"><?php echo date('h:i A', strtotime($document['uploaded_at'])); ?></small>
                </td>
                <td>
                    <?php echo htmlspecialchars($document['uploaded_by_name']); ?>
                </td>
                <td>
                    <?php 
                    $size_kb = $document['file_size'] / 1024;
                    if ($size_kb < 1024) {
                        echo number_format($size_kb, 2) . ' KB';
                    } else {
                        echo number_format($size_kb / 1024, 2) . ' MB';
                    }
                    ?>
                </td>
                <td>
                    <div class="btn-group btn-group-sm">
                        <a href="<?php echo htmlspecialchars($document['file_path']); ?>" 
                           class="btn btn-outline-primary" 
                           target="_blank" 
                           title="View Document">
                            <i class="ri-eye-line"></i>
                        </a>
                        <a href="<?php echo htmlspecialchars($document['file_path']); ?>" 
                           class="btn btn-outline-success" 
                           download 
                           title="Download">
                            <i class="ri-download-line"></i>
                        </a>
                        <?php if ($document['consultation_id']): ?>
                        <a href="view_consultation.php?id=<?php echo $document['consultation_id']; ?>" 
                           class="btn btn-outline-info" 
                           title="View Consultation">
                            <i class="ri-file-text-line"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                </td>
            </tr>
            <?php 
            // Show description if available
            if ($document['description']): 
            ?>
            <tr>
                <td colspan="7" class="bg-light">
                    <small><strong>Description:</strong> <?php echo nl2br(htmlspecialchars($document['description'])); ?></small>
                </td>
            </tr>
            <?php endif; ?>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>

<?php
$conn->close();
?>