<?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 procedures for this patient
$query = "SELECT 
    mp.*,
    ept.procedure_name,
    ept.category,
    ept.description as procedure_description,
    ept.estimated_duration,
    ept.base_cost,
    c.consultation_id,
    c.consultation_date,
    perf_user.full_name as performed_by_name,
    doc_user.full_name as scheduled_by_name
FROM medical_procedures mp
INNER JOIN ent_procedure_types ept ON mp.procedure_type_id = ept.procedure_type_id
LEFT JOIN consultations c ON mp.consultation_id = c.consultation_id
LEFT JOIN users perf_user ON mp.performed_by = perf_user.user_id
LEFT JOIN users doc_user ON mp.scheduled_by = doc_user.user_id
WHERE mp.patient_id = ?
ORDER BY mp.scheduled_date 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 procedures found for this patient.</div>';
    exit();
}
?>

<div class="table-responsive">
    <table class="table table-hover align-middle">
        <thead class="table-light">
            <tr>
                <th>Date</th>
                <th>Procedure</th>
                <th>Category</th>
                <th>Performed By</th>
                <th>Status</th>
                <th>Duration</th>
                <th>Cost</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php while ($procedure = $result->fetch_assoc()): ?>
            <tr>
                <td>
                    <?php echo date('M d, Y', strtotime($procedure['scheduled_date'])); ?>
                    <br>
                    <small class="text-muted"><?php echo date('h:i A', strtotime($procedure['scheduled_date'])); ?></small>
                </td>
                <td>
                    <strong><?php echo htmlspecialchars($procedure['procedure_name']); ?></strong>
                    <?php if ($procedure['procedure_notes']): ?>
                    <br><small class="text-muted"><?php echo htmlspecialchars(substr($procedure['procedure_notes'], 0, 50)) . '...'; ?></small>
                    <?php endif; ?>
                </td>
                <td>
                    <span class="badge bg-info"><?php echo htmlspecialchars($procedure['category']); ?></span>
                </td>
                <td>
                    <?php if ($procedure['performed_by_name']): ?>
                        <?php echo htmlspecialchars($procedure['performed_by_name']); ?>
                    <?php else: ?>
                        <span class="text-muted">Not assigned</span>
                    <?php endif; ?>
                </td>
                <td>
                    <?php
                    $status_badge = [
                        'SCHEDULED' => 'secondary',
                        'IN_PROGRESS' => 'warning',
                        'COMPLETED' => 'success',
                        'CANCELLED' => 'danger',
                        'ON_HOLD' => 'info'
                    ];
                    $badge_class = $status_badge[$procedure['status']] ?? 'secondary';
                    ?>
                    <span class="badge bg-<?php echo $badge_class; ?>">
                        <?php echo htmlspecialchars($procedure['status']); ?>
                    </span>
                </td>
                <td>
                    <?php 
                    if ($procedure['actual_duration']) {
                        echo htmlspecialchars($procedure['actual_duration']) . ' mins';
                    } else {
                        echo '<span class="text-muted">' . htmlspecialchars($procedure['estimated_duration']) . ' mins (est.)</span>';
                    }
                    ?>
                </td>
                <td>
                    KES <?php echo number_format($procedure['cost'] ?: $procedure['base_cost'], 2); ?>
                </td>
                <td>
                    <div class="btn-group btn-group-sm">
                        <a href="view_procedure.php?id=<?php echo $procedure['procedure_id']; ?>" 
                           class="btn btn-outline-primary" title="View Details">
                            <i class="ri-eye-line"></i>
                        </a>
                        <?php if ($procedure['consultation_id']): ?>
                        <a href="view_consultation.php?id=<?php echo $procedure['consultation_id']; ?>" 
                           class="btn btn-outline-info" title="View Consultation">
                            <i class="ri-file-text-line"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                </td>
            </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>

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