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

$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);

// 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);

// Calculate wellness score based on intake data
$wellnessScore = 75; // Default
if ($intake) {
    $score = 50;
    if (!empty($intake['exercise'])) $score += 10;
    if (($intake['sleepHours'] ?? 0) >= 7) $score += 10;
    if (($intake['stressLevel'] ?? 10) <= 5) $score += 15;
    if (empty($intake['currentConditions'])) $score += 10;
    if (($intake['sleepQuality'] ?? '') === 'Excellent') $score += 5;
    $wellnessScore = min(100, $score);
}

?>
<style>
  nav.fixed { display: none !important; }
  main.pt-20 { 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>
        </div>
      </div>
    </div>
    <nav class="sidebar-nav">
      <a href="/files/atasteofafricanmarketplace/dashboard/user/index.php" class="active"><i class="fas fa-home"></i>Overview</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/profile.php"><i class="fas fa-user"></i>My Profile</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/appointments.php"><i class="fas fa-calendar-check"></i>Appointments</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/billing.php"><i class="fas fa-file-invoice-dollar"></i>Billing</a>
      <a href="/files/atasteofafricanmarketplace/store.php"><i class="fas fa-store"></i>Store</a>
      <hr class="sidebar-divider">
      <a href="/files/atasteofafricanmarketplace/index.php"><i class="fas fa-arrow-left"></i>Back to Home</a>
      <a href="/files/atasteofafricanmarketplace/api/auth/logout.php"><i class="fas fa-sign-out-alt"></i>Sign Out</a>
    </nav>
    <div class="sidebar-footer">
      Herbal Wellness Care
    </div>
  </div>

  <!-- Main Content -->
  <div class="dashboard-content">
    <main>
      <!-- Header -->
      <div class="dashboard-header">
        <h1>Dashboard Overview</h1>
        <p>Welcome back, <?= htmlspecialchars($authUser['first_name']) ?>!</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: #059669;"></i>
          </div>
          <div class="stat-value"><?= $wellnessScore ?>%</div>
          <a href="#health-data" class="stat-link" style="color: #059669;">View Details 	</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: #3b82f6;"></i>
          </div>
          <div class="stat-value"><?= $stats['upcoming'] ?></div>
          <a href="/files/atasteofafricanmarketplace/dashboard/user/appointments.php" class="stat-link" style="color: #3b82f6;">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: #a855f7;"></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: #f59e0b;">View Billing 	</a>
        </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-purple">
              <i class="fas fa-store"></i>Browse Store
            </a>
            <a href="/files/atasteofafricanmarketplace/tree-of-life.php" class="action-btn action-btn-green">
              <i class="fas fa-tree"></i>Tree of Life
            </a>
            <a href="/files/atasteofafricanmarketplace/dashboard/user/profile.php" class="action-btn action-btn-blue">
              <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-blue">
              <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">2</span></h3>
          <div style="display: flex; flex-direction: column; gap: 12px;">
            <div class="notification-item" style="background-color: #dbeafe; border-radius: 8px;">
              <i class="fas fa-calendar" style="color: #3b82f6;"></i>
              <div class="notification-text">
                <div class="notification-title" style="color: #1e3a8a;">Session Reminder</div>
                <div class="notification-desc" style="color: #1e40af;">Your session is tomorrow at 2 PM</div>
              </div>
            </div>
            <div class="notification-item" style="background-color: #dcfce7; border-radius: 8px;">
              <i class="fas fa-leaf" style="color: #16a34a;"></i>
              <div class="notification-text">
                <div class="notification-title" style="color: #166534;">New Recommendation</div>
                <div class="notification-desc" style="color: #15803d;">Chamomile tea for better sleep</div>
              </div>
            </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;">F 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;">D 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;">F 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;">7 Plant-Based Nutrition</h4>
            <p style="color: #047857;">Explore our vegetarian herbal supplements for optimal health.</p>
          </div>
          <?php endif; ?>
        </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 a" 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>
    </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.');
      }
    });
}

function joinSession(appointmentId) {
  window.location.href = `/files/atasteofafricanmarketplace/video-session.php?appointment_id=${appointmentId}`;
}

function callCoach() {
  // Find the next appointment and redirect to video session (simulate call)
  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) {
          if (confirm('Start a video call with your coach?')) {
            window.location.href = `/files/atasteofafricanmarketplace/video-session.php?appointment_id=${next.id}`;
          }
        } else {
          alert('No coach available for a call.');
        }
      } else {
        alert('No appointments found.');
      }
    });
}

// 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;
  }
});
</script>

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