<?php
session_start();
require_once '../include/config.php';

// Check if doctor is logged in
if (!isset($_SESSION['doctor_id'])) {
    header("Location: login.php");
    exit();
}

$doctor_id = $_SESSION['doctor_id'];
$doctor_name = $_SESSION['doctor_name'] ?? 'Doctor';
$doctor_email = $_SESSION['doctor_email'] ?? '';

// Fetch doctor details safely
$doctor = [];
$docQuery = $conn->query("SELECT * FROM doctors WHERE doctor_id = '$doctor_id' OR id = '$doctor_id' LIMIT 1");
if ($docQuery && $docQuery->num_rows > 0) {
    $doctor = $docQuery->fetch_assoc();
}
$specialization = $doctor['specialization'] ?? 'General Medicine';
$consultation_fee = $doctor['consultation_fee'] ?? 0;
$license_number = $doctor['license_number'] ?? '';
$profile_photo = $doctor['profile_photo'] ?? '';
$profile_pic = !empty($profile_photo) ? '../' . $profile_photo : 'https://ui-avatars.com/api/?background=0a3d2f&color=fff&name=' . urlencode($doctor_name);

// --- Statistics with error prevention ---
$patient_count = 0;
$res = $conn->query("SELECT COUNT(DISTINCT patient_id) as cnt FROM consultations WHERE doctor_id = '$doctor_id'");
if ($res) { $row = $res->fetch_assoc(); $patient_count = $row['cnt'] ?? 0; }

$today_appointments = 0;
$res = $conn->query("SELECT COUNT(*) as cnt FROM appointments WHERE doctor_id = '$doctor_id' AND appointment_date = CURDATE()");
if ($res) { $row = $res->fetch_assoc(); $today_appointments = $row['cnt'] ?? 0; }

$pending_consults = 0;
$res = $conn->query("SELECT COUNT(*) as cnt FROM consultations WHERE doctor_id = '$doctor_id' AND status = 'scheduled'");
if ($res) { $row = $res->fetch_assoc(); $pending_consults = $row['cnt'] ?? 0; }

$ongoing_consults = 0;
$res = $conn->query("SELECT COUNT(*) as cnt FROM consultations WHERE doctor_id = '$doctor_id' AND status = 'ongoing'");
if ($res) { $row = $res->fetch_assoc(); $ongoing_consults = $row['cnt'] ?? 0; }

$completed_consults = 0;
$res = $conn->query("SELECT COUNT(*) as cnt FROM consultations WHERE doctor_id = '$doctor_id' AND status = 'completed'");
if ($res) { $row = $res->fetch_assoc(); $completed_consults = $row['cnt'] ?? 0; }

$total_earnings = 0;
$res = $conn->query("SELECT SUM(consultation_fee) as total FROM consultations WHERE doctor_id = '$doctor_id' AND status = 'completed'");
if ($res) { $row = $res->fetch_assoc(); $total_earnings = $row['total'] ?? 0; }

// Unread messages counts
$unread_patient_messages = 0;
$res = $conn->query("SELECT COUNT(*) as cnt FROM patient_doctor_messages WHERE doctor_id = '$doctor_id' AND is_read = 0");
if ($res) { $row = $res->fetch_assoc(); $unread_patient_messages = $row['cnt'] ?? 0; }

$unread_doctor_messages = 0;
$res = $conn->query("SELECT COUNT(*) as cnt FROM doctor_doctor_chat WHERE receiver_id = '$doctor_id' AND is_read = 0");
if ($res) { $row = $res->fetch_assoc(); $unread_doctor_messages = $row['cnt'] ?? 0; }

$unread_nurse_messages = 0;
$res = $conn->query("SELECT COUNT(*) as cnt FROM nurse_doctor_chat WHERE doctor_id = '$doctor_id' AND is_read = 0");
if ($res) { $row = $res->fetch_assoc(); $unread_nurse_messages = $row['cnt'] ?? 0; }

$unread_staff_messages = 0;
$res = $conn->query("SELECT COUNT(*) as cnt FROM staff_doctor_chat WHERE doctor_id = '$doctor_id' AND is_read = 0");
if ($res) { $row = $res->fetch_assoc(); $unread_staff_messages = $row['cnt'] ?? 0; }

$unread_notifications = 0;
$res = $conn->query("SELECT COUNT(*) as cnt FROM doctor_notifications WHERE doctor_id = '$doctor_id' AND is_read = 0");
if ($res) { $row = $res->fetch_assoc(); $unread_notifications = $row['cnt'] ?? 0; }

// CME sessions count
$cme_count = 0;
$res = $conn->query("SELECT COUNT(*) as cnt FROM cme_sessions WHERE doctor_id = '$doctor_id'");
if ($res) { $row = $res->fetch_assoc(); $cme_count = $row['cnt'] ?? 0; }

// Collaboration requests count
$collab_count = 0;
$res = $conn->query("SELECT COUNT(*) as cnt FROM collaborations WHERE doctor_id = '$doctor_id' AND status = 'pending'");
if ($res) { $row = $res->fetch_assoc(); $collab_count = $row['cnt'] ?? 0; }

// Fetch pending consultations for display
$pendingList = $conn->query("
    SELECT c.*, p.first_name, p.last_name, p.patient_id as patient_uid 
    FROM consultations c
    JOIN patients p ON c.patient_id = p.patient_id
    WHERE c.doctor_id = '$doctor_id' AND c.status = 'scheduled'
    ORDER BY c.scheduled_time ASC LIMIT 5
");

$ongoingList = $conn->query("
    SELECT c.*, p.first_name, p.last_name, p.patient_id as patient_uid 
    FROM consultations c
    JOIN patients p ON c.patient_id = p.patient_id
    WHERE c.doctor_id = '$doctor_id' AND c.status = 'ongoing'
    ORDER BY c.scheduled_time ASC
");

// Handle POST actions
$success_msg = '';
$error_msg = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['start_consultation'])) {
        $consult_id = intval($_POST['consult_id']);
        $room_name = "uhd_" . $doctor_id . "_" . $consult_id . "_" . time();
        $meeting_link = "https://meet.jit.si/" . $room_name;
        $update = $conn->query("UPDATE consultations SET status = 'ongoing', meeting_link = '$meeting_link', started_at = NOW() WHERE id = '$consult_id' AND doctor_id = '$doctor_id'");
        if ($update) {
            echo "<script>window.open('$meeting_link', '_blank'); window.location.href='uhd_dashboard.php?success=started';</script>";
            exit();
        }
    }
    if (isset($_POST['cancel_consultation'])) {
        $consult_id = intval($_POST['consult_id']);
        $conn->query("UPDATE consultations SET status = 'cancelled' WHERE id = '$consult_id' AND doctor_id = '$doctor_id'");
        $success_msg = "Consultation cancelled.";
    }
}

if (isset($_GET['success']) && $_GET['success'] == 'started') $success_msg = "Consultation started! Video call opened in new tab.";
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>UHD Doctor Dashboard - Unity Healthcare</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <style>
        :root {
            --uhd-green: #0a3d2f;
            --uhd-green-light: #0f6b4c;
            --uhd-gold: #d4a017;
            --uhd-dark: #064e3b;
        }
        body { background: #f0f2f5; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        
        /* Sidebar Styles */
        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            width: 280px;
            height: 100%;
            background: linear-gradient(135deg, var(--uhd-green), var(--uhd-dark));
            color: white;
            z-index: 1000;
            transition: all 0.3s ease;
            overflow-y: auto;
            box-shadow: 2px 0 15px rgba(0,0,0,0.1);
        }
        .sidebar-header {
            padding: 25px 20px;
            text-align: center;
            border-bottom: 1px solid rgba(255,255,255,0.2);
        }
        .sidebar-header img {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
            border: 3px solid var(--uhd-gold);
            margin-bottom: 10px;
        }
        .sidebar-header h4 { font-size: 1.2rem; margin-bottom: 5px; }
        .sidebar-header p { font-size: 0.75rem; opacity: 0.8; }
        .sidebar-menu { list-style: none; padding: 20px 0; }
        .sidebar-menu li { margin-bottom: 5px; }
        .sidebar-menu a {
            display: block;
            padding: 12px 25px;
            color: white;
            text-decoration: none;
            transition: 0.3s;
            font-size: 0.9rem;
        }
        .sidebar-menu a:hover, .sidebar-menu a.active {
            background: rgba(255,255,255,0.15);
            border-left: 3px solid var(--uhd-gold);
            padding-left: 22px;
        }
        .sidebar-menu i { width: 25px; margin-right: 10px; }
        .sidebar-badge {
            float: right;
            background: #dc3545;
            border-radius: 20px;
            padding: 2px 8px;
            font-size: 10px;
        }
        
        /* Main Content */
        .main-content {
            margin-left: 280px;
            padding: 20px;
            transition: all 0.3s;
            min-height: 100vh;
        }
        
        /* Top Header */
        .top-header {
            background: white;
            border-radius: 20px;
            padding: 15px 25px;
            margin-bottom: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }
        .welcome-text h2 { font-size: 1.3rem; color: var(--uhd-green); margin-bottom: 5px; }
        .welcome-text p { color: #666; font-size: 0.85rem; margin: 0; }
        .header-actions { display: flex; gap: 10px; }
        .btn-uhd { background: var(--uhd-gold); color: white; border-radius: 40px; padding: 8px 20px; border: none; }
        .btn-uhd:hover { background: #b8860b; color: white; }
        
        /* Stat Cards */
        .stats-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 30px; }
        .stat-card {
            background: white;
            border-radius: 20px;
            padding: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            transition: 0.3s;
            cursor: pointer;
            border-left: 4px solid var(--uhd-gold);
        }
        .stat-card:hover { transform: translateY(-5px); box-shadow: 0 10px 25px rgba(0,0,0,0.15); }
        .stat-card i { font-size: 2rem; color: var(--uhd-gold); margin-bottom: 10px; }
        .stat-card h3 { font-size: 1.8rem; font-weight: bold; color: var(--uhd-green); margin: 5px 0; }
        .stat-card p { color: #666; margin: 0; font-size: 0.85rem; }
        
        /* Feature Grid */
        .section-title {
            font-size: 1.2rem;
            font-weight: 600;
            color: var(--uhd-green);
            margin: 25px 0 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid var(--uhd-gold);
            display: inline-block;
        }
        .feature-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 15px; margin-bottom: 30px; }
        .feature-card {
            background: white;
            border-radius: 15px;
            padding: 20px 10px;
            text-align: center;
            cursor: pointer;
            transition: 0.3s;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            text-decoration: none;
            display: block;
        }
        .feature-card:hover { transform: translateY(-5px); background: var(--uhd-green); }
        .feature-card:hover i, .feature-card:hover h6, .feature-card:hover p { color: white; }
        .feature-card i { font-size: 2rem; color: var(--uhd-gold); margin-bottom: 10px; display: block; }
        .feature-card h6 { font-size: 0.85rem; font-weight: 600; color: #333; margin: 5px 0; }
        .feature-card p { font-size: 0.7rem; color: #666; margin: 0; }
        .feature-badge {
            background: #dc3545;
            color: white;
            border-radius: 30px;
            padding: 2px 8px;
            font-size: 0.65rem;
            margin-left: 5px;
        }
        
        /* Consultation Cards */
        .consult-card {
            background: white;
            border-radius: 15px;
            padding: 15px;
            margin-bottom: 15px;
            border-left: 4px solid;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        .consult-pending { border-left-color: #ffc107; }
        .consult-ongoing { border-left-color: #dc3545; animation: pulse 2s infinite; }
        @keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(220,53,69,0.2); } 50% { box-shadow: 0 0 0 5px rgba(220,53,69,0.1); } 100% { box-shadow: 0 0 0 0 rgba(220,53,69,0); } }
        
        .btn-sm-action { border-radius: 20px; padding: 4px 12px; margin: 2px; font-size: 0.75rem; }
        
        /* Mobile Toggle */
        .menu-toggle {
            display: none;
            position: fixed;
            top: 15px;
            left: 15px;
            z-index: 1001;
            background: var(--uhd-green);
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
        }
        
        @media (max-width: 768px) {
            .sidebar { transform: translateX(-100%); width: 260px; }
            .sidebar.active { transform: translateX(0); }
            .main-content { margin-left: 0; padding: 15px; }
            .menu-toggle { display: block; }
            .stats-row { grid-template-columns: repeat(2, 1fr); gap: 12px; }
            .feature-grid { grid-template-columns: repeat(3, 1fr); gap: 10px; }
            .stat-card h3 { font-size: 1.3rem; }
        }
    </style>
</head>
<body>

<button class="menu-toggle" onclick="toggleSidebar()"><i class="fas fa-bars"></i> Menu</button>

<!-- Sidebar -->
<div class="sidebar" id="sidebar">
    <div class="sidebar-header">
        <img src="<?= $profile_pic ?>" alt="Dr. <?= htmlspecialchars($doctor_name) ?>">
        <h4>Dr. <?= htmlspecialchars($doctor_name) ?></h4>
        <p><?= htmlspecialchars($specialization) ?></p>
    </div>
    <ul class="sidebar-menu">
        <li><a href="uhd_dashboard.php" class="active"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li>
        <li><a href="my_patients.php"><i class="fas fa-users"></i> My Patients</a></li>
        <li><a href="consultations.php"><i class="fas fa-video"></i> Video Consultations</a></li>
        <li><a href="appointments.php"><i class="fas fa-calendar-alt"></i> Appointments</a></li>
        <li><a href="prescriptions.php"><i class="fas fa-prescription-bottle"></i> Prescriptions</a></li>
        <li><a href="patient_messages.php"><i class="fas fa-comments"></i> Patient Messages <?php if($unread_patient_messages > 0): ?><span class="sidebar-badge"><?= $unread_patient_messages ?></span><?php endif; ?></a></li>
        <li><a href="doctor_chat.php"><i class="fas fa-user-md"></i> Doctor Chat <?php if($unread_doctor_messages > 0): ?><span class="sidebar-badge"><?= $unread_doctor_messages ?></span><?php endif; ?></a></li>
        <li><a href="nurse_chat.php"><i class="fas fa-user-nurse"></i> Nurse Chat <?php if($unread_nurse_messages > 0): ?><span class="sidebar-badge"><?= $unread_nurse_messages ?></span><?php endif; ?></a></li>
        <li><a href="staff_chat.php"><i class="fas fa-headset"></i> Staff Chat <?php if($unread_staff_messages > 0): ?><span class="sidebar-badge"><?= $unread_staff_messages ?></span><?php endif; ?></a></li>
        <li><a href="doctor_engagement.php"><i class="fas fa-handshake"></i> Engagement Hub</a></li>
        <li><a href="ai_assistant.php"><i class="fas fa-robot"></i> AI Assistant</a></li>
        <li><a href="cme_sessions.php"><i class="fas fa-graduation-cap"></i> CME Sessions</a></li>
        <li><a href="doctor_payments.php"><i class="fas fa-money-bill-wave"></i> Payments</a></li>
        <li><a href="referral.php"><i class="fas fa-share-alt"></i> Refer & Earn</a></li>
        <li><a href="profile.php"><i class="fas fa-user-edit"></i> Profile</a></li>
        <li><a href="notifications.php"><i class="fas fa-bell"></i> Notifications <?php if($unread_notifications > 0): ?><span class="sidebar-badge"><?= $unread_notifications ?></span><?php endif; ?></a></li>
        <li><a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
    </ul>
</div>

<!-- Main Content -->
<div class="main-content" id="mainContent">
    <!-- Top Header -->
    <div class="top-header">
        <div class="welcome-text">
            <h2><i class="fas fa-stethoscope me-2" style="color: var(--uhd-gold);"></i>Welcome back, Dr. <?= htmlspecialchars($doctor_name) ?></h2>
            <p><i class="far fa-calendar-alt me-1"></i> <?= date('l, F j, Y') ?> | <i class="far fa-clock me-1"></i> <?= date('h:i A') ?></p>
        </div>
        <div class="header-actions">
            <a href="schedule_consultation.php" class="btn-uhd"><i class="fas fa-plus"></i> Schedule</a>
            <a href="video_consultation.php" class="btn btn-outline-secondary rounded-pill"><i class="fas fa-video"></i> New Call</a>
        </div>
    </div>

    <!-- Alert Messages -->
    <?php if ($success_msg): ?>
        <div class="alert alert-success alert-dismissible fade show"><i class="fas fa-check-circle me-2"></i> <?= htmlspecialchars($success_msg) ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
    <?php endif; ?>
    <?php if ($error_msg): ?>
        <div class="alert alert-danger alert-dismissible fade show"><i class="fas fa-exclamation-triangle me-2"></i> <?= htmlspecialchars($error_msg) ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
    <?php endif; ?>

    <!-- Statistics Cards -->
    <div class="stats-row">
        <div class="stat-card" onclick="location.href='my_patients.php'"><i class="fas fa-users"></i><h3><?= $patient_count ?></h3><p>Total Patients</p></div>
        <div class="stat-card" onclick="location.href='appointments.php?date=today'"><i class="fas fa-calendar-check"></i><h3><?= $today_appointments ?></h3><p>Today's Appointments</p></div>
        <div class="stat-card" onclick="location.href='consultations.php?status=pending'"><i class="fas fa-hourglass-half"></i><h3><?= $pending_consults ?></h3><p>Pending Consults</p></div>
        <div class="stat-card" onclick="location.href='consultations.php?status=ongoing'"><i class="fas fa-video"></i><h3><?= $ongoing_consults ?></h3><p>Active Calls</p></div>
        <div class="stat-card" onclick="location.href='consultations.php?status=completed'"><i class="fas fa-check-circle"></i><h3><?= $completed_consults ?></h3><p>Completed</p></div>
        <div class="stat-card" onclick="location.href='doctor_payments.php'"><i class="fas fa-money-bill-wave"></i><h3>₦<?= number_format($total_earnings, 0) ?></h3><p>Total Earnings</p></div>
    </div>

    <!-- Quick Actions Section -->
    <h5 class="section-title"><i class="fas fa-bolt me-2"></i> Quick Actions</h5>
    <div class="feature-grid">
        <a href="my_patients.php" class="feature-card"><i class="fas fa-users"></i><h6>My Patients</h6><p>View all patients</p></a>
        <a href="add_prescription.php" class="feature-card"><i class="fas fa-prescription-bottle"></i><h6>Prescribe</h6><p>Write prescription</p></a>
        <a href="add_vital.php" class="feature-card"><i class="fas fa-heartbeat"></i><h6>Add Vitals</h6><p>Record vitals</p></a>
        <a href="patient_record.php" class="feature-card"><i class="fas fa-notes-medical"></i><h6>Medical Records</h6><p>View history</p></a>
        <a href="schedule_consultation.php" class="feature-card"><i class="fas fa-calendar-plus"></i><h6>Schedule</h6><p>Book consultation</p></a>
        <a href="video_consultation.php" class="feature-card"><i class="fas fa-video"></i><h6>Video Call</h6><p>Start instant call</p></a>
    </div>

    <!-- Communication Hub -->
    <h5 class="section-title"><i class="fas fa-comments me-2"></i> Communication Hub</h5>
    <div class="feature-grid">
        <a href="patient_messages.php" class="feature-card">
            <i class="fas fa-user-circle"></i>
            <h6>Patient Messages <?php if($unread_patient_messages > 0): ?><span class="feature-badge"><?= $unread_patient_messages ?></span><?php endif; ?></h6>
            <p>Chat with patients</p>
        </a>
        <a href="doctor_chat.php" class="feature-card">
            <i class="fas fa-user-md"></i>
            <h6>Doctor Chat <?php if($unread_doctor_messages > 0): ?><span class="feature-badge"><?= $unread_doctor_messages ?></span><?php endif; ?></h6>
            <p>Discuss with colleagues</p>
        </a>
        <a href="nurse_chat.php" class="feature-card">
            <i class="fas fa-user-nurse"></i>
            <h6>Nurse Chat <?php if($unread_nurse_messages > 0): ?><span class="feature-badge"><?= $unread_nurse_messages ?></span><?php endif; ?></h6>
            <p>Coordinate care</p>
        </a>
        <a href="staff_chat.php" class="feature-card">
            <i class="fas fa-headset"></i>
            <h6>Staff Chat <?php if($unread_staff_messages > 0): ?><span class="feature-badge"><?= $unread_staff_messages ?></span><?php endif; ?></h6>
            <p>Admin support</p>
        </a>
    </div>

    <!-- Clinical Tools -->
    <h5 class="section-title"><i class="fas fa-tools me-2"></i> Clinical Tools</h5>
    <div class="feature-grid">
        <a href="ai_assistant.php" class="feature-card"><i class="fas fa-robot"></i><h6>AI Assistant</h6><p>Clinical decision support</p></a>
        <a href="doctor_engagement.php" class="feature-card"><i class="fas fa-handshake"></i><h6>Engagement Hub</h6><p>Professional network</p></a>
        <a href="cme_sessions.php" class="feature-card"><i class="fas fa-graduation-cap"></i><h6>CME Sessions</h6><p><?= $cme_count ?> credits earned</p></a>
        <a href="collaboration_detail.php" class="feature-card"><i class="fas fa-users"></i><h6>Collaborations <?php if($collab_count > 0): ?><span class="feature-badge"><?= $collab_count ?></span><?php endif; ?></h6><p>Research partnerships</p></a>
    </div>

    <!-- Financial & Rewards -->
    <h5 class="section-title"><i class="fas fa-chart-line me-2"></i> Financial & Rewards</h5>
    <div class="feature-grid">
        <a href="doctor_payments.php" class="feature-card"><i class="fas fa-money-bill-wave"></i><h6>Payments</h6><p>View earnings</p></a>
        <a href="referral.php" class="feature-card"><i class="fas fa-share-alt"></i><h6>Refer & Earn</h6><p>₦10,000 per referral</p></a>
        <a href="subscription.php" class="feature-card"><i class="fas fa-crown"></i><h6>Subscription</h6><p>Premium features</p></a>
    </div>

    <!-- Pending Consultations -->
    <?php if ($pendingList && $pendingList->num_rows > 0): ?>
    <h5 class="section-title"><i class="fas fa-clock me-2"></i> Pending Consultations</h5>
    <div style="margin-bottom: 30px;">
        <?php while ($c = $pendingList->fetch_assoc()): ?>
            <div class="consult-card consult-pending">
                <div class="row align-items-center">
                    <div class="col-md-4">
                        <strong><i class="fas fa-user me-2"></i><?= htmlspecialchars($c['first_name'] . ' ' . $c['last_name']) ?></strong>
                        <br><small class="text-muted">ID: <?= substr($c['patient_uid'] ?? '', 0, 8) ?>...</small>
                    </div>
                    <div class="col-md-3">
                        <i class="fas fa-calendar-alt me-1"></i> <?= date('M d, Y', strtotime($c['scheduled_time'])) ?>
                        <br><i class="fas fa-clock me-1"></i> <?= date('h:i A', strtotime($c['scheduled_time'])) ?>
                    </div>
                    <div class="col-md-3">
                        <small class="text-muted"><?= htmlspecialchars(substr($c['reason'] ?? 'General checkup', 0, 40)) ?></small>
                    </div>
                    <div class="col-md-2 text-end">
                        <form method="POST" class="d-inline">
                            <input type="hidden" name="consult_id" value="<?= $c['id'] ?>">
                            <button type="submit" name="start_consultation" class="btn btn-danger btn-sm-action"><i class="fas fa-video"></i> Start</button>
                        </form>
                        <form method="POST" class="d-inline" onsubmit="return confirm('Cancel?')">
                            <input type="hidden" name="consult_id" value="<?= $c['id'] ?>">
                            <button type="submit" name="cancel_consultation" class="btn btn-secondary btn-sm-action"><i class="fas fa-times"></i></button>
                        </form>
                    </div>
                </div>
            </div>
        <?php endwhile; ?>
        <div class="text-center mt-2"><a href="consultations.php" class="text-decoration-none">View all consultations →</a></div>
    </div>
    <?php endif; ?>

    <!-- Ongoing Consultations -->
    <?php if ($ongoingList && $ongoingList->num_rows > 0): ?>
    <h5 class="section-title"><i class="fas fa-video me-2"></i> Ongoing Consultations</h5>
    <div style="margin-bottom: 30px;">
        <?php while ($c = $ongoingList->fetch_assoc()): ?>
            <div class="consult-card consult-ongoing">
                <div class="row align-items-center">
                    <div class="col-md-4">
                        <strong><i class="fas fa-user me-2"></i><?= htmlspecialchars($c['first_name'] . ' ' . $c['last_name']) ?></strong>
                    </div>
                    <div class="col-md-4">
                        <?php if (!empty($c['meeting_link'])): ?>
                            <a href="<?= $c['meeting_link'] ?>" target="_blank" class="btn btn-danger btn-sm-action"><i class="fas fa-video"></i> Join Room</a>
                            <button class="btn btn-outline-secondary btn-sm-action" onclick="copyLink('<?= htmlspecialchars($c['meeting_link']) ?>')"><i class="fas fa-copy"></i> Copy</button>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-4 text-end">
                        <button class="btn btn-success btn-sm-action" onclick="completeConsultation(<?= $c['id'] ?>)"><i class="fas fa-check"></i> Complete</button>
                    </div>
                </div>
            </div>
        <?php endwhile; ?>
    </div>
    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleSidebar() {
        document.getElementById('sidebar').classList.toggle('active');
    }
    
    function copyLink(link) {
        navigator.clipboard.writeText(link);
        alert('Meeting link copied to clipboard!');
    }
    
    function completeConsultation(id) {
        let notes = prompt("Enter consultation notes/summary:");
        if (notes) {
            fetch('complete_consultation_ajax.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: 'consult_id=' + id + '&notes=' + encodeURIComponent(notes)
            }).then(response => response.json()).then(data => {
                if (data.success) location.reload();
                else alert('Error completing consultation');
            });
        }
    }
    
    // Close sidebar when clicking outside on mobile
    document.addEventListener('click', function(event) {
        const sidebar = document.getElementById('sidebar');
        const toggleBtn = document.querySelector('.menu-toggle');
        if (window.innerWidth <= 768 && sidebar && toggleBtn && !sidebar.contains(event.target) && !toggleBtn.contains(event.target)) {
            sidebar.classList.remove('active');
        }
    });
</script>
</body>
</html>