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

$page_title = 'Wellness Coach Dashboard | Professional Patient Care';
$page_description = 'Comprehensive wellness coaching platform with patient health tracking';
$page_content = function () use ($authUser) {
// Get coach data
$db = hw_db();
$coachStmt = $db->prepare("SELECT * FROM coaches WHERE user_id = ?");
$coachStmt->execute([$authUser['id']]);
$coach = $coachStmt->fetch(PDO::FETCH_ASSOC);

if (!$coach) {
    echo '<div style="padding: 2rem; text-align: center;"><p style="color: #dc2626;">Coach profile not found.</p></div>';
    return;
}

// Get comprehensive statistics
$today = date('Y-m-d');
$todayStart = date('Y-m-d 00:00:00');
$todayEnd = date('Y-m-d 23:59:59');

// Today's sessions
$todayStmt = $db->prepare("
    SELECT a.*, u.first_name, u.last_name, u.email 
    FROM appointments a 
    JOIN users u ON a.user_id = u.id 
    WHERE a.coach_id = ? AND a.starts_at BETWEEN ? AND ? AND a.status != 'cancelled'
    ORDER BY a.starts_at ASC
");
$todayStmt->execute([$coach['id'], $todayStart, $todayEnd]);
$todaySessions = $todayStmt->fetchAll(PDO::FETCH_ASSOC);

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

// This week's sessions
$weekStart = date('Y-m-d 00:00:00', strtotime('monday this week'));
$weekEnd = date('Y-m-d 23:59:59', strtotime('sunday this week'));
$weekStmt = $db->prepare("
    SELECT COUNT(*) as week_count 
    FROM appointments 
    WHERE coach_id = ? AND starts_at BETWEEN ? AND ? AND status != 'cancelled'
");
$weekStmt->execute([$coach['id'], $weekStart, $weekEnd]);
$weekCount = $weekStmt->fetch(PDO::FETCH_ASSOC)['week_count'];

// Total earnings
$earningsStmt = $db->prepare("
    SELECT COUNT(*) as completed_sessions FROM appointments
    WHERE coach_id = ? AND status = 'completed'
");
$earningsStmt->execute([$coach['id']]);
$completedSessions = $earningsStmt->fetch(PDO::FETCH_ASSOC)['completed_sessions'];
$totalEarnings = $completedSessions * ($coach['hourly_rate'] ?? 75);

// Get recent patients
$recentStmt = $db->prepare("
    SELECT DISTINCT u.id, u.first_name, u.last_name, 
           MAX(a.starts_at) as last_session,
           COUNT(a.id) as session_count
    FROM users u
    JOIN appointments a ON u.id = a.user_id
    WHERE a.coach_id = ?
    GROUP BY u.id
    ORDER BY MAX(a.starts_at) DESC
    LIMIT 5
");
$recentStmt->execute([$coach['id']]);
$recentPatients = $recentStmt->fetchAll(PDO::FETCH_ASSOC);
?>
?>
<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;
  }
  body {
    padding-top: 0 !important;
  }
</style>
<link rel="stylesheet" href="/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" style="background: linear-gradient(135deg, #10b981, #059669);">
          <?= strtoupper(substr($coach['display_name'], 0, 2)) ?>
        </div>
        <div class="profile-info">
          <h3><?= htmlspecialchars($coach['display_name']) ?></h3>
          <p>Coach Portal</p>
        </div>
      </div>
    </div>
    <nav class="sidebar-nav">
      <a href="/atasteofafricanmarketplace/dashboard/coach/index.php" class="active"><i class="fas fa-home"></i>Overview</a>
      <a href="/atasteofafricanmarketplace/dashboard/coach/sessions.php"><i class="fas fa-calendar-check"></i>Sessions</a>
      <a href="/atasteofafricanmarketplace/dashboard/coach/clients.php"><i class="fas fa-users"></i>Clients</a>
      <a href="/atasteofafricanmarketplace/dashboard/coach/schedule.php"><i class="fas fa-clock"></i>Schedule</a>
      <a href="/atasteofafricanmarketplace/dashboard/coach/earnings.php"><i class="fas fa-dollar-sign"></i>Earnings</a>
      <hr class="sidebar-divider">
      <a href="/atasteofafricanmarketplace/index.php"><i class="fas fa-arrow-left"></i>Back to Home</a>
    </nav>
    <div class="sidebar-footer">
      <a href="/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 style="background: linear-gradient(135deg, #10b981, #059669); padding: 40px; border-radius: 20px; margin-bottom: 32px; color: white; position: relative; overflow: hidden;">
        <div style="position: absolute; top: -50px; right: -50px; width: 200px; height: 200px; background: rgba(255, 255, 255, 0.1); border-radius: 50%;"></div>
        <div style="position: absolute; bottom: -30px; left: -30px; width: 150px; height: 150px; background: rgba(255, 255, 255, 0.05); border-radius: 50%;"></div>
        <div style="position: relative; z-index: 1;">
          <h1 style="font-size: 36px; font-weight: 800; margin: 0 0 12px 0;">Welcome back, <?= htmlspecialchars(explode(' ', $coach['display_name'])[0]) ?>!</h1>
          <p style="font-size: 16px; opacity: 0.9; margin: 0;">Wellness Coach Dashboard • <?= date('l, F j, Y') ?></p>
        </div>
      </div>

      <!-- Summary Cards -->
      <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px; margin-bottom: 32px;">
        <div style="background: linear-gradient(135deg, #3b82f6, #2563eb); padding: 24px; border-radius: 16px; color: white; position: relative; overflow: hidden;">
          <div style="position: absolute; top: -20px; right: -20px; width: 100px; height: 100px; background: rgba(255, 255, 255, 0.1); border-radius: 50%;"></div>
          <div style="position: relative;">
            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 16px;">
              <div style="font-size: 14px; opacity: 0.9; font-weight: 600;">Total Sessions</div>
              <i class="fas fa-calendar-check" style="font-size: 32px; opacity: 0.3;"></i>
            </div>
            <div style="font-size: 42px; font-weight: 800; line-height: 1;"><?= $stats['total_appointments'] ?></div>
            <div style="font-size: 13px; opacity: 0.8; margin-top: 8px;">All-time sessions</div>
          </div>
        </div>

        <div style="background: linear-gradient(135deg, #f59e0b, #d97706); padding: 24px; border-radius: 16px; color: white; position: relative; overflow: hidden;">
          <div style="position: absolute; top: -20px; right: -20px; width: 100px; height: 100px; background: rgba(255, 255, 255, 0.1); border-radius: 50%;"></div>
          <div style="position: relative;">
            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 16px;">
              <div style="font-size: 14px; opacity: 0.9; font-weight: 600;">Upcoming</div>
              <i class="fas fa-hourglass-half" style="font-size: 32px; opacity: 0.3;"></i>
            </div>
            <div style="font-size: 42px; font-weight: 800; line-height: 1;"><?= $stats['upcoming'] ?></div>
            <div style="font-size: 13px; opacity: 0.8; margin-top: 8px;">Scheduled sessions</div>
          </div>
        </div>

        <div style="background: linear-gradient(135deg, #8b5cf6, #7c3aed); padding: 24px; border-radius: 16px; color: white; position: relative; overflow: hidden;">
          <div style="position: absolute; top: -20px; right: -20px; width: 100px; height: 100px; background: rgba(255, 255, 255, 0.1); border-radius: 50%;"></div>
          <div style="position: relative;">
            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 16px;">
              <div style="font-size: 14px; opacity: 0.9; font-weight: 600;">This Week</div>
              <i class="fas fa-chart-line" style="font-size: 32px; opacity: 0.3;"></i>
            </div>
            <div style="font-size: 42px; font-weight: 800; line-height: 1;"><?= $weekCount ?></div>
            <div style="font-size: 13px; opacity: 0.8; margin-top: 8px;">Sessions scheduled</div>
          </div>
        </div>

        <div style="background: linear-gradient(135deg, #10b981, #059669); padding: 24px; border-radius: 16px; color: white; position: relative; overflow: hidden;">
          <div style="position: absolute; top: -20px; right: -20px; width: 100px; height: 100px; background: rgba(255, 255, 255, 0.1); border-radius: 50%;"></div>
          <div style="position: relative;">
            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 16px;">
              <div style="font-size: 14px; opacity: 0.9; font-weight: 600;">My Patients</div>
              <i class="fas fa-users" style="font-size: 32px; opacity: 0.3;"></i>
            </div>
            <div style="font-size: 42px; font-weight: 800; line-height: 1;"><?= $stats['total_patients'] ?></div>
            <div style="font-size: 13px; opacity: 0.8; margin-top: 8px;">Active patients</div>
          </div>
        </div>

        <div style="background: linear-gradient(135deg, #ec4899, #db2777); padding: 24px; border-radius: 16px; color: white; position: relative; overflow: hidden;">
          <div style="position: absolute; top: -20px; right: -20px; width: 100px; height: 100px; background: rgba(255, 255, 255, 0.1); border-radius: 50%;"></div>
          <div style="position: relative;">
            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 16px;">
              <div style="font-size: 14px; opacity: 0.9; font-weight: 600;">Revenue</div>
              <i class="fas fa-dollar-sign" style="font-size: 32px; opacity: 0.3;"></i>
            </div>
            <div style="font-size: 42px; font-weight: 800; line-height: 1;">$<?= number_format($totalEarnings, 0) ?></div>
            <div style="font-size: 13px; opacity: 0.8; margin-top: 8px;">Estimated earnings</div>
          </div>
        </div>
      </div>

      <!-- Two Column Layout -->
      <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(500px, 1fr)); gap: 24px;">
        <!-- Today's Schedule -->
        <div style="background: white; padding: 32px; border-radius: 16px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);">
          <h3 style="font-size: 20px; font-weight: 700; color: #0b3d2e; margin: 0 0 24px 0; display: flex; align-items: center; justify-content: space-between;">
            <span style="display: flex; align-items: center; gap: 12px;">
              <i class="fas fa-calendar-day" style="color: #10b981;"></i>
              Today's Schedule
            </span>
            <span style="font-size: 14px; font-weight: 700; color: #10b981;"><?= count($todaySessions) ?> Sessions</span>
          </h3>

          <?php if (empty($todaySessions)): ?>
            <div style="text-align: center; padding: 60px 20px; background: #f9fafb; border-radius: 12px;">
              <i class="fas fa-calendar" style="font-size: 64px; color: #cbd5e1; margin-bottom: 16px;"></i>
              <p style="color: #64748b; margin: 0; font-weight: 600;">No sessions today</p>
              <p style="color: #94a3b8; margin: 8px 0 0 0; font-size: 14px;">Great time to catch up!</p>
            </div>
          <?php else: ?>
            <div style="display: flex; flex-direction: column; gap: 16px;">
              <?php foreach ($todaySessions as $session):
                $startTime = new DateTime($session['starts_at']);
                $isUpcoming = $startTime > new DateTime();
              ?>
                <div style="background: <?= $isUpcoming ? 'linear-gradient(135deg, #f0f9f6, #fef9e7)' : '#f9fafb' ?>; padding: 20px; border-radius: 12px; border: 2px solid <?= $isUpcoming ? '#10b981' : '#e5e7eb' ?>; transition: all 0.3s;" onmouseover="this.style.transform='translateX(4px)'; this.style.boxShadow='0 4px 12px rgba(16, 185, 129, 0.2)'" onmouseout="this.style.transform='translateX(0)'; this.style.boxShadow='none'">
                  <div style="display: flex; align-items: center; gap: 16px; margin-bottom: 12px;">
                    <div style="width: 48px; height: 48px; background: linear-gradient(135deg, #10b981, #059669); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-weight: 700; font-size: 16px; flex-shrink: 0;">
                      <?= strtoupper(substr($session['first_name'], 0, 1)) . strtoupper(substr($session['last_name'], 0, 1)) ?>
                    </div>
                    <div style="flex: 1;">
                      <h4 style="font-size: 16px; font-weight: 700; color: #0b3d2e; margin: 0 0 4px 0;"><?= htmlspecialchars($session['first_name'] . ' ' . $session['last_name']) ?></h4>
                      <div style="font-size: 13px; color: #64748b; display: flex; align-items: center; gap: 16px;">
                        <span><i class="far fa-clock" style="color: #10b981;"></i> <?= $startTime->format('g:i A') ?></span>
                        <span style="background: <?= $session['status'] === 'scheduled' ? '#dbeafe' : '#d1fae5' ?>; color: <?= $session['status'] === 'scheduled' ? '#1e40af' : '#065f46' ?>; padding: 4px 12px; border-radius: 12px; font-size: 11px; font-weight: 700; text-transform: uppercase;"><?= ucfirst($session['status']) ?></span>
                      </div>
                    </div>
                    <?php if ($isUpcoming && $session['status'] === 'scheduled'): ?>
                      <button onclick="startSession(<?= $session['id'] ?>)" style="background: linear-gradient(135deg, #10b981, #059669); color: white; padding: 10px 20px; border-radius: 8px; font-size: 14px; font-weight: 700; border: none; cursor: pointer; transition: all 0.3s;">
                        <i class="fas fa-video"></i> Start
                      </button>
                    <?php endif; ?>
                  </div>
                </div>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>
        </div>

        <!-- Recent Patients -->
        <div style="background: white; padding: 32px; border-radius: 16px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);">
          <h3 style="font-size: 20px; font-weight: 700; color: #0b3d2e; margin: 0 0 24px 0; display: flex; align-items: center; gap: 12px;">
            <i class="fas fa-user-clock" style="color: #8b5cf6;"></i>
            Recent Patients
          </h3>

          <?php if (empty($recentPatients)): ?>
            <div style="text-align: center; padding: 60px 20px; background: #f9fafb; border-radius: 12px;">
              <i class="fas fa-users" style="font-size: 64px; color: #cbd5e1; margin-bottom: 16px;"></i>
              <p style="color: #64748b; margin: 0;">No patient history yet</p>
            </div>
          <?php else: ?>
            <div style="display: flex; flex-direction: column; gap: 12px;">
              <?php foreach ($recentPatients as $patient):
                $lastSession = new DateTime($patient['last_session']);
                $now = new DateTime();
                $diff = $now->diff($lastSession);
              ?>
                <div style="background: #f9fafb; padding: 16px; border-radius: 12px; border: 2px solid #e5e7eb; transition: all 0.3s;" onmouseover="this.style.borderColor='#8b5cf6'; this.style.background='#faf5ff'" onmouseout="this.style.borderColor='#e5e7eb'; this.style.background='#f9fafb'">
                  <div style="display: flex; justify-content: space-between; align-items: center; gap: 12px; margin-bottom: 8px;">
                    <div style="font-weight: 700; color: #0b3d2e; font-size: 15px;">
                      <?= htmlspecialchars($patient['first_name'] . ' ' . $patient['last_name']) ?>
                    </div>
                    <span style="background: #e0e7ff; color: #3730a3; padding: 4px 10px; border-radius: 12px; font-size: 11px; font-weight: 700;">
                      <?= $diff->days === 0 ? 'Today' : ($diff->days . 'd ago') ?>
                    </span>
                  </div>
                  <div style="font-size: 13px; color: #64748b;">
                    <i class="fas fa-check-circle" style="color: #10b981;"></i>
                    <?= $patient['session_count'] ?> sessions completed
                  </div>
                </div>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>
        </div>
      </div>

      <!-- Quick Actions -->
      <div style="margin-top: 32px;">
        <h3 style="font-size: 20px; font-weight: 700; color: #0b3d2e; margin: 0 0 20px 0;">Quick Actions</h3>
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px;">
          <a href="/atasteofafricanmarketplace/dashboard/coach/clients.php" style="display: block; background: linear-gradient(135deg, #3b82f6, #2563eb); padding: 24px; border-radius: 16px; text-decoration: none; color: white; transition: all 0.3s;" onmouseover="this.style.transform='translateY(-4px)'; this.style.boxShadow='0 8px 16px rgba(59, 130, 246, 0.3)'" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='none'">
            <i class="fas fa-users" style="font-size: 32px; margin-bottom: 12px; opacity: 0.9;"></i>
            <div style="font-size: 16px; font-weight: 700;">View Patients</div>
            <div style="font-size: 13px; opacity: 0.8; margin-top: 4px;">Full patient directory</div>
          </a>

          <a href="/atasteofafricanmarketplace/dashboard/coach/schedule.php" style="display: block; background: linear-gradient(135deg, #8b5cf6, #7c3aed); padding: 24px; border-radius: 16px; text-decoration: none; color: white; transition: all 0.3s;" onmouseover="this.style.transform='translateY(-4px)'; this.style.boxShadow='0 8px 16px rgba(139, 92, 246, 0.3)'" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='none'">
            <i class="fas fa-calendar-plus" style="font-size: 32px; margin-bottom: 12px; opacity: 0.9;"></i>
            <div style="font-size: 16px; font-weight: 700;">Manage Schedule</div>
            <div style="font-size: 13px; opacity: 0.8; margin-top: 4px;">Set availability</div>
          </a>

          <a href="/atasteofafricanmarketplace/dashboard/coach/earnings.php" style="display: block; background: linear-gradient(135deg, #10b981, #059669); padding: 24px; border-radius: 16px; text-decoration: none; color: white; transition: all 0.3s;" onmouseover="this.style.transform='translateY(-4px)'; this.style.boxShadow='0 8px 16px rgba(16, 185, 129, 0.3)'" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='none'">
            <i class="fas fa-chart-line" style="font-size: 32px; margin-bottom: 12px; opacity: 0.9;"></i>
            <div style="font-size: 16px; font-weight: 700;">View Earnings</div>
            <div style="font-size: 13px; opacity: 0.8; margin-top: 4px;">Income & analytics</div>
          </a>

          <a href="/atasteofafricanmarketplace/dashboard/coach/sessions.php" style="display: block; background: linear-gradient(135deg, #f59e0b, #d97706); padding: 24px; border-radius: 16px; text-decoration: none; color: white; transition: all 0.3s;" onmouseover="this.style.transform='translateY(-4px)'; this.style.boxShadow='0 8px 16px rgba(245, 158, 11, 0.3)'" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='none'">
            <i class="fas fa-calendar-check" style="font-size: 32px; margin-bottom: 12px; opacity: 0.9;"></i>
            <div style="font-size: 16px; font-weight: 700;">My Sessions</div>
            <div style="font-size: 13px; opacity: 0.8; margin-top: 4px;">View all sessions</div>
          </a>
        </div>
      </div>
    </main>
  </div>
</div>

<script>
async function startSession(appointmentId) {
  if (!confirm('Start video session with this patient?')) return;
  
  try {
    const response = await fetch('/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 = `/atasteofafricanmarketplace/video-session.php?token=${data.session_token}`;
    } else {
      alert('Failed to start video session: ' + (data.message || 'Unknown error'));
    }
  } catch (error) {
    console.error('Error starting session:', error);
    alert('Failed to start video session. Please try again.');
  }
}
</script>

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