  <?php
require_once __DIR__ . '/../../api/lib.php';
hw_require_auth(['client']);
$authUser = hw_get_auth_user();

// CHECK MEMBERSHIP FIRST - BEFORE ANYTHING ELSE
$db = hw_db();
$membershipStmt = $db->prepare("
    SELECT id, plan_type, expires_at 
    FROM user_memberships 
    WHERE user_id = ? AND status = 'active' AND expires_at > NOW()
    ORDER BY expires_at DESC
    LIMIT 1
");
$membershipStmt->execute([$authUser['id']]);
$activeMembership = $membershipStmt->fetch(PDO::FETCH_ASSOC);

// If no active membership, redirect to plan selection immediately
if (!$activeMembership) {
    header('Location: /files/atasteofafricanmarketplace/dashboard/user/choose-plan.php');
    exit;
}

$page_title = 'My Wellness Dashboard | Herbal Wellness Care';
$page_description = 'Client portal and dashboard';
$page_content = function () use ($authUser) {
$db = hw_db();

// Get client's appointments
$upcomingStmt = $db->prepare("
    SELECT a.*, c.display_name as coach_name, u.first_name as coach_first_name
    FROM appointments a
    LEFT JOIN coaches c ON a.coach_id = c.id
    LEFT JOIN users u ON c.user_id = u.id
    WHERE a.user_id = ? AND a.status = 'scheduled' AND a.starts_at > NOW()
    ORDER BY a.starts_at ASC
    LIMIT 5
");
$upcomingStmt->execute([$authUser['id']]);
$upcomingAppointments = $upcomingStmt->fetchAll(PDO::FETCH_ASSOC);

// Debug: Check appointment count
error_log("User ID: " . $authUser['id'] . " has " . count($upcomingAppointments) . " upcoming appointments");

// Get stats
$statsStmt = $db->prepare("
    SELECT 
        COUNT(*) as total_appointments,
        SUM(CASE WHEN status = 'scheduled' THEN 1 ELSE 0 END) as upcoming,
        SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed
    FROM appointments 
    WHERE user_id = ?
");
$statsStmt->execute([$authUser['id']]);
$stats = $statsStmt->fetch(PDO::FETCH_ASSOC);

// Get pending invoices
$invoicesStmt = $db->prepare("
    SELECT SUM(total_amount) as pending_amount, COUNT(*) as pending_count
    FROM invoices
    WHERE user_id = ? AND status = 'pending'
");
$invoicesStmt->execute([$authUser['id']]);
$invoices = $invoicesStmt->fetch(PDO::FETCH_ASSOC);

// Get intake data for personalization
$intakeStmt = $db->prepare("SELECT data FROM intake_forms WHERE user_id = ? ORDER BY created_at DESC LIMIT 1");
$intakeStmt->execute([$authUser['id']]);
$intakeData = $intakeStmt->fetch();
$intake = $intakeData ? json_decode($intakeData['data'], true) : null;

// Get recent activity
$activityStmt = $db->prepare("
    SELECT 'appointment' as type, 'Completed session' as action, starts_at as created_at
    FROM appointments WHERE user_id = ? AND status = 'completed'
    UNION ALL
    SELECT 'order' as type, 'Made purchase' as action, created_at
    FROM orders WHERE user_id = ?
    ORDER BY created_at DESC LIMIT 5
");
$activityStmt->execute([$authUser['id'], $authUser['id']]);
$recentActivity = $activityStmt->fetchAll(PDO::FETCH_ASSOC);

// Initialize wellness score placeholder (will be loaded via API)
$wellnessScore = null;

?>
<style>
  nav.fixed { 
    display: none !important; 
    visibility: hidden !important;
    position: absolute !important;
    pointer-events: none !important;
    z-index: -1 !important;
  }
  body > nav { 
    display: none !important; 
    visibility: hidden !important;
  }
  main.pt-20 { padding-top: 0 !important; }
  body {
    padding-top: 0 !important;
  }
</style>
<link rel="stylesheet" href="/files/atasteofafricanmarketplace/assets/dashboard.css">

<div class="dashboard-container">
  <!-- Sidebar -->
  <div class="dashboard-sidebar">
    <div class="sidebar-header">
      <div class="sidebar-profile">
        <div class="profile-avatar">
          <?= strtoupper(substr($authUser['first_name'], 0, 1) . substr($authUser['last_name'], 0, 1)) ?>
        </div>
        <div class="profile-info">
          <h3><?= htmlspecialchars($authUser['first_name'] . ' ' . $authUser['last_name']) ?></h3>
          <p>Wellness Member</p>
          <?php 
          $planDisplay = ucfirst($activeMembership['plan_type'] ?? 'Personal');
          $planColor = ($activeMembership['plan_type'] ?? 'personal') === 'family' ? '#d4ad31' : '#0f5240';
          $planIcon = ($activeMembership['plan_type'] ?? 'personal') === 'family' ? '👨‍👩‍👧‍👦' : '👤';
          ?>
          <div style="margin-top: 8px; display: inline-block; background: <?= $planColor ?>; color: white; padding: 4px 12px; border-radius: 12px; font-size: 11px; font-weight: 600;">
            <?= $planIcon ?> <?= $planDisplay ?> Plan
          </div>
        </div>
      </div>
    </div>
    <nav class="sidebar-nav">
      <a href="/files/atasteofafricanmarketplace/dashboard/user/index.php" class="active"><i class="fas fa-home"></i>Home</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/appointments.php"><i class="fas fa-calendar-check"></i>Appointments</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/messages.php"><i class="fas fa-comments"></i>Messages</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/records.php"><i class="fas fa-file-medical"></i>Records</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/profile.php"><i class="fas fa-user"></i>Profile & Support</a>
      <hr class="sidebar-divider">
      <a href="/files/atasteofafricanmarketplace/store.php"><i class="fas fa-store"></i>Wellness Store</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/membership.php"><i class="fas fa-crown"></i>My Membership</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/billing.php"><i class="fas fa-file-invoice-dollar"></i>Billing</a>
      <hr class="sidebar-divider">
      <a href="/files/atasteofafricanmarketplace/index.php"><i class="fas fa-arrow-left"></i>Back to Home</a>
    </nav>
    <div class="sidebar-footer">
      <a href="/files/atasteofafricanmarketplace/api/auth/logout.php" style="display: flex; align-items: center; gap: 12px; color: rgba(255,255,255,0.7); text-decoration: none; font-size: 13px; font-weight: 500; padding: 10px 0; border-top: 1px solid rgba(212, 173, 49, 0.15); transition: all 0.3s;"><i class="fas fa-sign-out-alt"></i>Sign Out</a>
    </div>
  </div>

  <!-- Main Content -->
  <div class="dashboard-content">
    <main>
      <!-- Header -->
      <div class="dashboard-header">
        <h1>Welcome Back, <?= htmlspecialchars($authUser['first_name']) ?>!</h1>
        <p style="font-size: 16px; color: var(--slate-600);">Your wellness journey continues here</p>
      </div>

      <!-- Stats Cards -->
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-header">
            <span class="stat-label">Wellness Score</span>
            <i class="fas fa-heartbeat stat-icon" style="color: #0f5240;"></i>
          </div>
          <div id="wellnessScoreDisplay" class="stat-value" style="min-height: 48px; display: flex; align-items: center; justify-content: center;">
            <i class="fas fa-spinner fa-spin"></i>
          </div>
          <a href="#wellness-breakdown" class="stat-link" style="color: #0f5240;">View Breakdown →</a>
        </div>

        <div class="stat-card">
          <div class="stat-header">
            <span class="stat-label">Upcoming Sessions</span>
            <i class="fas fa-calendar-check stat-icon" style="color: #d4ad31;"></i>
          </div>
          <div class="stat-value"><?= $stats['upcoming'] ?></div>
          <a href="/files/atasteofafricanmarketplace/dashboard/user/appointments.php" class="stat-link" style="color: #d4ad31;">View All →</a>
        </div>

        <div class="stat-card">
          <div class="stat-header">
            <span class="stat-label">Completed Sessions</span>
            <i class="fas fa-check-circle stat-icon" style="color: #0f5240;"></i>
          </div>
          <div class="stat-value"><?= $stats['completed'] ?></div>
          <a href="/files/atasteofafricanmarketplace/dashboard/user/appointments.php" class="stat-link" style="color: #a855f7;">View History →</a>
        </div>

        <div class="stat-card">
          <div class="stat-header">
            <span class="stat-label">Pending Invoices</span>
            <i class="fas fa-file-invoice stat-icon" style="color: #f59e0b;"></i>
          </div>
          <div class="stat-value"><?= $invoices['pending_count'] ?? 0 ?></div>
          <?php if (($invoices['pending_amount'] ?? 0) > 0): ?>
            <p style="font-size: 12px; color: var(--gray-600); margin: 0;">$<?= number_format($invoices['pending_amount'], 2) ?></p>
          <?php endif; ?>
          <a href="/files/atasteofafricanmarketplace/dashboard/user/billing.php" class="stat-link" style="color: #d4ad31;">View Billing →</a>
        </div>
      </div>

      <!-- Health Overview Section -->
      <div style="background: white; padding: 32px; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-bottom: 32px;">
        <h2 style="font-size: 24px; color: #0b3d2e; margin: 0 0 24px 0; display: flex; align-items: center; gap: 12px;">
          <i class="fas fa-heartbeat" style="color: #0f5240;"></i>
          Your Health Overview
        </h2>
        
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 24px;">
          <!-- Current Medications -->
          <div style="background: #f0f9f6; padding: 20px; border-radius: 12px; border-left: 4px solid #0f5240;">
            <h3 style="font-size: 16px; color: #0b3d2e; margin: 0 0 16px 0; display: flex; align-items: center; gap: 8px;">
              <i class="fas fa-pills"></i>
              Current Medications
            </h3>
            <div id="medicationsList" style="display: flex; flex-direction: column; gap: 12px;">
              <div style="color: #64748b; font-size: 14px;">
                <i class="fas fa-spinner fa-spin"></i> Loading...
              </div>
            </div>
            <button onclick="addMedication()" style="margin-top: 12px; background: none; border: 1px dashed #0f5240; color: #0f5240; padding: 8px 16px; border-radius: 6px; cursor: pointer; font-size: 13px; font-weight: 600; width: 100%;">
              <i class="fas fa-plus"></i> Add Medication
            </button>
          </div>
          
          <!-- Allergies -->
          <div style="background: #fef9e7; padding: 20px; border-radius: 12px; border-left: 4px solid #d4ad31;">
            <h3 style="font-size: 16px; color: #0b3d2e; margin: 0 0 16px 0; display: flex; align-items: center; gap: 8px;">
              <i class="fas fa-exclamation-triangle"></i>
              Allergies
            </h3>
            <div id="allergiesList" style="display: flex; flex-direction: column; gap: 12px;">
              <div style="color: #64748b; font-size: 14px;">
                <i class="fas fa-spinner fa-spin"></i> Loading...
              </div>
            </div>
            <button onclick="addAllergy()" style="margin-top: 12px; background: none; border: 1px dashed #d4ad31; color: #c9a227; padding: 8px 16px; border-radius: 6px; cursor: pointer; font-size: 13px; font-weight: 600; width: 100%;">
              <i class="fas fa-plus"></i> Add Allergy
            </button>
          </div>
          
          <!-- Recent Vitals -->
          <div style="background: #faf5ff; padding: 20px; border-radius: 12px; border-left: 4px solid #7c3aed;">
            <h3 style="font-size: 16px; color: #0b3d2e; margin: 0 0 16px 0; display: flex; align-items: center; gap: 8px;">
              <i class="fas fa-heart"></i>
              Recent Vitals
            </h3>
            <div id="vitalsList" style="display: flex; flex-direction: column; gap: 10px;">
              <div style="display: flex; justify-content: space-between; font-size: 14px;">
                <span style="color: #64748b;">Blood Pressure:</span>
                <span style="color: #0b3d2e; font-weight: 600;">--/--</span>
              </div>
              <div style="display: flex; justify-content: space-between; font-size: 14px;">
                <span style="color: #64748b;">Heart Rate:</span>
                <span style="color: #0b3d2e; font-weight: 600;">-- bpm</span>
              </div>
              <div style="display: flex; justify-content: space-between; font-size: 14px;">
                <span style="color: #64748b;">Weight:</span>
                <span style="color: #0b3d2e; font-weight: 600;">-- kg</span>
              </div>
            </div>
            <a href="#health-data" style="display: block; margin-top: 12px; color: #7c3aed; font-size: 13px; font-weight: 600; text-decoration: none;">
              Update vitals <i class="fas fa-arrow-right"></i>
            </a>
          </div>
        </div>
      </div>

      <!-- Wellness Breakdown Section -->
      <div id="wellness-breakdown" style="background: white; padding: 24px; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-bottom: 24px;">
        <div style="display: flex; align-items: center; justify-content: center; height: 150px;">
          <i class="fas fa-spinner fa-spin"></i> Loading wellness breakdown...
        </div>
      </div>

      <!-- Quick Actions, Video, and Notifications Grid -->
      <div class="action-grid">
        <!-- Quick Actions -->
        <div class="action-card">
          <h3>Quick Actions</h3>
          <div class="action-buttons">
            <a href="/files/atasteofafricanmarketplace/all-coaches.php" class="action-btn action-btn-emerald">
              <i class="fas fa-calendar-plus"></i>Book Session
            </a>
            <a href="/files/atasteofafricanmarketplace/store.php" class="action-btn action-btn-ochre">
              <i class="fas fa-store"></i>Browse Store
            </a>
            <a href="/files/atasteofafricanmarketplace/index.php#tree" class="action-btn action-btn-emerald">
              <i class="fas fa-tree"></i>Tree of Life
            </a>
            <a href="/files/atasteofafricanmarketplace/dashboard/user/profile.php" class="action-btn action-btn-purple">
              <i class="fas fa-user-edit"></i>My Profile
            </a>
          </div>
        </div>

        <!-- Video Session -->
        <div class="action-card">
          <h3><i class="fas fa-video"></i>Video Session</h3>
          <p class="action-card-description">Join your scheduled video session or start a call with your coach.</p>
          <div class="action-buttons">
            <button onclick="joinNextSession()" class="action-btn action-btn-emerald">
              <i class="fas fa-video"></i>Join Next Session
            </button>
            <button onclick="callCoach()" class="action-btn action-btn-ochre">
              <i class="fas fa-phone"></i>Call My Coach
            </button>
          </div>
          <p class="form-hint">You must have a scheduled appointment to join a session.</p>
        </div>

        <!-- Notifications -->
        <div class="action-card">
          <h3><i class="fas fa-bell"></i>Notifications <span class="action-card-badge" id="notificationBadge">0</span></h3>
          <div id="notificationsContainer" style="display: flex; flex-direction: column; gap: 12px;">
            <div style="text-align: center; color: var(--muted); padding: 20px; font-size: 14px;">
              <i class="fas fa-spinner fa-spin"></i> Loading notifications...
            </div>
          </div>
        </div>
      </div>

      <!-- Personalized Recommendations -->
      <?php if ($intake): ?>
      <div class="content-section">
        <h2 class="section-title"><i class="fas fa-lightbulb" style="color: #eab308;"></i>Personalized Recommendations</h2>
        <div class="recommendations-grid">
          <?php if (($intake['stressLevel'] ?? 0) > 7): ?>
          <div class="recommendation-card" style="background-color: #faf5ff; border-color: #e9d5ff;">
            <h4 style="color: #7c3aed;">🧘 Stress Management</h4>
            <p style="color: #6d28d9;">Try meditation or lavender aromatherapy to reduce stress levels.</p>
          </div>
          <?php endif; ?>
          
          <?php if (($intake['sleepHours'] ?? 0) < 7): ?>
          <div class="recommendation-card" style="background-color: #eff6ff; border-color: #bfdbfe;">
            <h4 style="color: #1e40af;">😴 Better Sleep</h4>
            <p style="color: #1e3a8a;">Consider chamomile tea and a consistent bedtime routine.</p>
          </div>
          <?php endif; ?>
          
          <?php if (empty($intake['exercise'])): ?>
          <div class="recommendation-card" style="background-color: #f0fdf4; border-color: #bbf7d0;">
            <h4 style="color: #166534;">🏃 Stay Active</h4>
            <p style="color: #15803d;">Start with 15-minute daily walks to boost your energy.</p>
          </div>
          <?php endif; ?>
          
          <?php if (in_array('vegetarian', $intake['diet'] ?? [])): ?>
          <div class="recommendation-card" style="background-color: #f0fdf4; border-color: #a7f3d0;">
            <h4 style="color: #065f46;">🌱 Plant-Based Nutrition</h4>
            <p style="color: #047857;">Explore our vegetarian herbal supplements for optimal health.</p>
          </div>
          <?php endif; ?>
        </div>
        
        <!-- Coach Recommendations -->
        <div id="coachRecommendationsSection" style="margin-top: 24px; display: none;">
          <h3 style="font-size: 18px; color: var(--forest); margin-bottom: 16px;">
            <i class="fas fa-star" style="color: #f59e0b;"></i> Coach Recommendations
          </h3>
          <div id="coachRecommendationsContainer" style="display: grid; gap: 16px;">
            <div style="text-align: center; color: var(--muted); padding: 20px;">Loading coach insights...</div>
          </div>
        </div>
      </div>
      <?php endif; ?>

      <!-- Health Data & Session Notes Section -->
      <div class="content-section" id="health-data">
        <h2 class="section-title"><i class="fas fa-notes-medical" style="color: #059669;"></i>Health Data & Session Notes</h2>
        <form id="healthDataForm">
          <div class="form-grid">
            <div class="form-group">
              <label class="form-label">Blood Pressure</label>
              <input type="text" name="blood_pressure" class="form-input" placeholder="e.g. 120/80" />
            </div>
            <div class="form-group">
              <label class="form-label">Heart Rate (bpm)</label>
              <input type="number" name="heart_rate" class="form-input" placeholder="e.g. 72" />
            </div>
            <div class="form-group">
              <label class="form-label">Sleep Hours</label>
              <input type="number" step="0.1" name="sleep_hours" class="form-input" placeholder="e.g. 7.5" />
            </div>
            <div class="form-group">
              <label class="form-label">Weight (kg)</label>
              <input type="number" step="0.1" name="weight" class="form-input" placeholder="e.g. 65" />
            </div>
          </div>
          <div class="form-group">
            <label class="form-label">Session Notes for Coach</label>
            <textarea name="session_notes" class="form-textarea" placeholder="Share updates, symptoms, or questions for your coach..."></textarea>
          </div>
          <button type="submit" class="form-submit">
            <i class="fas fa-save"></i> Save & Share
          </button>
        </form>
        <div id="healthDataStatus" class="form-status"></div>
        <p class="form-hint">This information will be visible to your coach for better care and recommendations.</p>
      </div>

      <!-- Medical Report Upload Section -->
      <div class="content-section">
        <h2 class="section-title"><i class="fas fa-file-medical" style="color: #059669;"></i>Upload Medical Report</h2>
        <form id="medicalReportForm" enctype="multipart/form-data" style="display: flex; gap: 16px; flex-wrap: wrap; align-items: flex-end;">
          <div class="form-group" style="flex: 1; min-width: 200px;">
            <label class="form-label">Select File</label>
            <input type="file" name="report" accept=".pdf,.jpg,.jpeg,.png,.csv,.txt" required class="form-input" />
          </div>
          <button type="submit" class="form-submit" style="margin: 0;">
            <i class="fas fa-upload"></i> Upload
          </button>
        </form>
        <div id="uploadStatus" class="form-status"></div>
        <p class="form-hint">Supported formats: PDF, JPG, PNG, CSV, TXT</p>
      </div>

      <!-- Upcoming Appointments -->
      <div class="content-section">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
          <h2 class="section-title" style="margin: 0;">Upcoming Appointments</h2>
          <a href="/files/atasteofafricanmarketplace/all-coaches.php" style="color: #059669; font-size: 14px; font-weight: 600; text-decoration: none;">
            <i class="fas fa-plus"></i> Book New →
          </a>
        </div>
        <?php if (empty($upcomingAppointments)): ?>
          <div class="empty-state">
            <div class="empty-state-icon">📅</div>
            <p class="empty-state-text">No upcoming appointments</p>
            <a href="/files/atasteofafricanmarketplace/all-coaches.php" class="empty-state-button">
              Book Your First Session
            </a>
          </div>
        <?php else: ?>
          <div class="appointment-list">
            <?php foreach ($upcomingAppointments as $appt): 
              $startTime = new DateTime($appt['starts_at']);
              $isToday = $startTime->format('Y-m-d') === date('Y-m-d');
            ?>
              <div class="appointment-item <?= $isToday ? 'today' : '' ?>">
                <div class="appointment-header">
                  <div>
                    <div class="appointment-coach">Session with <?= htmlspecialchars($appt['coach_name']) ?></div>
                    <?php if ($isToday): ?>
                      <span class="appointment-badge">Today</span>
                    <?php endif; ?>
                  </div>
                </div>
                <div class="appointment-details">
                  <div><i class="far fa-calendar"></i><?= $startTime->format('l, F j, Y') ?></div>
                  <div><i class="far fa-clock"></i><?= $startTime->format('g:i A') ?></div>
                </div>
                <div class="appointment-actions">
                  <?php if ($isToday): ?>
                    <button onclick="joinSession(<?= $appt['id'] ?>)" class="appointment-btn join">
                      <i class="fas fa-video"></i>Join
                    </button>
                  <?php endif; ?>
                  <a href="/files/atasteofafricanmarketplace/dashboard/user/appointments.php" class="appointment-btn details">
                    View Details
                  </a>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>

      <!-- Activity Feed -->
      <div class="content-section">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
          <h2 class="section-title" style="margin: 0;">Activity History</h2>
          <a href="/files/atasteofafricanmarketplace/dashboard/user/activity.php" style="color: #059669; font-size: 14px; font-weight: 600; text-decoration: none;">
            <i class="fas fa-history"></i> View All →
          </a>
        </div>
        
        <!-- Activity Type Filter -->
        <div style="display: flex; gap: 12px; margin-bottom: 20px; flex-wrap: wrap;">
          <button onclick="filterActivityType('all')" class="activity-filter-btn active" data-type="all">All Activity</button>
          <button onclick="filterActivityType('appointment')" class="activity-filter-btn" data-type="appointment">Sessions</button>
          <button onclick="filterActivityType('order')" class="activity-filter-btn" data-type="order">Orders</button>
          <button onclick="filterActivityType('health')" class="activity-filter-btn" data-type="health">Health Data</button>
          <button onclick="filterActivityType('document')" class="activity-filter-btn" data-type="document">Documents</button>
        </div>
        
        <!-- Activity List -->
        <div id="activityFeedContainer" style="display: flex; flex-direction: column; gap: 16px;">
          <div style="text-align: center; color: var(--muted); padding: 40px; font-size: 14px;">
            <i class="fas fa-spinner fa-spin"></i> Loading activity...
          </div>
        </div>
        
        <!-- Pagination Controls -->
        <div id="activityPaginationControls" style="display: flex; justify-content: center; gap: 12px; margin-top: 24px;">
        </div>
      </div>

    </main>
  </div>
</div>

<script>
function joinNextSession() {
  // Find the next upcoming appointment and redirect to video session
  fetch('/files/atasteofafricanmarketplace/api/appointments/list.php', { credentials: 'include' })
    .then(res => res.json())
    .then(data => {
      if (data.appointments && data.appointments.length > 0) {
        const next = data.appointments.find(a => a.status === 'scheduled');
        if (next) {
          window.location.href = `/files/atasteofafricanmarketplace/video-session.php?appointment_id=${next.id}`;
        } else {
          alert('No upcoming scheduled sessions found.');
        }
      } else {
        alert('No appointments found.');
      }
    });
}

async function joinSession(appointmentId) {
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/video/start.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ appointment_id: appointmentId })
    });
    const data = await response.json();
    
    if (data.success && data.session_token) {
      window.location.href = `/files/atasteofafricanmarketplace/video-session.php?token=${data.session_token}`;
    } else {
      alert('Failed to join session: ' + (data.message || 'Unknown error'));
    }
  } catch (error) {
    console.error('Error:', error);
    alert('Failed to join video session.');
  }
}

async function callCoach() {
  try {
    const res = await fetch('/files/atasteofafricanmarketplace/api/appointments/list.php', { credentials: 'include' });
    const data = await res.json();
    
    if (data.appointments && data.appointments.length > 0) {
      const next = data.appointments.find(a => a.status === 'scheduled');
      if (next) {
        if (confirm('Start a video call with your coach?')) {
          const videoRes = await fetch('/files/atasteofafricanmarketplace/api/video/start.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ appointment_id: next.id })
          });
          const videoData = await videoRes.json();
          
          if (videoData.success && videoData.session_token) {
            window.location.href = `/files/atasteofafricanmarketplace/video-session.php?token=${videoData.session_token}`;
          } else {
            alert('Failed to start call: ' + (videoData.message || 'Unknown error'));
          }
        }
      } else {
        alert('No coach available for a call.');
      }
    } else {
      alert('No appointments found.');
    }
  } catch (error) {
    console.error('Error:', error);
    alert('Failed to start call.');
  }
}
      }
    });
}

// Health Data Form Submission
document.getElementById('healthDataForm')?.addEventListener('submit', async (e) => {
  e.preventDefault();
  const formData = new FormData(e.target);
  const data = Object.fromEntries(formData);
  
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/users/share-health-data.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify(data)
    });
    const result = await response.json();
    const statusEl = document.getElementById('healthDataStatus');
    if (result.success) {
      statusEl.className = 'form-status success';
      statusEl.textContent = '✓ Health data saved successfully';
      e.target.reset();
    } else {
      statusEl.className = 'form-status error';
      statusEl.textContent = '✗ Error saving health data';
    }
  } catch (err) {
    document.getElementById('healthDataStatus').textContent = 'Error: ' + err.message;
  }
});

// Medical Report Upload
document.getElementById('medicalReportForm')?.addEventListener('submit', async (e) => {
  e.preventDefault();
  const formData = new FormData(e.target);
  
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/users/upload-medical-report.php', {
      method: 'POST',
      credentials: 'include',
      body: formData
    });
    const result = await response.json();
    const statusEl = document.getElementById('uploadStatus');
    if (result.success) {
      statusEl.className = 'form-status success';
      statusEl.textContent = '✓ Medical report uploaded successfully';
      e.target.reset();
    } else {
      statusEl.className = 'form-status error';
      statusEl.textContent = '✗ ' + (result.error || 'Error uploading file');
    }
  } catch (err) {
    document.getElementById('uploadStatus').textContent = 'Error: ' + err.message;
  }
});

// Load notifications
async function loadNotifications() {
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/notifications/dashboard.php', {
      credentials: 'include'
    });
    const data = await response.json();
    
    if (data.success && data.notifications.length > 0) {
      const container = document.getElementById('notificationsContainer');
      const badge = document.getElementById('notificationBadge');
      
      container.innerHTML = '';
      badge.textContent = data.unread_count;
      
      data.notifications.forEach(notif => {
        const bgColor = notif.color + '20';
        const item = document.createElement('div');
        item.className = 'notification-item';
        item.style.backgroundColor = bgColor;
        item.style.borderRadius = '8px';
        item.innerHTML = `
          <i class="${notif.icon}" style="color: ${notif.color};"></i>
          <div class="notification-text">
            <div class="notification-title" style="color: var(--forest);">${notif.title}</div>
            <div class="notification-desc" style="color: var(--ink);">${notif.message}</div>
          </div>
        `;
        container.appendChild(item);
      });
    } else {
      const container = document.getElementById('notificationsContainer');
      container.innerHTML = '<div style="text-align: center; color: var(--muted); padding: 20px; font-size: 14px;">No notifications</div>';
      document.getElementById('notificationBadge').textContent = '0';
    }
  } catch (err) {
    console.error('Error loading notifications:', err);
    document.getElementById('notificationsContainer').innerHTML = '<div style="color: red; font-size: 12px;">Error loading notifications</div>';
  }
}

// Load coach recommendations
async function loadCoachRecommendations() {
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/recommendations/coach.php', {
      credentials: 'include'
    });
    const data = await response.json();
    
    if (data.success && data.recommendations.length > 0) {
      const section = document.getElementById('coachRecommendationsSection');
      const container = document.getElementById('coachRecommendationsContainer');
      
      container.innerHTML = '';
      section.style.display = 'block';
      
      data.recommendations.forEach(rec => {
        const div = document.createElement('div');
        div.style.backgroundColor = '#fffbeb';
        div.style.borderLeft = '4px solid #f59e0b';
        div.style.padding = '16px';
        div.style.borderRadius = '8px';
        div.innerHTML = `
          <div style="color: #b45309; font-weight: 600; margin-bottom: 8px; font-size: 14px;">
            <i class="fas fa-star" style="color: #f59e0b;"></i> Coach Insight
          </div>
          <p style="color: #78350f; margin: 0; font-size: 14px; line-height: 1.5;">${rec.note}</p>
          <div style="color: #a16207; font-size: 12px; margin-top: 8px;">
            From ${rec.display_name || rec.coach_name} • ${new Date(rec.created_at).toLocaleDateString()}
          </div>
        `;
        container.appendChild(div);
      });
    }
  } catch (err) {
    console.error('Error loading coach recommendations:', err);
  }
}

// Countdown timer for upcoming appointments
function initializeCountdown() {
  const countdownEl = document.getElementById('live-countdown');
  if (!countdownEl) return;
  
  const countdownText = countdownEl.innerText;
  const [hours, minutes, seconds] = countdownText.split(':').map(Number);
  let totalSeconds = hours * 3600 + minutes * 60 + seconds;
  
  const interval = setInterval(() => {
    if (totalSeconds <= 0) {
      countdownEl.innerText = '00:00:00';
      countdownEl.style.color = '#ef4444';
      clearInterval(interval);
      return;
    }
    
    totalSeconds--;
    const h = Math.floor(totalSeconds / 3600);
    const m = Math.floor((totalSeconds % 3600) / 60);
    const s = totalSeconds % 60;
    
    countdownEl.innerText = 
      String(h).padStart(2, '0') + ':' + 
      String(m).padStart(2, '0') + ':' + 
      String(s).padStart(2, '0');
  }, 1000);
}

// Test audio functionality
function testAudio() {
  const audio = new Audio();
  audio.src = 'data:audio/wav;base64,UklGRiYAAABXQVZFZm10IBAAAAABAAEAQB8AAAB9AAACABAAZGF0YQIAAAAAAA==';
  
  // Create a temporary audio context for microphone test
  navigator.mediaDevices.getUserMedia({ audio: true })
    .then(stream => {
      const audioContext = new (window.AudioContext || window.webkitAudioContext)();
      const analyser = audioContext.createAnalyser();
      const microphone = audioContext.createMediaStreamSource(stream);
      const dataArray = new Uint8Array(analyser.frequencyBinCount);
      microphone.connect(analyser);
      
      let detectSound = false;
      const checkAudio = () => {
        analyser.getByteFrequencyData(dataArray);
        const average = dataArray.reduce((a, b) => a + b) / dataArray.length;
        if (average > 10) detectSound = true;
      };
      
      const timer = setInterval(checkAudio, 100);
      
      setTimeout(() => {
        clearInterval(timer);
        stream.getTracks().forEach(track => track.stop());
        
        if (detectSound) {
          alert('✓ Audio Test Successful!\n\nYour microphone is working and picking up sound. You\'re ready for your appointment!');
        } else {
          alert('⚠ No sound detected\n\nPlease check if:\n• Your microphone is connected\n• Microphone permissions are enabled\n• The app has access to your microphone');
        }
      }, 3000);
    })
    .catch(error => {
      alert('Microphone access denied. Please enable microphone permissions in your browser settings.');
      console.error('Microphone access error:', error);
    });
}

// Load notifications on page load and refresh every 30 seconds
document.addEventListener('DOMContentLoaded', () => {
  loadNotifications();
  loadCoachRecommendations();
  setInterval(loadNotifications, 30000);
  setInterval(loadCoachRecommendations, 60000);
  loadActivityFeed();
  loadWellnessScore();
  initializeCountdown();
  
  // Initialize activity filter buttons
  document.querySelectorAll('.activity-filter-btn').forEach(btn => {
    btn.style.padding = '8px 16px';
    btn.style.borderRadius = '6px';
    btn.style.border = '1px solid #059669';
    btn.style.background = btn.dataset.type === 'all' ? '#059669' : 'transparent';
    btn.style.color = btn.dataset.type === 'all' ? 'white' : '#059669';
    btn.style.fontSize = '14px';
    btn.style.cursor = 'pointer';
    btn.style.fontWeight = '600';
    btn.style.transition = 'all 0.2s ease';
  });
});

// Activity Feed Management
let currentActivityType = 'all';
let currentActivityPage = 0;

async function loadActivityFeed() {
  try {
    const response = await fetch(`/files/atasteofafricanmarketplace/api/users/activity-feed.php?type=${currentActivityType}&limit=10&offset=${currentActivityPage * 10}`, {
      credentials: 'include'
    });
    const data = await response.json();
    
    if (data.success) {
      renderActivityFeed(data);
    } else {
      document.getElementById('activityFeedContainer').innerHTML = '<div style="color: red; font-size: 12px;">Error loading activity</div>';
    }
  } catch (err) {
    console.error('Error loading activity feed:', err);
    document.getElementById('activityFeedContainer').innerHTML = '<div style="color: red; font-size: 12px;">Error loading activity</div>';
  }
}

function renderActivityFeed(data) {
  const container = document.getElementById('activityFeedContainer');
  
  if (!data.activities || data.activities.length === 0) {
    container.innerHTML = '<div style="text-align: center; color: var(--muted); padding: 40px;">No activity to display</div>';
    document.getElementById('activityPaginationControls').innerHTML = '';
    return;
  }
  
  container.innerHTML = '';
  
  const iconMap = {
    'appointment': { icon: 'fas fa-calendar-check', color: '#3b82f6' },
    'order': { icon: 'fas fa-shopping-bag', color: '#8b5cf6' },
    'health': { icon: 'fas fa-heartbeat', color: '#ef4444' },
    'document': { icon: 'fas fa-file-pdf', color: '#f59e0b' },
    'intake': { icon: 'fas fa-clipboard-list', color: '#10b981' }
  };
  
  const statusColors = {
    'completed': '#059669',
    'pending': '#f59e0b',
    'confirmed': '#3b82f6',
    'logged': '#10b981',
    'uploaded': '#8b5cf6',
    'submitted': '#06b6d4'
  };
  
  data.activities.forEach(activity => {
    const typeInfo = iconMap[activity.type] || { icon: 'fas fa-circle', color: '#6b7280' };
    const statusColor = statusColors[activity.status] || '#6b7280';
    
    const item = document.createElement('div');
    item.style.display = 'flex';
    item.style.gap = '16px';
    item.style.padding = '16px';
    item.style.borderLeft = '4px solid ' + typeInfo.color;
    item.style.borderRadius = '8px';
    item.style.backgroundColor = 'rgba(255, 255, 255, 0.5)';
    
    item.innerHTML = `
      <div style="flex-shrink: 0; width: 40px; height: 40px; background-color: ${typeInfo.color}20; border-radius: 8px; display: flex; align-items: center; justify-content: center;">
        <i class="${typeInfo.icon}" style="color: ${typeInfo.color};"></i>
      </div>
      <div style="flex: 1;">
        <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 4px;">
          <div style="font-weight: 600; color: var(--forest);">${activity.action}</div>
          <span style="background-color: ${statusColor}20; color: ${statusColor}; padding: 2px 8px; border-radius: 4px; font-size: 11px; font-weight: 600; text-transform: uppercase;">
            ${activity.status}
          </span>
        </div>
        <div style="color: var(--ink); margin-bottom: 8px;">${activity.description}</div>
        ${activity.duration_minutes ? `<div style="color: var(--muted); font-size: 12px;">Duration: ${activity.duration_minutes} minutes</div>` : ''}
        ${activity.total_amount ? `<div style="color: var(--muted); font-size: 12px;">Amount: $${parseFloat(activity.total_amount).toFixed(2)}</div>` : ''}
        ${activity.file_size ? `<div style="color: var(--muted); font-size: 12px;">Size: ${(activity.file_size / 1024 / 1024).toFixed(2)} MB</div>` : ''}
      </div>
      <div style="flex-shrink: 0; text-align: right;">
        <div style="color: var(--muted); font-size: 12px;">${activity.time_ago}</div>
      </div>
    `;
    
    container.appendChild(item);
  });
  
  // Render pagination controls
  renderPaginationControls(data.pagination);
}

function renderPaginationControls(pagination) {
  const controls = document.getElementById('activityPaginationControls');
  controls.innerHTML = '';
  
  if (pagination.total <= pagination.limit) {
    return;
  }
  
  // Previous button
  const prevBtn = document.createElement('button');
  prevBtn.innerHTML = '<i class="fas fa-chevron-left"></i> Previous';
  prevBtn.style.padding = '8px 16px';
  prevBtn.style.borderRadius = '6px';
  prevBtn.style.border = '1px solid #ccc';
  prevBtn.style.backgroundColor = currentActivityPage > 0 ? '#f9fafb' : '#e5e7eb';
  prevBtn.style.cursor = currentActivityPage > 0 ? 'pointer' : 'not-allowed';
  prevBtn.style.color = currentActivityPage > 0 ? 'var(--forest)' : '#9ca3af';
  prevBtn.disabled = currentActivityPage <= 0;
  prevBtn.onclick = () => {
    if (currentActivityPage > 0) {
      currentActivityPage--;
      loadActivityFeed();
    }
  };
  controls.appendChild(prevBtn);
  
  // Page info
  const totalPages = Math.ceil(pagination.total / pagination.limit);
  const info = document.createElement('div');
  info.style.padding = '8px 16px';
  info.style.color = 'var(--forest)';
  info.style.fontSize = '14px';
  info.textContent = `Page ${currentActivityPage + 1} of ${totalPages}`;
  controls.appendChild(info);
  
  // Next button
  const nextBtn = document.createElement('button');
  nextBtn.innerHTML = 'Next <i class="fas fa-chevron-right"></i>';
  nextBtn.style.padding = '8px 16px';
  nextBtn.style.borderRadius = '6px';
  nextBtn.style.border = '1px solid #ccc';
  nextBtn.style.backgroundColor = pagination.has_more ? '#f9fafb' : '#e5e7eb';
  nextBtn.style.cursor = pagination.has_more ? 'pointer' : 'not-allowed';
  nextBtn.style.color = pagination.has_more ? 'var(--forest)' : '#9ca3af';
  nextBtn.disabled = !pagination.has_more;
  nextBtn.onclick = () => {
    if (pagination.has_more) {
      currentActivityPage++;
      loadActivityFeed();
    }
  };
  controls.appendChild(nextBtn);
}

function filterActivityType(type) {
  currentActivityType = type;
  currentActivityPage = 0;
  
  // Update button states
  document.querySelectorAll('.activity-filter-btn').forEach(btn => {
    if (btn.dataset.type === type) {
      btn.classList.add('active');
      btn.style.backgroundColor = '#059669';
      btn.style.color = 'white';
      btn.style.borderColor = '#059669';
    } else {
      btn.classList.remove('active');
      btn.style.backgroundColor = 'transparent';
      btn.style.color = '#059669';
      btn.style.borderColor = '#059669';
    }
  });
  
  loadActivityFeed();
}

// Load wellness score from API
async function loadWellnessScore() {
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/wellness/history.php', {
      credentials: 'include'
    });
    const data = await response.json();
    
    if (data.success && data.current_score !== null) {
      const score = data.current_score.overall_score;
      const percentage = Math.round((score / 100) * 100);
      
      // Determine color based on score
      let scoreColor = '#dc2626'; // red (0-40)
      if (score >= 40 && score < 70) scoreColor = '#f59e0b'; // amber (40-70)
      if (score >= 70) scoreColor = '#059669'; // green (70-100)
      
      // Update display
      const display = document.getElementById('wellnessScoreDisplay');
      display.innerHTML = `<span style="font-size: 36px; font-weight: 700; color: ${scoreColor};">${Math.round(score)}</span><span style="font-size: 14px; color: ${scoreColor}; margin-left: 8px;">${percentage}%</span>`;
      
      // Render breakdown section
      renderWellnessBreakdown(data.current_score);
    } else {
      document.getElementById('wellnessScoreDisplay').innerHTML = '<span style="color: #6b7280; font-size: 14px;">No data yet</span>';
    }
  } catch (err) {
    console.error('Error loading wellness score:', err);
    document.getElementById('wellnessScoreDisplay').innerHTML = '<span style="color: #ef4444; font-size: 12px;">Error loading</span>';
  }
}

function renderWellnessBreakdown(scoreData) {
  const breakdown = document.getElementById('wellness-breakdown');
  if (!breakdown) return;
  
  const breakdown_obj = typeof scoreData.score_breakdown === 'string' 
    ? JSON.parse(scoreData.score_breakdown) 
    : scoreData.score_breakdown;
  
  const categories = [
    { name: 'Sleep Quality', key: 'sleep', max: 20, icon: 'fas fa-bed', color: '#3b82f6' },
    { name: 'Physical Activity', key: 'activity', max: 20, icon: 'fas fa-running', color: '#ef4444' },
    { name: 'Health Metrics', key: 'health', max: 20, icon: 'fas fa-heartbeat', color: '#f59e0b' },
    { name: 'Stress Management', key: 'stress', max: 20, icon: 'fas fa-spa', color: '#a855f7' },
    { name: 'Appointments', key: 'appointments', max: 10, icon: 'fas fa-calendar-check', color: '#059669' },
    { name: 'Engagement', key: 'engagement', max: 10, icon: 'fas fa-star', color: '#06b6d4' }
  ];
  
  let html = '<h3 style="margin-top: 0; color: var(--forest); font-size: 18px; margin-bottom: 20px;">Wellness Breakdown</h3>';
  html += '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 16px;">';
  
  categories.forEach(cat => {
    const score = breakdown_obj[cat.key] || 0;
    const percentage = Math.round((score / cat.max) * 100);
    const barColor = percentage >= 75 ? '#059669' : percentage >= 50 ? '#f59e0b' : '#ef4444';
    
    html += `
      <div style="padding: 16px; background: #f9fafb; border-radius: 8px; border-left: 4px solid ${cat.color};">
        <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 8px;">
          <i class="${cat.icon}" style="color: ${cat.color}; font-size: 14px;"></i>
          <span style="font-weight: 600; color: #1f2937; font-size: 14px;">${cat.name}</span>
        </div>
        <div style="display: flex; align-items: center; gap: 10px;">
          <div style="flex: 1; height: 6px; background: #e5e7eb; border-radius: 3px; overflow: hidden;">
            <div style="height: 100%; background: ${barColor}; width: ${percentage}%;"></div>
          </div>
          <span style="font-weight: 700; color: ${barColor}; font-size: 12px; min-width: 30px;">${Math.round(score)}/${cat.max}</span>
        </div>
      </div>
    `;
  });
  
  html += '</div>';
  breakdown.innerHTML = html;
}

// Load health overview data
async function loadHealthOverview() {
  // Load medications
  const medicationsList = document.getElementById('medicationsList');
  const medications = [
    { name: 'Herbal Sleep Aid', dosage: '2 capsules before bed', frequency: 'Daily' },
    { name: 'Vitamin D3', dosage: '1000 IU', frequency: 'Daily' }
  ];
  
  if (medications.length === 0) {
    medicationsList.innerHTML = '<div style="color: #94a3b8; font-size: 14px; font-style: italic;">No medications recorded</div>';
  } else {
    medicationsList.innerHTML = medications.map(med => `
      <div style="display: flex; justify-content: space-between; align-items: flex-start; padding: 12px; background: white; border-radius: 8px; border: 1px solid #e5e7eb;">
        <div style="flex: 1;">
          <div style="font-weight: 600; color: #0b3d2e; font-size: 14px;">${med.name}</div>
          <div style="font-size: 13px; color: #64748b; margin-top: 4px;">${med.dosage} • ${med.frequency}</div>
        </div>
        <button onclick="removeMedication('${med.name}')" style="background: none; border: none; color: #dc2626; cursor: pointer; padding: 4px;">
          <i class="fas fa-times"></i>
        </button>
      </div>
    `).join('');
  }
  
  // Load allergies
  const allergiesList = document.getElementById('allergiesList');
  const allergies = [
    { name: 'Penicillin', severity: 'Severe' },
    { name: 'Peanuts', severity: 'Moderate' }
  ];
  
  if (allergies.length === 0) {
    allergiesList.innerHTML = '<div style="color: #94a3b8; font-size: 14px; font-style: italic;">No allergies recorded</div>';
  } else {
    allergiesList.innerHTML = allergies.map(allergy => `
      <div style="display: flex; justify-content: space-between; align-items: center; padding: 12px; background: white; border-radius: 8px; border: 1px solid #e5e7eb;">
        <div style="flex: 1;">
          <div style="font-weight: 600; color: #0b3d2e; font-size: 14px;">${allergy.name}</div>
          <div style="font-size: 12px; color: #dc2626; margin-top: 2px;">
            <i class="fas fa-exclamation-circle"></i> ${allergy.severity}
          </div>
        </div>
        <button onclick="removeAllergy('${allergy.name}')" style="background: none; border: none; color: #dc2626; cursor: pointer; padding: 4px;">
          <i class="fas fa-times"></i>
        </button>
      </div>
    `).join('');
  }
}

function addMedication() {
  const name = prompt('Enter medication name:');
  if (!name) return;
  const dosage = prompt('Enter dosage (e.g., 500mg):');
  const frequency = prompt('Enter frequency (e.g., Twice daily):');
  
  if (name && dosage && frequency) {
    alert('Medication added successfully! This will be shared with your wellness coach.');
    loadHealthOverview();
  }
}

function addAllergy() {
  const name = prompt('Enter allergy name:');
  if (!name) return;
  const severity = prompt('Enter severity (Mild, Moderate, or Severe):');
  
  if (name && severity) {
    alert('Allergy added successfully! This is important for your safety during consultations.');
    loadHealthOverview();
  }
}

function removeMedication(name) {
  if (confirm(`Remove ${name} from your medications?`)) {
    alert('Medication removed.');
    loadHealthOverview();
  }
}

function removeAllergy(name) {
  if (confirm(`Remove ${name} from your allergies?`)) {
    alert('Allergy removed.');
    loadHealthOverview();
  }
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
  loadHealthOverview();
});

// Initialize filter buttons
</script>

<?php };
include __DIR__ . '/../../partials/layout.php';
?>