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

// CHECK MEMBERSHIP
$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() LIMIT 1");
$membershipStmt->execute([$authUser['id']]);
if (!$membershipStmt->fetch()) {
    header('Location: /files/atasteofafricanmarketplace/dashboard/user/choose-plan.php');
    exit;
}

$page_title = 'My Appointments | Herbal Wellness Care';
$page_description = 'View and manage your appointments';
$page_content = function () use ($authUser) { ?>
<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="/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"><i class="fas fa-home"></i>Home</a>
      <a href="/files/atasteofafricanmarketplace/dashboard/user/appointments.php" class="active"><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 with Actions -->
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 32px; flex-wrap: wrap; gap: 16px;">
        <div>
          <h1 style="font-size: 32px; font-weight: 800; color: #0b3d2e; margin: 0 0 8px 0;">My Appointments</h1>
          <p style="font-size: 16px; color: #64748b; margin: 0;">Manage your wellness consultations and sessions</p>
        </div>
        <a href="/files/atasteofafricanmarketplace/all-coaches.php" 
           style="display: flex; align-items: center; gap: 10px; background: linear-gradient(135deg, #0f5240, #146651); color: white; padding: 14px 24px; border-radius: 12px; font-size: 15px; font-weight: 700; text-decoration: none; box-shadow: 0 6px 16px rgba(15, 82, 64, 0.3); transition: all 0.3s;">
          <i class="fas fa-calendar-plus"></i>
          <span>Book New Appointment</span>
        </a>
      </div>

      <!-- Filter Tabs -->
      <div style="background: white; padding: 16px 24px; border-radius: 16px; margin-bottom: 24px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); display: flex; gap: 12px; flex-wrap: wrap; align-items: center;">
        <span style="font-weight: 600; color: #64748b; font-size: 14px; margin-right: 8px;">Filter:</span>
        <button onclick="filterAppointments('all')" id="filter-all" class="filter-btn active" style="padding: 8px 20px; border-radius: 8px; font-size: 14px; font-weight: 600; border: 2px solid #0f5240; background: #0f5240; color: white; cursor: pointer; transition: all 0.3s;">
          All
        </button>
        <button onclick="filterAppointments('upcoming')" id="filter-upcoming" class="filter-btn" style="padding: 8px 20px; border-radius: 8px; font-size: 14px; font-weight: 600; border: 2px solid #e5e7eb; background: white; color: #64748b; cursor: pointer; transition: all 0.3s;">
          Upcoming
        </button>
        <button onclick="filterAppointments('today')" id="filter-today" class="filter-btn" style="padding: 8px 20px; border-radius: 8px; font-size: 14px; font-weight: 600; border: 2px solid #e5e7eb; background: white; color: #64748b; cursor: pointer; transition: all 0.3s;">
          Today
        </button>
        <button onclick="filterAppointments('past')" id="filter-past" class="filter-btn" style="padding: 8px 20px; border-radius: 8px; font-size: 14px; font-weight: 600; border: 2px solid #e5e7eb; background: white; color: #64748b; cursor: pointer; transition: all 0.3s;">
          Past
        </button>
      </div>

      <!-- Appointments Summary Cards -->
      <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-bottom: 32px;">
        <div style="background: linear-gradient(135deg, #10b981, #059669); padding: 24px; border-radius: 16px; box-shadow: 0 6px 16px rgba(16, 185, 129, 0.3);">
          <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px;">
            <i class="fas fa-calendar-check" style="font-size: 32px; color: rgba(255, 255, 255, 0.9);"></i>
            <span id="upcoming-count" style="font-size: 36px; font-weight: 800; color: white;">0</span>
          </div>
          <p style="color: rgba(255, 255, 255, 0.9); font-size: 14px; font-weight: 600; margin: 0;">Upcoming Sessions</p>
        </div>

        <div style="background: linear-gradient(135deg, #3b82f6, #2563eb); padding: 24px; border-radius: 16px; box-shadow: 0 6px 16px rgba(59, 130, 246, 0.3);">
          <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px;">
            <i class="fas fa-clock" style="font-size: 32px; color: rgba(255, 255, 255, 0.9);"></i>
            <span id="today-count" style="font-size: 36px; font-weight: 800; color: white;">0</span>
          </div>
          <p style="color: rgba(255, 255, 255, 0.9); font-size: 14px; font-weight: 600; margin: 0;">Today's Appointments</p>
        </div>

        <div style="background: linear-gradient(135deg, #8b5cf6, #7c3aed); padding: 24px; border-radius: 16px; box-shadow: 0 6px 16px rgba(139, 92, 246, 0.3);">
          <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px;">
            <i class="fas fa-check-circle" style="font-size: 32px; color: rgba(255, 255, 255, 0.9);"></i>
            <span id="completed-count" style="font-size: 36px; font-weight: 800; color: white;">0</span>
          </div>
          <p style="color: rgba(255, 255, 255, 0.9); font-size: 14px; font-weight: 600; margin: 0;">Completed Sessions</p>
        </div>
      </div>

      <!-- Appointments List -->
      <div id="appointments-list" style="display: flex; flex-direction: column; gap: 24px;">
        <div style="text-align: center; padding: 60px 20px; background: white; border-radius: 16px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);">
          <div style="display: inline-block; width: 64px; height: 64px; background: linear-gradient(135deg, #f0f9f6, #fef9e7); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin-bottom: 16px;">
            <i class="fas fa-spinner fa-spin" style="font-size: 32px; color: #0f5240;"></i>
          </div>
          <p style="color: #64748b; font-size: 16px; margin: 0;">Loading appointments...</p>
        </div>
      </div>
    </main>
  </div>
</div>

<style>
.filter-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.filter-btn.active {
  background: #0f5240 !important;
  color: white !important;
  border-color: #0f5240 !important;
}

.appointment-card {
  transition: all 0.3s;
}

.appointment-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 32px rgba(15, 82, 64, 0.2) !important;
}
</style>

<script>
let allAppointmentsData = [];
let currentFilter = 'all';

// Format countdown timer
function formatCountdown(seconds) {
  if (seconds <= 0) return '00:00:00';
  const h = Math.floor(seconds / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  const s = seconds % 60;
  return String(h).padStart(2, '0') + ':' + String(m).padStart(2, '0') + ':' + String(s).padStart(2, '0');
}

// Start all countdown timers
function startAllCountdowns() {
  const countdowns = document.querySelectorAll('[id^="countdown-timer-"]');
  countdowns.forEach(countdown => {
    const startTime = parseInt(countdown.dataset.start);
    const updateTimer = () => {
      const now = Date.now();
      const diff = Math.floor((startTime - now) / 1000);
      
      if (diff <= 0) {
        countdown.textContent = '00:00:00';
        countdown.style.color = '#ef4444';
        return;
      }
      
      countdown.textContent = formatCountdown(diff);
    };
    
    updateTimer();
    setInterval(updateTimer, 1000);
  });
}

// Test audio functionality
function testAudioForAppointment() {
  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);
    });
}

// Filter appointments
function filterAppointments(filter) {
  currentFilter = filter;
  
  // Update active button
  document.querySelectorAll('.filter-btn').forEach(btn => {
    btn.classList.remove('active');
    btn.style.background = 'white';
    btn.style.color = '#64748b';
    btn.style.borderColor = '#e5e7eb';
  });
  
  const activeBtn = document.getElementById(`filter-${filter}`);
  if (activeBtn) {
    activeBtn.classList.add('active');
  }
  
  renderAppointments();
}

// Render appointments based on filter
function renderAppointments() {
  const list = document.getElementById('appointments-list');
  const now = new Date();
  
  let filteredAppointments = allAppointmentsData;
  
  if (currentFilter === 'upcoming') {
    filteredAppointments = allAppointmentsData.filter(apt => new Date(apt.starts_at) > now);
  } else if (currentFilter === 'today') {
    filteredAppointments = allAppointmentsData.filter(apt => {
      const startDate = new Date(apt.starts_at);
      return startDate.toDateString() === now.toDateString();
    });
  } else if (currentFilter === 'past') {
    filteredAppointments = allAppointmentsData.filter(apt => new Date(apt.starts_at) < now);
  }
  
  if (filteredAppointments.length === 0) {
    const emptyMessages = {
      all: 'No appointments found',
      upcoming: 'No upcoming appointments',
      today: 'No appointments today',
      past: 'No past appointments'
    };
    
    list.innerHTML = `
      <div style="text-align: center; padding: 60px 20px; background: white; border-radius: 16px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);">
        <div style="font-size: 64px; margin-bottom: 16px;">📅</div>
        <h3 style="font-size: 20px; color: #0b3d2e; margin: 0 0 8px 0; font-weight: 700;">${emptyMessages[currentFilter]}</h3>
        <p style="color: #64748b; margin: 0 0 24px 0;">Schedule a consultation with one of our wellness coaches</p>
        <a href="/files/atasteofafricanmarketplace/all-coaches.php" 
           style="display: inline-flex; align-items: center; gap: 10px; background: #0f5240; color: white; padding: 14px 28px; border-radius: 10px; font-weight: 700; text-decoration: none; transition: all 0.3s;">
          <i class="fas fa-calendar-plus"></i>
          Book Your First Session
        </a>
      </div>
    `;
    return;
  }
  
  list.innerHTML = filteredAppointments.map(apt => {
    const startDate = new Date(apt.starts_at);
    const endDate = new Date(apt.ends_at);
    const isUpcoming = startDate > now;
    const isToday = startDate.toDateString() === now.toDateString();
    const isSoon = (startDate - now) < 3600000; // Within 1 hour
    const timeUntil = Math.floor((startDate - now) / 1000);
    const status = apt.status || 'scheduled';
    
    const duration = ((endDate - startDate) / 3600000).toFixed(1);
    
    let topBarText = '⏰ UPCOMING';
    if (isSoon && isUpcoming) topBarText = '🔴 STARTING SOON';
    else if (isToday && isUpcoming) topBarText = '📅 TODAY';
    else if (!isUpcoming) topBarText = '📋 PAST APPOINTMENT';
    
    return `
    <div class="appointment-card" style="background: linear-gradient(135deg, #f0f9f6 0%, #fef9e7 100%); border-radius: 16px; overflow: hidden; box-shadow: 0 4px 16px rgba(15, 82, 64, 0.1); border: 2px solid ${isUpcoming ? '#d4ad31' : '#e5e7eb'};">
      <!-- Top Status Bar -->
      <div style="background: linear-gradient(90deg, ${isUpcoming ? '#0f5240' : '#64748b'} 0%, ${isUpcoming ? '#146651' : '#475569'} 100%); padding: 12px 24px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 12px;">
        <div style="display: flex; align-items: center; gap: 12px; color: white;">
          <i class="fas ${isUpcoming ? 'fa-video' : 'fa-check-circle'}" style="font-size: 16px;"></i>
          <span style="font-weight: 700; font-size: 13px; text-transform: uppercase; letter-spacing: 0.5px;">
            ${topBarText}
          </span>
        </div>
        <div style="display: flex; align-items: center; gap: 8px;">
          <span style="display: inline-block; padding: 4px 12px; border-radius: 20px; font-size: 11px; font-weight: 700; text-transform: uppercase; ${
            status === 'completed' ? 'background: rgba(16, 185, 129, 0.3); color: #059669;' :
            status === 'pending' ? 'background: rgba(245, 158, 11, 0.3); color: #d97706;' :
            status === 'cancelled' ? 'background: rgba(239, 68, 68, 0.3); color: #dc2626;' :
            'background: rgba(59, 130, 246, 0.3); color: #1d4ed8;'
          }">
            ${status.toUpperCase()}
          </span>
        </div>
      </div>

      <!-- Main Content -->
      <div style="padding: 24px;">
        <div style="display: grid; grid-template-columns: auto 1fr; gap: 20px; margin-bottom: ${isSoon && isUpcoming ? '24px' : '0'};">
          <!-- Coach Avatar -->
          <div style="position: relative;">
            <div style="width: 80px; height: 80px; border-radius: 12px; background: linear-gradient(135deg, #d4ad31, #c9a227); display: flex; align-items: center; justify-content: center; color: white; font-size: 32px; font-weight: bold; box-shadow: 0 6px 12px rgba(212, 173, 49, 0.3);">
              ${apt.coach_name ? apt.coach_name.charAt(0).toUpperCase() : 'C'}
            </div>
            ${isUpcoming ? `
              <div style="position: absolute; bottom: 0; right: 0; background: #10b981; width: 24px; height: 24px; border-radius: 50%; border: 3px solid white; display: flex; align-items: center; justify-content: center; color: white; font-size: 12px;">
                <i class="fas fa-check"></i>
              </div>
            ` : ''}
          </div>

          <!-- Appointment Info -->
          <div>
            <h3 style="font-size: 22px; color: #0b3d2e; margin: 0 0 6px 0; font-weight: 800;">
              ${apt.coach_name || 'Wellness Coach'}
            </h3>
            <p style="color: #0f5240; font-weight: 600; font-size: 13px; margin: 0 0 14px 0; text-transform: uppercase; letter-spacing: 0.5px;">
              <i class="fas fa-stethoscope" style="margin-right: 6px;"></i>Wellness Consultation
            </p>

            <!-- Time & Date Grid -->
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 12px;">
              <div style="background: white; padding: 10px 14px; border-radius: 8px; border: 1px solid #e5e7eb;">
                <div style="font-size: 11px; color: #64748b; font-weight: 600; text-transform: uppercase; margin-bottom: 4px;">
                  <i class="far fa-calendar" style="color: #0f5240; margin-right: 4px;"></i>Date
                </div>
                <div style="font-size: 14px; font-weight: 700; color: #0b3d2e;">
                  ${startDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
                </div>
              </div>

              <div style="background: white; padding: 10px 14px; border-radius: 8px; border: 1px solid #e5e7eb;">
                <div style="font-size: 11px; color: #64748b; font-weight: 600; text-transform: uppercase; margin-bottom: 4px;">
                  <i class="far fa-clock" style="color: #d4ad31; margin-right: 4px;"></i>Time
                </div>
                <div style="font-size: 14px; font-weight: 700; color: #0b3d2e;">
                  ${startDate.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })}
                </div>
              </div>

              <div style="background: white; padding: 10px 14px; border-radius: 8px; border: 1px solid #e5e7eb;">
                <div style="font-size: 11px; color: #64748b; font-weight: 600; text-transform: uppercase; margin-bottom: 4px;">
                  <i class="fas fa-hourglass-half" style="color: #146651; margin-right: 4px;"></i>Duration
                </div>
                <div style="font-size: 14px; font-weight: 700; color: #0b3d2e;">
                  ${duration}h
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Live Countdown Timer -->
        ${isSoon && isUpcoming ? `
          <div style="background: linear-gradient(135deg, rgba(212, 173, 49, 0.1), rgba(15, 82, 64, 0.1)); border: 2px solid #d4ad31; border-radius: 12px; padding: 14px; margin-bottom: 20px; text-align: center;">
            <div style="font-size: 12px; color: #64748b; font-weight: 600; text-transform: uppercase; margin-bottom: 6px; letter-spacing: 0.5px;">
              <i class="fas fa-timer" style="margin-right: 6px;"></i>Time Until Session
            </div>
            <div id="countdown-timer-${apt.id}" data-start="${startDate.getTime()}" style="font-size: 24px; font-weight: 700; color: #d4ad31; font-family: 'Courier New', monospace; letter-spacing: 2px;">
              ${formatCountdown(timeUntil)}
            </div>
          </div>
        ` : ''}

        <!-- Coach Notes -->
        ${apt.notes ? `
          <div style="background: #f0f9f6; border-left: 4px solid #0f5240; padding: 14px; border-radius: 8px; margin-bottom: 20px;">
            <div style="font-size: 11px; color: #64748b; font-weight: 600; text-transform: uppercase; margin-bottom: 6px; letter-spacing: 0.5px;">
              <i class="fas fa-clipboard-list" style="color: #0f5240; margin-right: 6px;"></i>Coach Notes & Instructions
            </div>
            <div style="font-size: 14px; color: #0b3d2e; line-height: 1.6;">
              ${apt.notes}
            </div>
          </div>
        ` : ''}

        <!-- Action Buttons -->
        ${isUpcoming ? `
          <div style="display: flex; gap: 10px; flex-wrap: wrap;">
            ${isSoon ? `
              <button onclick="joinVideoSession(${apt.id})" 
                 style="flex: 1; min-width: 180px; display: flex; align-items: center; justify-content: center; gap: 10px; background: linear-gradient(135deg, #10b981, #059669); color: white; padding: 14px 20px; border-radius: 10px; font-size: 14px; font-weight: 700; border: none; cursor: pointer; box-shadow: 0 6px 12px rgba(16, 185, 129, 0.3); transition: all 0.3s;">
                <i class="fas fa-video"></i>
                <span>Join Meeting Now</span>
              </button>
              <button onclick="testAudioForAppointment()" style="display: flex; align-items: center; justify-content: center; gap: 8px; background: white; color: #0f5240; padding: 14px 20px; border-radius: 10px; font-size: 13px; font-weight: 600; border: 2px solid #0f5240; cursor: pointer; transition: all 0.3s;">
                <i class="fas fa-microphone"></i>
                Test Audio
              </button>
            ` : `
              <button onclick="alert('Join button will be available 1 hour before the session')" style="flex: 1; min-width: 180px; display: flex; align-items: center; justify-content: center; gap: 10px; background: white; color: #0f5240; padding: 14px 20px; border-radius: 10px; font-size: 14px; font-weight: 700; border: 2px solid #0f5240; cursor: pointer;">
                <i class="far fa-clock"></i>
                <span>Available Soon</span>
              </button>
            `}
            
            <button onclick="alert('Reschedule feature coming soon')" style="display: flex; align-items: center; justify-content: center; gap: 8px; background: white; color: #64748b; padding: 14px 20px; border-radius: 10px; font-size: 13px; font-weight: 600; border: 2px solid #e5e7eb; cursor: pointer; transition: all 0.3s;">
              <i class="fas fa-sync-alt"></i>
              Reschedule
            </button>
          </div>
        ` : ''}
      </div>
    </div>
  `}).join('');
  
  // Start countdown timers
  startAllCountdowns();
}

async function loadAppointments() {
  const list = document.getElementById('appointments-list');
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/appointments/list.php', {
      credentials: 'include'
    });
    
    if (response.status === 401) {
      window.location.href = '/files/atasteofafricanmarketplace/login.php';
      return;
    }
    
    const data = await response.json();
    
    if (data.appointments && data.appointments.length > 0) {
      allAppointmentsData = data.appointments;
      const now = new Date();
      
      // Update summary counts
      const upcoming = data.appointments.filter(apt => new Date(apt.starts_at) > now).length;
      const today = data.appointments.filter(apt => {
        const startDate = new Date(apt.starts_at);
        return startDate.toDateString() === now.toDateString();
      }).length;
      const completed = data.appointments.filter(apt => apt.status === 'completed').length;
      
      document.getElementById('upcoming-count').textContent = upcoming;
      document.getElementById('today-count').textContent = today;
      document.getElementById('completed-count').textContent = completed;
      
      renderAppointments();
    } else {
      allAppointmentsData = [];
      document.getElementById('upcoming-count').textContent = '0';
      document.getElementById('today-count').textContent = '0';
      document.getElementById('completed-count').textContent = '0';
      
      list.innerHTML = `
        <div style="text-align: center; padding: 60px 20px; background: white; border-radius: 16px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);">
          <div style="font-size: 64px; margin-bottom: 16px;">📅</div>
          <h3 style="font-size: 20px; color: #0b3d2e; margin: 0 0 8px 0; font-weight: 700;">No appointments scheduled</h3>
          <p style="color: #64748b; margin: 0 0 24px 0;">Start your wellness journey today</p>
          <a href="/files/atasteofafricanmarketplace/all-coaches.php" 
             style="display: inline-flex; align-items: center; gap: 10px; background: #0f5240; color: white; padding: 14px 28px; border-radius: 10px; font-weight: 700; text-decoration: none; transition: all 0.3s;">
            <i class="fas fa-calendar-plus"></i>
            Book Your First Session
          </a>
        </div>
      `;
    }
  } catch (error) {
    console.error('Error loading appointments:', error);
    list.innerHTML = `
      <div style="text-align: center; padding: 60px 20px; background: white; border-radius: 16px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);">
        <div style="font-size: 64px; margin-bottom: 16px;">⚠️</div>
        <h3 style="font-size: 20px; color: #0b3d2e; margin: 0 0 8px 0; font-weight: 700;">Error loading appointments</h3>
        <p style="color: #64748b; margin: 0 0 24px 0;">Please refresh the page to try again</p>
        <button onclick="loadAppointments()" 
                style="display: inline-flex; align-items: center; gap: 10px; background: #0f5240; color: white; padding: 14px 28px; border-radius: 10px; font-weight: 700; border: none; cursor: pointer;">
          <i class="fas fa-refresh"></i>
          Retry
        </button>
      </div>
    `;
  }
}

loadAppointments();

async function joinVideoSession(appointmentId) {
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/video/start.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      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(data.message || 'Failed to join video session');
    }
  } catch (error) {
    console.error('Error:', error);
    alert('Network error. Please try again.');
  }
}

async function startVideoSession(appointmentId) {
  try {
    const response = await fetch('/files/atasteofafricanmarketplace/api/video/start.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ appointment_id: appointmentId })
    });
    
    const data = await response.json();
    
    if (data.success) {
      // Open video session in new window
      const sessionUrl = `/files/atasteofafricanmarketplace/video-session.php?token=${data.session_token}`;
      window.open(sessionUrl, '_blank', 'width=1200,height=800');
    } else {
      alert(data.message || 'Failed to start video session');
    }
  } catch (error) {
    alert('Network error. Please try again.');
  }
}

function viewDetails(appointmentId) {
  const appointments = window.appointmentsData || [];
  const apt = appointments.find(a => a.id == appointmentId);
  if (!apt) return;
  
  const startDate = new Date(apt.starts_at);
  const endDate = apt.ends_at ? new Date(apt.ends_at) : new Date(startDate.getTime() + 60*60*1000);
  
  const detailsHtml = `
    <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" onclick="closeDetails(event)">
      <div class="bg-white p-6 rounded-lg max-w-md w-full mx-4" onclick="event.stopPropagation()">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-bold">Appointment Details</h3>
          <button onclick="closeDetails()" class="text-gray-500 hover:text-gray-700">&times;</button>
        </div>
        <div class="space-y-3">
          <div><strong>Coach:</strong> ${apt.coach_name}</div>
          <div><strong>Date:</strong> ${startDate.toLocaleDateString()}</div>
          <div><strong>Time:</strong> ${startDate.toLocaleTimeString()} - ${endDate.toLocaleTimeString()}</div>
          <div><strong>Status:</strong> <span class="capitalize">${apt.status}</span></div>
          ${apt.notes ? `<div><strong>Notes:</strong> ${apt.notes}</div>` : ''}
          <div><strong>Duration:</strong> ${apt.duration || 60} minutes</div>
        </div>
        <div class="mt-4 flex gap-2">
          <button onclick="closeDetails()" class="bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-600">Close</button>
        </div>
      </div>
    </div>
  `;
  
  document.body.insertAdjacentHTML('beforeend', detailsHtml);
}

function closeDetails(event) {
  if (event && event.target !== event.currentTarget) return;
  const modal = document.querySelector('.fixed.inset-0');
  if (modal) modal.remove();
}

</script>

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