<?php
session_start();
include '../layouts/dbconn.php';

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

$doctor_id = $_SESSION['user_id'];

$query = "SELECT 
    c.consultation_id,
    c.consultation_date,
    c.consultation_time,
    c.consultation_status,
    c.chief_complaint,
    c.created_at,
    p.patient_id,
    p.patient_number,
    u.full_name as patient_name,
    u.phone_primary,
    p.date_of_birth,
    p.blood_group,
    a.appointment_id
FROM consultations c
INNER JOIN patients p ON c.patient_id = p.patient_id
INNER JOIN users u ON p.user_id = u.user_id
LEFT JOIN appointments a ON c.appointment_id = a.appointment_id
WHERE c.doctor_id = ? 
AND c.consultation_status IN ('PENDING', 'IN_PROGRESS')
AND DATE(c.consultation_date) = CURDATE()
ORDER BY 
    CASE c.consultation_status 
        WHEN 'IN_PROGRESS' THEN 1 
        WHEN 'PENDING' THEN 2 
    END,
    c.consultation_time ASC";

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

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        // Calculate age
        $dob = new DateTime($row['date_of_birth']);
        $now = new DateTime();
        $age = $dob->diff($now)->y;
        
        // Get initials
        $names = explode(' ', $row['patient_name']);
        $initials = '';
        foreach ($names as $name) {
            $initials .= strtoupper(substr($name, 0, 1));
        }
        
        // Status badge
        $status_class = $row['consultation_status'] == 'IN_PROGRESS' ? 'status-in-progress' : 'status-pending';
        $status_text = str_replace('_', ' ', $row['consultation_status']);
        
        // Calculate elapsed time for in-progress consultations
        $elapsed_time = '';
        if ($row['consultation_status'] == 'IN_PROGRESS') {
            $start = new DateTime($row['created_at']);
            $now = new DateTime();
            $diff = $now->diff($start);
            $elapsed_time = '<div class="timer-badge" data-start="' . $row['created_at'] . '">' . 
                           str_pad($diff->h, 2, '0', STR_PAD_LEFT) . ':' . 
                           str_pad($diff->i, 2, '0', STR_PAD_LEFT) . '</div>';
        }
        
        echo '
        <div class="card consultation-card">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-auto">
                        <div class="patient-avatar">' . $initials . '</div>
                    </div>
                    <div class="col">
                        <h5 class="mb-1">' . htmlspecialchars($row['patient_name']) . '</h5>
                        <p class="text-muted mb-2">
                            <strong>ID:</strong> ' . $row['patient_number'] . ' | 
                            <strong>Age:</strong> ' . $age . ' years | 
                            <strong>Blood:</strong> ' . ($row['blood_group'] ?? 'N/A') . '
                        </p>
                        <p class="mb-1"><i class="ri-phone-line me-1"></i>' . htmlspecialchars($row['phone_primary']) . '</p>
                        ' . ($row['chief_complaint'] ? '<p class="mb-0"><strong>Chief Complaint:</strong> ' . htmlspecialchars($row['chief_complaint']) . '</p>' : '') . '
                    </div>
                    <div class="col-auto text-center">
                        <span class="' . $status_class . '">' . $status_text . '</span>
                        <div class="mt-2">' . $elapsed_time . '</div>
                    </div>
                    <div class="col-auto">
                        <a href="new_consultation.php?consultation_id=' . $row['consultation_id'] . '" 
                           class="btn btn-primary me-2">
                            <i class="ri-edit-line me-1"></i>Continue
                        </a>
                        <a href="patient_medical_history.php?patient_id=' . $row['patient_id'] . '" 
                           class="btn btn-info me-2">
                            <i class="ri-history-line me-1"></i>History
                        </a>
                        <button class="btn btn-success btn-complete" data-id="' . $row['consultation_id'] . '">
                            <i class="ri-check-line me-1"></i>Complete
                        </button>
                    </div>
                </div>
            </div>
        </div>';
    }
} else {
    echo '
    <div class="text-center text-muted py-5">
        <i class="ri-stethoscope-line" style="font-size: 3rem;"></i>
        <p class="mt-3">No active consultations at the moment</p>
    </div>';
}

$conn->close();
?>