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

$page_title = 'My Sessions | Coach Dashboard';
$page_description = 'Manage your coaching sessions';
$page_content = function () use ($authUser) {
$db = hw_db();

// Get coach data
$coachStmt = $db->prepare("SELECT * FROM coaches WHERE user_id = ?");
$coachStmt->execute([$authUser['id']]);
$coach = $coachStmt->fetch(PDO::FETCH_ASSOC);

if (!$coach) {
    echo '<div class="p-8 text-center"><p class="text-red-600">Coach profile not found.</p></div>';
    return;
}

// Filters
$status = $_GET['status'] ?? 'all';
$search = $_GET['search'] ?? '';

// Build query
$conditions = ['a.coach_id = ?'];
$params = [$coach['id']];

if ($status !== 'all') {
    $conditions[] = 'a.status = ?';
    $params[] = $status;
}

if (!empty($search)) {
    $conditions[] = "(u.first_name LIKE ? OR u.last_name LIKE ? OR u.email LIKE ?)";
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

$whereClause = implode(' AND ', $conditions);

// Get appointments
$stmt = $db->prepare("
    SELECT a.*, u.first_name, u.last_name, u.email, u.phone,
           TIMESTAMPDIFF(MINUTE, a.starts_at, a.ends_at) as duration_minutes
    FROM appointments a
    JOIN users u ON a.user_id = u.id
    WHERE $whereClause
    ORDER BY a.starts_at DESC
    LIMIT 50
");
$stmt->execute($params);
$appointments = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get summary stats
$summaryStmt = $db->prepare("
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'scheduled' THEN 1 ELSE 0 END) as scheduled,
        SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
        SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled
    FROM appointments
    WHERE coach_id = ?
");
$summaryStmt->execute([$coach['id']]);
$summary = $summaryStmt->fetch(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"><i class="fas fa-home"></i>Overview</a>
      <a href="/atasteofafricanmarketplace/dashboard/coach/sessions.php" class="active"><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="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 Sessions</h1>
          <p style="font-size: 16px; color: #64748b; margin: 0;">View and manage all your coaching sessions</p>
        </div>
        <button onclick="exportSessions()" style="background: white; color: #10b981; padding: 12px 24px; border-radius: 10px; font-size: 14px; font-weight: 700; border: 2px solid #10b981; cursor: pointer; transition: all 0.3s; display: flex; align-items: center; gap: 8px;">
          <i class="fas fa-download"></i> Export Sessions
        </button>
      </div>

      <!-- Summary Stats -->
      <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 20px; margin-bottom: 32px;">
        <div style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); padding: 24px; border-radius: 16px; box-shadow: 0 8px 24px rgba(16, 185, 129, 0.2); position: relative; overflow: hidden;">
          <div style="position: absolute; top: -30px; right: -30px; width: 120px; height: 120px; background: rgba(255, 255, 255, 0.05); border-radius: 50%;"></div>
          <div style="position: relative; z-index: 1;">
            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 12px;">
              <p style="color: rgba(255, 255, 255, 0.9); font-size: 14px; font-weight: 600; margin: 0;">Total Sessions</p>
              <i class="fas fa-calendar-alt" style="color: rgba(255, 255, 255, 0.3); font-size: 24px;"></i>
            </div>
            <p style="font-size: 36px; font-weight: 800; color: white; margin: 0;"><?= $summary['total'] ?></p>
            <p style="color: rgba(255, 255, 255, 0.7); font-size: 12px; margin: 8px 0 0 0;">All time sessions</p>
          </div>
        </div>

        <div style="background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); padding: 24px; border-radius: 16px; box-shadow: 0 8px 24px rgba(59, 130, 246, 0.2); position: relative; overflow: hidden;">
          <div style="position: absolute; top: -30px; right: -30px; width: 120px; height: 120px; background: rgba(255, 255, 255, 0.05); border-radius: 50%;"></div>
          <div style="position: relative; z-index: 1;">
            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 12px;">
              <p style="color: rgba(255, 255, 255, 0.9); font-size: 14px; font-weight: 600; margin: 0;">Scheduled</p>
              <i class="fas fa-clock" style="color: rgba(255, 255, 255, 0.3); font-size: 24px;"></i>
            </div>
            <p style="font-size: 36px; font-weight: 800; color: white; margin: 0;"><?= $summary['scheduled'] ?></p>
            <p style="color: rgba(255, 255, 255, 0.7); font-size: 12px; margin: 8px 0 0 0;">Upcoming sessions</p>
          </div>
        </div>

        <div style="background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); padding: 24px; border-radius: 16px; box-shadow: 0 8px 24px rgba(139, 92, 246, 0.2); position: relative; overflow: hidden;">
          <div style="position: absolute; top: -30px; right: -30px; width: 120px; height: 120px; background: rgba(255, 255, 255, 0.05); border-radius: 50%;"></div>
          <div style="position: relative; z-index: 1;">
            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 12px;">
              <p style="color: rgba(255, 255, 255, 0.9); font-size: 14px; font-weight: 600; margin: 0;">Completed</p>
              <i class="fas fa-check-circle" style="color: rgba(255, 255, 255, 0.3); font-size: 24px;"></i>
            </div>
            <p style="font-size: 36px; font-weight: 800; color: white; margin: 0;"><?= $summary['completed'] ?></p>
            <p style="color: rgba(255, 255, 255, 0.7); font-size: 12px; margin: 8px 0 0 0;">Successfully completed</p>
          </div>
        </div>

        <div style="background: linear-gradient(135deg, #64748b 0%, #475569 100%); padding: 24px; border-radius: 16px; box-shadow: 0 8px 24px rgba(100, 116, 139, 0.2); position: relative; overflow: hidden;">
          <div style="position: absolute; top: -30px; right: -30px; width: 120px; height: 120px; background: rgba(255, 255, 255, 0.05); border-radius: 50%;"></div>
          <div style="position: relative; z-index: 1;">
            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 12px;">
              <p style="color: rgba(255, 255, 255, 0.9); font-size: 14px; font-weight: 600; margin: 0;">Cancelled</p>
              <i class="fas fa-times-circle" style="color: rgba(255, 255, 255, 0.3); font-size: 24px;"></i>
            </div>
            <p style="font-size: 36px; font-weight: 800; color: white; margin: 0;"><?= $summary['cancelled'] ?></p>
            <p style="color: rgba(255, 255, 255, 0.7); font-size: 12px; margin: 8px 0 0 0;">Cancelled sessions</p>
          </div>
        </div>
      </div>

      <!-- Filters -->
      <div style="background: white; padding: 24px; border-radius: 16px; margin-bottom: 32px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);">
        <form method="GET" style="display: flex; gap: 16px; flex-wrap: wrap; align-items: end;">
          <div style="flex: 1; min-width: 250px;">
            <label style="display: block; font-weight: 600; color: #0b3d2e; margin-bottom: 8px; font-size: 14px;">
              <i class="fas fa-search" style="color: #10b981; margin-right: 6px;"></i>Search Client
            </label>
            <input type="text" name="search" placeholder="Search by client name or email..." 
                   value="<?= htmlspecialchars($search) ?>"
                   style="width: 100%; padding: 12px 16px; border: 2px solid #e5e7eb; border-radius: 8px; font-size: 15px; transition: all 0.3s; font-family: inherit;">
          </div>
          
          <div style="min-width: 180px;">
            <label style="display: block; font-weight: 600; color: #0b3d2e; margin-bottom: 8px; font-size: 14px;">
              <i class="fas fa-filter" style="color: #10b981; margin-right: 6px;"></i>Status
            </label>
            <select name="status" style="width: 100%; padding: 12px 16px; border: 2px solid #e5e7eb; border-radius: 8px; font-size: 15px; transition: all 0.3s; font-family: inherit; background: white;">
              <option value="all" <?= $status === 'all' ? 'selected' : '' ?>>All Statuses</option>
              <option value="scheduled" <?= $status === 'scheduled' ? 'selected' : '' ?>>Scheduled</option>
              <option value="completed" <?= $status === 'completed' ? 'selected' : '' ?>>Completed</option>
              <option value="cancelled" <?= $status === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
            </select>
          </div>
          
          <button type="submit" style="background: linear-gradient(135deg, #10b981, #059669); color: white; padding: 12px 24px; border-radius: 8px; font-size: 15px; font-weight: 700; border: none; cursor: pointer; transition: all 0.3s; box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);">
            <i class="fas fa-search"></i> Search
          </button>
          <a href="/atasteofafricanmarketplace/dashboard/coach/sessions.php" style="background: white; color: #64748b; padding: 12px 24px; border-radius: 8px; font-size: 15px; font-weight: 700; border: 2px solid #e5e7eb; cursor: pointer; transition: all 0.3s; text-decoration: none; display: inline-block;">
            <i class="fas fa-times"></i> Clear
          </a>
        </form>
      </div>

      <!-- Sessions List -->
      <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-list" style="color: #10b981;"></i>
          Session History
        </h3>
        
        <?php if (empty($appointments)): ?>
          <div style="background: #f9fafb; padding: 60px 40px; border-radius: 12px; text-align: center;">
            <i class="fas fa-calendar-times" style="font-size: 64px; color: #cbd5e1; margin-bottom: 20px;"></i>
            <p style="color: #64748b; margin: 0; font-size: 16px;">No sessions found</p>
            <p style="color: #94a3b8; margin: 8px 0 0 0; font-size: 14px;">Try adjusting your filters or search terms</p>
          </div>
        <?php else: ?>
          <div style="display: flex; flex-direction: column; gap: 16px;">
            <?php foreach ($appointments as $appt): 
              $startTime = new DateTime($appt['starts_at']);
              $isUpcoming = $startTime > new DateTime();
              $statusColors = [
                'scheduled' => ['bg' => '#dbeafe', 'text' => '#1e40af', 'icon' => 'clock'],
                'completed' => ['bg' => '#d1fae5', 'text' => '#065f46', 'icon' => 'check-circle'],
                'cancelled' => ['bg' => '#f3f4f6', 'text' => '#4b5563', 'icon' => 'times-circle']
              ];
              $statusInfo = $statusColors[$appt['status']] ?? ['bg' => '#f3f4f6', 'text' => '#4b5563', 'icon' => 'question-circle'];
            ?>
              <div style="background: linear-gradient(135deg, #f0f9f6, #fef9e7); padding: 24px; border-radius: 12px; border: 2px solid #e5e7eb; transition: all 0.3s;" onmouseover="this.style.borderColor='#10b981'; this.style.boxShadow='0 4px 12px rgba(16, 185, 129, 0.2)'" onmouseout="this.style.borderColor='#e5e7eb'; this.style.boxShadow='none'">
                <div style="display: flex; justify-content: space-between; align-items: start; gap: 20px; flex-wrap: wrap;">
                  <!-- Client Info -->
                  <div style="display: flex; gap: 16px; align-items: center; flex: 1; min-width: 250px;">
                    <div style="width: 56px; height: 56px; background: linear-gradient(135deg, #10b981, #059669); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-weight: 700; font-size: 20px; flex-shrink: 0;">
                      <?= strtoupper(substr($appt['first_name'], 0, 1) . substr($appt['last_name'], 0, 1)) ?>
                    </div>
                    <div style="flex: 1;">
                      <div style="font-weight: 700; color: #0b3d2e; font-size: 16px; margin-bottom: 4px;">
                        <?= htmlspecialchars($appt['first_name'] . ' ' . $appt['last_name']) ?>
                      </div>
                      <div style="font-size: 13px; color: #64748b; display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
                        <span><i class="far fa-envelope" style="color: #10b981;"></i> <?= htmlspecialchars($appt['email']) ?></span>
                        <?php if ($appt['phone']): ?>
                        <span>•</span>
                        <span><i class="fas fa-phone" style="color: #10b981;"></i> <?= htmlspecialchars($appt['phone']) ?></span>
                        <?php endif; ?>
                      </div>
                    </div>
                  </div>

                  <!-- Session Details -->
                  <div style="display: flex; gap: 24px; align-items: center; flex-wrap: wrap;">
                    <div>
                      <div style="font-size: 12px; color: #64748b; font-weight: 600; text-transform: uppercase; margin-bottom: 4px;">Date & Time</div>
                      <div style="font-weight: 700; color: #0b3d2e; font-size: 14px;">
                        <i class="far fa-calendar" style="color: #10b981;"></i>
                        <?= $startTime->format('M j, Y') ?>
                      </div>
                      <div style="font-size: 13px; color: #64748b; margin-top: 2px;">
                        <i class="far fa-clock" style="color: #10b981;"></i>
                        <?= $startTime->format('g:i A') ?>
                      </div>
                    </div>

                    <div>
                      <div style="font-size: 12px; color: #64748b; font-weight: 600; text-transform: uppercase; margin-bottom: 4px;">Duration</div>
                      <div style="background: white; padding: 8px 16px; border-radius: 8px; font-weight: 700; color: #0b3d2e; font-size: 14px;">
                        <i class="fas fa-hourglass-half" style="color: #10b981;"></i>
                        <?= $appt['duration_minutes'] ?> min
                      </div>
                    </div>

                    <div>
                      <div style="font-size: 12px; color: #64748b; font-weight: 600; text-transform: uppercase; margin-bottom: 4px;">Status</div>
                      <div style="background: <?= $statusInfo['bg'] ?>; color: <?= $statusInfo['text'] ?>; padding: 8px 16px; border-radius: 8px; font-weight: 700; font-size: 13px; text-transform: uppercase; display: inline-flex; align-items: center; gap: 6px;">
                        <i class="fas fa-<?= $statusInfo['icon'] ?>"></i>
                        <?= ucfirst($appt['status']) ?>
                      </div>
                    </div>

                    <!-- Actions -->
                    <div>
                      <?php if ($appt['status'] === 'scheduled' && $isUpcoming): ?>
                        <button onclick="startSession(<?= $appt['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; box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3); display: flex; align-items: center; gap: 8px;">
                          <i class="fas fa-video"></i> Start Session
                        </button>
                      <?php elseif ($appt['status'] === 'completed'): ?>
                        <button onclick="viewNotes(<?= $appt['id'] ?>)" style="background: white; color: #10b981; padding: 10px 20px; border-radius: 8px; font-size: 14px; font-weight: 700; border: 2px solid #10b981; cursor: pointer; transition: all 0.3s; display: flex; align-items: center; gap: 8px;">
                          <i class="fas fa-file-medical-alt"></i> View Notes
                        </button>
                      <?php else: ?>
                        <span style="color: #94a3b8; font-size: 14px;">-</span>
                      <?php endif; ?>
                    </div>
                  </div>
                </div>

                <!-- Session Notes Preview (if completed) -->
                <?php if ($appt['status'] === 'completed' && !empty($appt['notes'])): ?>
                <div style="margin-top: 16px; padding-top: 16px; border-top: 1px solid #e5e7eb;">
                  <div style="font-size: 12px; color: #64748b; font-weight: 600; text-transform: uppercase; margin-bottom: 6px;">
                    <i class="fas fa-sticky-note"></i> Session Notes
                  </div>
                  <div style="color: #475569; font-size: 14px; line-height: 1.6;">
                    <?= htmlspecialchars(substr($appt['notes'], 0, 150)) ?><?= strlen($appt['notes']) > 150 ? '...' : '' ?>
                  </div>
                </div>
                <?php endif; ?>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </main>
  </div>
</div>

<style>
button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2) !important;
}

button:active {
  transform: translateY(0);
}

input:focus, select:focus {
  outline: none;
  border-color: #10b981;
  box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
}

a:hover {
  transform: translateY(-1px);
}
</style>

<script>
async function startSession(appointmentId) {
  if (!confirm('Start video session with this client?')) 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.');
  }
}

function viewNotes(appointmentId) {
  alert(`Viewing notes for session #${appointmentId}. Full notes viewer coming soon!`);
}

function exportSessions() {
  alert('Exporting sessions to CSV... Feature coming soon!');
}
</script>

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