<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (!isset($_SESSION['patient_id'])) {
    header("Location: login.php");
    exit();
}

include '../include/config.php';

$user_id = $_SESSION['patient_id'];
$user_name = $_SESSION['patient_name'];
$user_email = $_SESSION['patient_email'];

$user = $conn->query("SELECT * FROM patients WHERE patient_id = '$user_id'")->fetch_assoc();

// Handle profile picture upload
$profile_pic_error = '';
$profile_pic_success = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['profile_picture'])) {
    $target_dir = "../uploads/profiles/";
    if (!file_exists($target_dir)) mkdir($target_dir, 0777, true);
    
    $file_extension = strtolower(pathinfo($_FILES['profile_picture']['name'], PATHINFO_EXTENSION));
    $allowed_types = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    
    if (in_array($file_extension, $allowed_types)) {
        $new_filename = 'user_' . $user_id . '_' . time() . '.' . $file_extension;
        if (move_uploaded_file($_FILES['profile_picture']['tmp_name'], $target_dir . $new_filename)) {
            $profile_pic_path = 'uploads/profiles/' . $new_filename;
            $conn->query("UPDATE patients SET profile_pic = '$profile_pic_path' WHERE patient_id = '$user_id'");
            $profile_pic_success = "Profile picture updated!";
            $user = $conn->query("SELECT * FROM patients WHERE patient_id = '$user_id'")->fetch_assoc();
        } else {
            $profile_pic_error = "Error uploading image.";
        }
    } else {
        $profile_pic_error = "Only JPG, JPEG, PNG, GIF, and WEBP files are allowed.";
    }
}

// Get all stats
$total_consultations = $conn->query("SELECT COUNT(*) as cnt FROM consultations WHERE patient_id = '$user_id'")->fetch_assoc()['cnt'] ?? 0;
$upcoming_appointments = $conn->query("SELECT COUNT(*) as cnt FROM appointments WHERE patient_id = '$user_id' AND appointment_date >= CURDATE()")->fetch_assoc()['cnt'] ?? 0;
$wallet_balance = $conn->query("SELECT balance FROM hps_wallet WHERE user_id = '$user_id'")->fetch_assoc()['balance'] ?? 0;
$active_subscriptions = $conn->query("SELECT COUNT(*) as cnt FROM hps_subscriptions WHERE user_id = '$user_id' AND status = 'active'")->fetch_assoc()['cnt'] ?? 0;

// Get unread counts for notification icons
$unread_messages = $conn->query("SELECT COUNT(*) as cnt FROM patient_doctor_messages WHERE patient_id = '$user_id' AND is_read = 0 AND sender = 'doctor'")->fetch_assoc()['cnt'] ?? 0;
$unread_notifications = $conn->query("SELECT COUNT(*) as cnt FROM patient_notifications WHERE patient_id = '$user_id' AND is_read = 0")->fetch_assoc()['cnt'] ?? 0;

$page_title = 'Wellness Dashboard | UHD';
include '../include/header.php';
?>

<!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>Wellness Dashboard | UHD</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">
    <link href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <style>
        :root { --primary: #0a3d2f; --accent: #d4a017; --red: #dc3545; --dark: #064e3b; }
        body { font-family: 'Inter', sans-serif; background: linear-gradient(135deg, #0a3d2f 0%, #064e3b 100%); min-height: 100vh; }
        
        .profile-section { background: rgba(255,255,255,0.08); backdrop-filter: blur(10px); border-radius: 32px; padding: 25px; margin-bottom: 30px; border: 1px solid rgba(255,255,255,0.15); }
        .profile-pic { width: 80px; height: 80px; border-radius: 50%; object-fit: cover; border: 3px solid var(--accent); }
        .edit-pic-btn { background: var(--accent); border-radius: 50%; width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; cursor: pointer; border: 2px solid white; }
        
        .notification-icons { display: flex; gap: 15px; align-items: center; }
        .icon-btn { position: relative; background: rgba(255,255,255,0.15); border-radius: 50%; width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: 0.2s; }
        .icon-btn:hover { background: var(--accent); }
        .badge-count { position: absolute; top: -5px; right: -5px; background: var(--red); color: white; border-radius: 50%; width: 18px; height: 18px; font-size: 10px; display: flex; align-items: center; justify-content: center; font-weight: bold; }
        
        .stat-card { background: white; border-radius: 20px; padding: 20px; text-align: center; transition: all 0.3s; cursor: pointer; box-shadow: 0 10px 25px rgba(0,0,0,0.1); border-bottom: 3px solid var(--red); }
        .stat-card:hover { transform: translateY(-5px); box-shadow: 0 20px 35px rgba(0,0,0,0.15); }
        .stat-number { font-size: 1.8rem; font-weight: 800; color: var(--primary); margin: 10px 0; }
        .stat-card i { font-size: 1.8rem; color: var(--accent); }
        
        .hub-card { background: white; border-radius: 24px; padding: 28px; text-align: center; transition: all 0.3s; cursor: pointer; height: 100%; box-shadow: 0 10px 25px rgba(0,0,0,0.08); border-bottom: 3px solid var(--red); position: relative; overflow: hidden; }
        .hub-card:hover { transform: translateY(-8px); box-shadow: 0 20px 40px rgba(0,0,0,0.15); }
        .hub-icon { width: 70px; height: 70px; background: linear-gradient(135deg, var(--primary), var(--dark)); border-radius: 20px; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px; }
        .hub-icon i { font-size: 2rem; color: var(--accent); }
        .hub-card h3 { font-size: 1.3rem; font-weight: 700; margin-bottom: 10px; }
        .hub-desc { font-size: 0.85rem; color: #555; margin-bottom: 15px; }
        .feature-list { list-style: none; padding: 0; margin: 15px 0; }
        .feature-list li { padding: 6px 0; font-size: 0.8rem; color: #666; border-bottom: 1px solid #eee; text-align: left; }
        .feature-list i { width: 25px; color: var(--accent); }
        .btn-hub { background: var(--accent); color: var(--dark); border-radius: 40px; padding: 10px 20px; font-weight: 600; border: none; margin-top: 15px; width: 100%; transition: 0.2s; }
        .btn-hub:hover { background: #b8860b; color: white; }
        
        .video-card { background: linear-gradient(135deg, #1a1a2e, #16213e); border-radius: 24px; padding: 25px; cursor: pointer; transition: all 0.3s; border: 1px solid rgba(212,160,23,0.3); margin-bottom: 20px; }
        .video-card:hover { transform: translateY(-5px); border-color: var(--accent); }
        
        .wellness-tip { background: linear-gradient(135deg, #1e3c72, #2a5298); border-radius: 20px; padding: 20px; color: white; }
        .btn-gold { background: #d4a017; color: #0a3d2f; border: none; transition: 0.2s; }
        .btn-gold:hover { background: #b8860b; color: white; }
        
        @media (max-width: 768px) {
            .profile-pic { width: 60px; height: 60px; }
            .stat-number { font-size: 1.3rem; }
            .hub-card { padding: 20px; }
            .hub-icon { width: 50px; height: 50px; }
            .feature-list li { font-size: 0.7rem; }
        }
    </style>
</head>
<body>

<div class="container mt-4">
    <!-- Profile Section -->
    <div class="profile-section text-white">
        <div class="row align-items-center">
            <div class="col-auto">
                <div class="position-relative d-inline-block">
                    <?php $profile_pic = !empty($user['profile_pic']) ? '../' . $user['profile_pic'] : 'https://ui-avatars.com/api/?background=d4a017&color=fff&name=' . urlencode($user_name); ?>
                    <img src="<?= $profile_pic ?>" class="profile-pic">
                    <div class="edit-pic-btn position-absolute bottom-0 end-0" data-bs-toggle="modal" data-bs-target="#profilePicModal">
                        <i class="fas fa-camera fa-xs"></i>
                    </div>
                </div>
            </div>
            <div class="col">
                <span class="badge bg-warning text-dark mb-2 px-3 py-1 rounded-pill"><i class="fas fa-spa me-1"></i> Welcome Back</span>
                <h2 class="fw-bold mb-1">Hello, <?= htmlspecialchars(explode(' ', $user_name)[0]) ?>! ðŸ‘‹</h2>
                <p class="mb-0 opacity-75"><i class="fas fa-envelope me-1"></i> <?= htmlspecialchars($user_email) ?></p>
            </div>
            <div class="col-auto">
                <div class="notification-icons">
                    <div class="icon-btn" onclick="location.href='messages.php'">
                        <i class="fas fa-comments"></i>
                        <?php if($unread_messages > 0): ?>
                            <span class="badge-count"><?= $unread_messages > 9 ? '9+' : $unread_messages ?></span>
                        <?php endif; ?>
                    </div>
                    <div class="icon-btn" onclick="location.href='notifications.php'">
                        <i class="fas fa-bell"></i>
                        <?php if($unread_notifications > 0): ?>
                            <span class="badge-count"><?= $unread_notifications > 9 ? '9+' : $unread_notifications ?></span>
                        <?php endif; ?>
                    </div>
                    <div class="icon-btn" onclick="location.href='view_profile.php'">
                        <i class="fas fa-user"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Stats -->
    <div class="row g-3 mb-5">
        <div class="col-md-3 col-6"><div class="stat-card" onclick="location.href='medical/consultations.php'"><i class="fas fa-video"></i><div class="stat-number"><?= $total_consultations ?></div><p class="mb-0 fw-bold">Consultations</p></div></div>
        <div class="col-md-3 col-6"><div class="stat-card" onclick="location.href='medical/appointments.php'"><i class="fas fa-calendar-check"></i><div class="stat-number"><?= $upcoming_appointments ?></div><p class="mb-0 fw-bold">Appointments</p></div></div>
        <div class="col-md-3 col-6"><div class="stat-card" onclick="location.href='hps/wallet.php'"><i class="fas fa-wallet"></i><div class="stat-number">â‚¦<?= number_format($wallet_balance, 2) ?></div><p class="mb-0 fw-bold">Wallet</p></div></div>
        <div class="col-md-3 col-6"><div class="stat-card" onclick="location.href='hps/dashboard.php'"><i class="fas fa-shield-alt"></i><div class="stat-number"><?= $active_subscriptions ?></div><p class="mb-0 fw-bold">Active Plans</p></div></div>
    </div>

    <!-- Main Hubs -->
    <h4 class="text-white mb-4"><i class="fas fa-cube me-2"></i> Your Health Ecosystem</h4>
    <div class="row g-4 mb-5">
        <!-- Medical Hub -->
        <div class="col-md-4">
            <div class="hub-card" onclick="location.href='medical/index.php'">
                <div class="hub-icon"><i class="fas fa-stethoscope"></i></div>
                <h3>Medical Hub</h3>
                <p class="hub-desc">Your complete healthcare management center</p>
                <ul class="feature-list">
                    <li><i class="fas fa-video me-2"></i> Video Consultations</li>
                    <li><i class="fas fa-calendar me-2"></i> Appointments</li>
                    <li><i class="fas fa-notes-medical me-2"></i> Medical Records</li>
                    <li><i class="fas fa-prescription me-2"></i> Prescriptions</li>
                </ul>
                <button class="btn-hub">Explore Medical Hub â†’</button>
            </div>
        </div>

        <!-- HPS Insurance Hub -->
        <div class="col-md-4">
            <div class="hub-card" onclick="location.href='hps/dashboard.php'">
                <div class="hub-icon"><i class="fas fa-shield-alt"></i></div>
                <h3>HPS Insurance</h3>
                <p class="hub-desc">Protect your health and family with flexible plans</p>
                <ul class="feature-list">
                    <li><i class="fas fa-user me-2"></i> HPS Single Plan</li>
                    <li><i class="fas fa-users me-2"></i> HPS Family Plan</li>
                    <li><i class="fas fa-handshake me-2"></i> HPS Associates</li>
                    <li><i class="fas fa-wallet me-2"></i> Wallet & Cards</li>
                </ul>
                <button class="btn-hub">Explore Insurance â†’</button>
            </div>
        </div>

        <!-- Investment Hub -->
        <div class="col-md-4">
            <div class="hub-card" onclick="location.href='hps/invest.php'">
                <div class="hub-icon"><i class="fas fa-chart-line"></i></div>
                <h3>HPS Invest</h3>
                <p class="hub-desc">Grow your wealth while supporting healthcare</p>
                <ul class="feature-list">
                    <li><i class="fas fa-microscope me-2"></i> Medical Equipment</li>
                    <li><i class="fas fa-percent me-2"></i> 12-24% ROI</li>
                    <li><i class="fas fa-chart-pie me-2"></i> Diversified Portfolios</li>
                    <li><i class="fas fa-calendar-week me-2"></i> Quarterly Returns</li>
                </ul>
                <button class="btn-hub">Explore Investment â†’</button>
            </div>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="row g-3 mb-4">
        <div class="col-md-6">
            <div class="video-card" onclick="location.href='medical/consultations.php'">
                <div class="row align-items-center">
                    <div class="col-8">
                        <i class="fas fa-video fa-2x mb-2" style="color: var(--accent);"></i>
                        <h5 class="text-white mb-1">Need to see a doctor?</h5>
                        <p class="text-white-50 mb-0">Connect instantly via secure video consultation</p>
                    </div>
                    <div class="col-4 text-end">
                        <div class="btn-gold d-inline-block px-3 py-2 rounded-pill"><i class="fas fa-play-circle me-1"></i> Start</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="video-card" onclick="location.href='hps/wallet.php'">
                <div class="row align-items-center">
                    <div class="col-8">
                        <i class="fas fa-wallet fa-2x mb-2" style="color: var(--accent);"></i>
                        <h5 class="text-white mb-1">Manage Your Wallet</h5>
                        <p class="text-white-50 mb-0">Deposit, withdraw, and track transactions</p>
                    </div>
                    <div class="col-4 text-end">
                        <div class="btn-gold d-inline-block px-3 py-2 rounded-pill"><i class="fas fa-arrow-right me-1"></i> Go</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Wellness Tips -->
    <div class="row">
        <div class="col-12">
            <div class="wellness-tip">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <i class="fas fa-lightbulb fa-2x mb-2"></i>
                        <h5 class="fw-bold mb-1">Wellness Insight</h5>
                        <p class="mb-0 opacity-75">"Prevention is better than cure. Regular check-ups and a healthy lifestyle are your best investment in long-term wellness."</p>
                    </div>
                    <div class="col-md-4 text-md-end mt-3 mt-md-0">
                        <button class="btn btn-outline-light rounded-pill btn-sm" onclick="location.href='medical/daily_activity.php'">
                            <i class="fas fa-chart-line me-1"></i> Update Wellness
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Profile Picture Modal -->
<div class="modal fade" id="profilePicModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header" style="background: var(--primary); color: white;">
                <h5 class="modal-title"><i class="fas fa-camera me-2"></i> Update Profile Picture</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <div class="modal-body text-center">
                    <?php if($profile_pic_error): ?><div class="alert alert-danger"><?= $profile_pic_error ?></div><?php endif; ?>
                    <?php if($profile_pic_success): ?><div class="alert alert-success"><?= $profile_pic_success ?></div><?php endif; ?>
                    <img src="<?= $profile_pic ?>" class="rounded-circle mb-3" style="width: 120px; height: 120px; object-fit: cover; border: 3px solid var(--accent);">
                    <input type="file" name="profile_picture" class="form-control" accept="image/jpeg,image/png,image/gif,image/webp" required>
                    <small class="text-muted">Max size: 5MB. Allowed: JPG, PNG, GIF, WEBP</small>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-gold">Upload Picture</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

<!-- ============================================ -->
<!-- AI CLINICAL ASSISTANT SECTION - BOTTOM OF DASHBOARD -->
<!-- ============================================ -->
<style>
/* =========================
   SCOPED AI CLINIC STYLES (No interference with dashboard)
========================= */
.ai-clinic-wrapper {
    all: initial;
    display: block;
    margin-top: 50px;
    margin-bottom: 0;
}

.ai-clinic-container {
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    background: linear-gradient(135deg, #0b1220, #020617);
    border-radius: 28px;
    padding: 2px;
    box-shadow: 0 20px 40px rgba(0,0,0,0.3);
    margin: 0 0 30px 0;
}

.ai-clinic-card {
    background: #020617;
    border-radius: 26px;
    padding: 30px;
}

.ai-clinic-card h1 {
    text-align: center;
    margin: 0 0 10px 0;
    font-size: 1.8rem;
    background: linear-gradient(90deg, #22d3ee, #2dd4bf);
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
}

.ai-clinic-card .subtitle {
    text-align: center;
    color: #94a3b8;
    margin: 0 0 25px 0;
    font-size: 0.95rem;
}

.ai-clinic-card textarea {
    width: 100%;
    min-height: 140px;
    padding: 16px;
    border-radius: 18px;
    border: 1px solid #1e293b;
    background: #020617;
    color: #e5e7eb;
    font-size: 1rem;
    font-family: inherit;
    resize: vertical;
}

.ai-clinic-card textarea::placeholder {
    color: #64748b;
}

.ai-clinic-card .btn-analyze {
    width: 100%;
    margin-top: 20px;
    padding: 14px;
    border-radius: 18px;
    border: none;
    background: linear-gradient(90deg, #22d3ee, #2dd4bf);
    color: #020617;
    font-size: 1rem;
    font-weight: 700;
    cursor: pointer;
    transition: opacity 0.2s;
}

.ai-clinic-card .btn-analyze:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

.ai-extra-buttons {
    display: flex;
    gap: 12px;
    margin-top: 15px;
    flex-wrap: wrap;
}

.ai-extra-buttons button,
.ai-extra-buttons a {
    padding: 10px 18px;
    border-radius: 40px;
    border: none;
    cursor: pointer;
    font-weight: 600;
    font-size: 0.85rem;
    text-decoration: none;
    display: inline-block;
    text-align: center;
}

.ai-voice-btn {
    background: #10b981;
    color: #020617;
}

.ai-email-btn {
    background: #047857;
    color: white;
}

.ai-response-box {
    margin-top: 25px;
    padding: 20px;
    border-radius: 20px;
    border: 1px solid #1e293b;
    display: none;
    line-height: 1.7;
    color: #e5e7eb;
    background: #020617;
    max-height: 400px;
    overflow-y: auto;
}

.ai-disclaimer {
    margin-top: 20px;
    font-size: 0.7rem;
    color: #64748b;
    text-align: center;
}

/* BMI Calculator Section */
.bmi-section, .heartrate-section, .mental-section {
    background: #0f172a;
    border-radius: 20px;
    padding: 20px;
    margin-top: 25px;
}

.bmi-section h3, .heartrate-section h3, .mental-section h3 {
    color: #fbbf24;
    margin-bottom: 15px;
    font-size: 1.2rem;
}

.bmi-section input, .heartrate-section input {
    padding: 10px 14px;
    margin: 5px;
    border-radius: 12px;
    border: 1px solid #1e293b;
    width: 130px;
    background: #020617;
    color: #fef3c7;
}

.bmi-section button, .heartrate-section button, .mental-section button {
    padding: 10px 20px;
    border-radius: 12px;
    border: none;
    background: #0284c7;
    color: white;
    font-weight: 600;
    cursor: pointer;
}

.result-text {
    margin-top: 15px;
    font-size: 0.9rem;
    color: #fde68a;
}

/* Music Therapy Section */
.music-section {
    background: #0f172a;
    border-radius: 20px;
    padding: 20px;
    margin-top: 25px;
    text-align: center;
}

.music-section h3 {
    color: #38bdf8;
    margin-bottom: 8px;
}

.music-section select {
    padding: 8px 14px;
    margin-bottom: 15px;
    border-radius: 12px;
    border: 1px solid #1e293b;
    background: #020617;
    color: #fef3c7;
    font-size: 14px;
}

.music-section iframe {
    width: 100%;
    border-radius: 14px;
}

/* Digital Tools Grid */
.digital-tools {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
    margin-top: 25px;
}

/* Health Education Videos */
.edu-section {
    margin-top: 30px;
}

.edu-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-top: 20px;
}

.edu-card {
    background: #0f172a;
    border-radius: 18px;
    padding: 15px;
}

.edu-card iframe {
    width: 100%;
    height: 160px;
    border-radius: 14px;
    border: none;
}

.edu-card h4 {
    color: #fbbf24;
    margin: 10px 0 5px;
    font-size: 0.95rem;
}

.edu-card p {
    font-size: 0.85rem;
    color: #cbd5f5;
}

/* Responsive */
@media (max-width: 768px) {
    .ai-clinic-card { padding: 20px; }
    .ai-clinic-card h1 { font-size: 1.4rem; }
    .digital-tools { grid-template-columns: 1fr; }
    .edu-grid { grid-template-columns: 1fr; }
}
</style>

<div class="ai-clinic-wrapper">
    <div class="ai-clinic-container">
        <div class="ai-clinic-card">
            <h1>🏥 AI Clinical Assistant</h1>
            <p class="subtitle">Describe your symptoms for a preliminary AI-powered health assessment</p>

            <textarea id="aiSymptoms" placeholder="Example: I have fever, headache, and fatigue for 2 days..."></textarea>

            <div class="ai-extra-buttons">
                <button class="ai-voice-btn" id="aiVoiceBtn">🎤 Speak</button>
                <a href="#" id="aiEmailBtn" class="ai-email-btn">📧 Email AI Response</a>
            </div>

            <button class="btn-analyze" id="aiAnalyzeBtn">Analyze Symptoms</button>
            <div id="aiResponse" class="ai-response-box"></div>
            <div class="ai-disclaimer">
                ⚕️ Dr. Fulgent AI provides general information only. Always consult a qualified healthcare provider for medical advice.
            </div>

            <!-- Digital Healthcare Tools -->
            <div class="digital-tools">
                <!-- BMI Calculator -->
                <div class="bmi-section">
                    <h3>📊 BMI Calculator</h3>
                    <input type="number" id="bmiWeight" placeholder="Weight (kg)">
                    <input type="number" id="bmiHeight" placeholder="Height (cm)">
                    <button onclick="calculateBMI()">Calculate</button>
                    <div id="bmiResult" class="result-text"></div>
                </div>

                <!-- Heart Rate Tracker -->
                <div class="heartrate-section">
                    <h3>❤️ Heart Rate Tracker</h3>
                    <input type="number" id="heartRateInput" placeholder="Enter BPM">
                    <button onclick="checkHeartRate()">Check</button>
                    <div id="heartRateResult" class="result-text"></div>
                </div>

                <!-- Mental Wellness Check -->
                <div class="mental-section">
                    <h3>🧠 Mental Wellness Check</h3>
                    <button onclick="startMentalCheck()">Start Self-Assessment</button>
                    <div id="mentalResult" class="result-text"></div>
                </div>
            </div>

            <!-- Music Therapy -->
            <div class="music-section">
                <h3>🎵 Music Therapy & Wellness Lounge</h3>
                <p style="color: #94a3b8; font-size: 0.85rem; margin-bottom: 12px;">Choose a calming track for relaxation, stress relief, or sleep</p>
                <select id="musicMode">
                    <option value="ambient">🌿 Relaxing Ambient - Stress Relief</option>
                    <option value="sleep">😴 Soothing Lullaby - Sleep Music</option>
                </select>
                <div id="musicEmbed">
                    <iframe id="ytPlayer" width="100%" height="200" src="https://www.youtube.com/embed/mDM3SPBjSmw?autoplay=0&loop=1&playlist=mDM3SPBjSmw" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
                </div>
                <p style="margin-top: 12px; font-size: 12px; color: #64748b;">💡 Tip: Use headphones and close your eyes for best effect</p>
            </div>

            <!-- Health Education Videos -->
            <div class="edu-section">
                <h3 style="color: #fbbf24; margin-bottom: 15px;">📚 Health Education Library</h3>
                <div class="edu-grid">
                    <div class="edu-card">
                        <iframe src="https://www.youtube.com/embed/HPcIqVNZ_os" frameborder="0" allowfullscreen></iframe>
                        <h4>Understanding Hypertension</h4>
                        <p>Learn about causes, prevention, and management of high blood pressure</p>
                    </div>
                    <div class="edu-card">
                        <iframe src="https://www.youtube.com/embed/2R6SsqC9VN8" frameborder="0" allowfullscreen></iframe>
                        <h4>Diabetes Management</h4>
                        <p>Essential tips for managing blood sugar and living well with diabetes</p>
                    </div>
                    <div class="edu-card">
                        <iframe src="https://www.youtube.com/embed/rMHusZk9P7E" frameborder="0" allowfullscreen></iframe>
                        <h4>Mental Health Awareness</h4>
                        <p>Understanding anxiety, depression, and self-care strategies</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// ================= AI ANALYSIS =================
const analyzeBtn = document.getElementById("aiAnalyzeBtn");
const symptomsInput = document.getElementById("aiSymptoms");
const responseBox = document.getElementById("aiResponse");
const emailBtn = document.getElementById("aiEmailBtn");

analyzeBtn.onclick = async () => {
    const symptoms = symptomsInput.value.trim();
    if (!symptoms) {
        alert("Please describe your symptoms.");
        return;
    }

    analyzeBtn.disabled = true;
    analyzeBtn.textContent = "Analyzing...";
    responseBox.style.display = "block";
    responseBox.innerHTML = "🩺 Processing your symptoms securely...";

    try {
        const res = await fetch("/api/ai_assistant.php", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ symptoms: symptoms })
        });
        const data = await res.json();
        
        let text = "";
        if (typeof data === "string") text = data;
        else if (data?.choices?.[0]?.message?.content) text = data.choices[0].message.content;
        else if (data?.error?.message) text = "⚠️ " + data.error.message;
        else text = "Unable to analyze at this moment. Please try again.";

        responseBox.innerHTML = text.replace(/\n/g, "<br>");
        emailBtn.href = `mailto:fdchelp@fulgentdigit.com.ng?subject=AI Health Report&body=${encodeURIComponent(text)}`;
    } catch (e) {
        responseBox.innerHTML = "❌ Server error. Please try again later.";
    }

    analyzeBtn.disabled = false;
    analyzeBtn.textContent = "Analyze Symptoms";
};

// ================= VOICE RECOGNITION =================
if ('webkitSpeechRecognition' in window) {
    document.getElementById("aiVoiceBtn").onclick = () => {
        const recognition = new webkitSpeechRecognition();
        recognition.lang = "en-US";
        recognition.start();
        recognition.onresult = (event) => {
            symptomsInput.value = event.results[0][0].transcript;
        };
    };
} else {
    document.getElementById("aiVoiceBtn").onclick = () => alert("Speech recognition not supported in this browser.");
}

// ================= BMI CALCULATOR =================
function calculateBMI() {
    const weight = parseFloat(document.getElementById('bmiWeight').value);
    const heightCm = parseFloat(document.getElementById('bmiHeight').value);
    if (!weight || !heightCm) {
        document.getElementById('bmiResult').textContent = "Please enter valid numbers.";
        return;
    }
    const heightM = heightCm / 100;
    const bmi = (weight / (heightM * heightM)).toFixed(1);
    let category = "";
    if (bmi < 18.5) category = "Underweight";
    else if (bmi < 25) category = "Normal weight";
    else if (bmi < 30) category = "Overweight";
    else category = "Obese";
    document.getElementById('bmiResult').textContent = `📊 Your BMI: ${bmi} (${category})`;
}

// ================= HEART RATE CHECK =================
function checkHeartRate() {
    const bpm = parseInt(document.getElementById('heartRateInput').value);
    if (!bpm) {
        document.getElementById('heartRateResult').textContent = "Enter a valid BPM.";
        return;
    }
    let status = "";
    if (bpm < 60) status = "Below normal (Bradycardia)";
    else if (bpm <= 100) status = "Normal range";
    else status = "Above normal (Tachycardia)";
    document.getElementById('heartRateResult').textContent = `❤️ Heart Rate: ${bpm} BPM - ${status}`;
}

// ================= MENTAL HEALTH CHECK =================
function startMentalCheck() {
    const questions = [
        "Have you felt down or hopeless recently?",
        "Have you lost interest in activities you enjoy?",
        "Do you feel anxious or restless often?",
        "Do you have trouble sleeping or concentrating?",
        "Have you felt fatigued or low energy?"
    ];
    let score = 0;
    for (let i = 0; i < questions.length; i++) {
        if (confirm(questions[i] + " (OK = Yes, Cancel = No)")) score++;
    }
    let result = "";
    if (score <= 1) result = "🧘 Low stress - Keep up healthy habits";
    else if (score <= 3) result = "⚠️ Moderate stress - Consider coping strategies";
    else result = "🆘 High stress - Consider professional support";
    document.getElementById('mentalResult').innerHTML = `📋 Your score: ${score}/5 - ${result}`;
}

// ================= MUSIC THERAPY =================
const musicSelect = document.getElementById("musicMode");
const player = document.getElementById("ytPlayer");

musicSelect.addEventListener("change", () => {
    if (musicSelect.value === "ambient") {
        player.src = "https://www.youtube.com/embed/mDM3SPBjSmw?autoplay=0&loop=1&playlist=mDM3SPBjSmw";
    } else {
        player.src = "https://www.youtube.com/embed/2SmUkXtQIPc?autoplay=0&loop=1&playlist=2SmUkXtQIPc";
    }
});
</script>
<!-- ========== UHD UNIVERSAL FOOTER ========== -->
<style>
.uhd-footer {
    background: linear-gradient(135deg, #0a3d2f, #064e3b);
    color: white;
    margin-top: 50px;
    padding: 40px 20px 20px;
    border-top: 3px solid #dc3545;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.uhd-footer-container {
    max-width: 1200px;
    margin: 0 auto;
}
.uhd-footer-row {
    display: flex;
    flex-wrap: wrap;
    gap: 30px;
    justify-content: space-between;
}
.uhd-footer-col {
    flex: 1;
    min-width: 180px;
}
.uhd-footer h5 {
    color: #d4a017;
    font-weight: 700;
    margin-bottom: 15px;
    font-size: 1rem;
}
.uhd-footer p {
    color: rgba(255,255,255,0.7);
    font-size: 0.8rem;
    line-height: 1.6;
}
.uhd-footer-links {
    list-style: none;
    padding-left: 0;
}
.uhd-footer-links li {
    margin-bottom: 8px;
}
.uhd-footer-links a {
    color: rgba(255,255,255,0.7);
    text-decoration: none;
    font-size: 0.8rem;
    transition: all 0.2s;
}
.uhd-footer-links a:hover {
    color: #d4a017;
    padding-left: 5px;
}
.uhd-social-icons {
    margin-top: 15px;
}
.uhd-social-icon {
    width: 35px;
    height: 35px;
    background: rgba(255,255,255,0.1);
    border-radius: 50%;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    margin-right: 8px;
    transition: all 0.3s;
    color: white;
    text-decoration: none;
    font-size: 16px;
}
.uhd-social-icon:hover {
    background: #d4a017;
    transform: translateY(-3px);
    color: #0a3d2f;
}
.uhd-contact-info {
    margin-bottom: 10px;
    color: rgba(255,255,255,0.7);
    font-size: 0.8rem;
}
.uhd-contact-info i {
    width: 25px;
    color: #d4a017;
}
.uhd-footer-bottom {
    border-top: 1px solid rgba(255,255,255,0.1);
    padding-top: 20px;
    margin-top: 30px;
    text-align: center;
    font-size: 0.7rem;
    color: rgba(255,255,255,0.5);
}
@media (max-width: 768px) {
    .uhd-footer-row {
        flex-direction: column;
        text-align: center;
        gap: 25px;
    }
    .uhd-social-icon {
        margin: 0 5px;
    }
}
</style>

<footer class="uhd-footer">
    <div class="uhd-footer-container">
        <div class="uhd-footer-row">
            <div class="uhd-footer-col">
                <h5>🏥 Unity Healthcare DB</h5>
                <p>Nigeria's integrated health data platform connecting patients, doctors, hospitals, and administrators in one seamless healthcare ecosystem.</p>
                <div class="uhd-social-icons">
                    <a href="#" class="uhd-social-icon">📘</a>
                    <a href="#" class="uhd-social-icon">🐦</a>
                    <a href="#" class="uhd-social-icon">🔗</a>
                    <a href="#" class="uhd-social-icon">📷</a>
                </div>
            </div>
            <div class="uhd-footer-col">
                <h5>Quick Links</h5>
                <ul class="uhd-footer-links">
                    <li><a href="/index.php">🏠 Home</a></li>
                    <li><a href="/patient/dashboard.php">📊 Dashboard</a></li>
                    <li><a href="/patient/medical/index.php">🏥 Medical Hub</a></li>
                    <li><a href="/patient/hps/dashboard.php">🛡️ HPS Protection</a></li>
                </ul>
            </div>
            <div class="uhd-footer-col">
                <h5>Support</h5>
                <ul class="uhd-footer-links">
                    <li><a href="/about.php">📖 About Us</a></li>
                    <li><a href="/contact.php">📧 Contact</a></li>
                    <li><a href="/privacy.php">🔒 Privacy Policy</a></li>
                    <li><a href="/terms.php">📜 Terms of Service</a></li>
                </ul>
            </div>
            <div class="uhd-footer-col">
                <h5>Contact Us</h5>
                <div class="uhd-contact-info"><i>📞</i> +234 708 936 4492</div>
                <div class="uhd-contact-info"><i>✉️</i> support@uhd.com.ng</div>
                <div class="uhd-contact-info"><i>🕒</i> 24/7 Available</div>
            </div>
        </div>
        <div class="uhd-footer-bottom">
            <p>&copy; 2024-2026 Unity Healthcare Database. All rights reserved. | Powered by Fulgent Digital Clinic</p>
        </div>
    </div>
</footer>