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

$page_title = 'My Clients | Coach Dashboard';
$page_description = 'View and manage your clients';
$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;
}

// Get clients (users who have had appointments with this coach)
$stmt = $db->prepare("
    SELECT 
        u.id,
        u.first_name,
        u.last_name,
        u.email,
        u.phone,
        u.created_at,
        COUNT(DISTINCT a.id) as total_sessions,
        SUM(CASE WHEN a.status = 'completed' THEN 1 ELSE 0 END) as completed_sessions,
        MAX(a.starts_at) as last_session_date
    FROM users u
    INNER JOIN appointments a ON u.id = a.user_id
    WHERE a.coach_id = ?
    GROUP BY u.id, u.first_name, u.last_name, u.email, u.phone, u.created_at
    ORDER BY last_session_date DESC
");
$stmt->execute([$coach['id']]);
$clients = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get stats
$totalClients = count($clients);
$activeClients = 0;
foreach ($clients as $client) {
    if ($client['last_session_date']) {
        $lastSession = new DateTime($client['last_session_date']);
        $now = new DateTime();
        $diff = $now->diff($lastSession);
        if ($diff->days <= 30) {
            $activeClients++;
        }
    }
}
?>
<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"><i class="fas fa-calendar-check"></i>Sessions</a>
      <a href="/atasteofafricanmarketplace/dashboard/coach/clients.php" class="active"><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 Clients</h1>
          <p style="font-size: 16px; color: #64748b; margin: 0;">View and manage your client relationships</p>
        </div>
        <button onclick="exportClients()" 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 Client List
        </button>
      </div>

      <!-- Stats Cards -->
      <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 20px; margin-bottom: 32px;">
        <div style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); padding: 32px; 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: 16px;">
              <div>
                <p style="color: rgba(255, 255, 255, 0.9); font-size: 14px; font-weight: 600; margin: 0 0 8px 0;">Total Clients</p>
                <p style="font-size: 48px; font-weight: 800; color: white; margin: 0; line-height: 1;"><?= $totalClients ?></p>
              </div>
              <div style="width: 64px; height: 64px; background: rgba(255, 255, 255, 0.15); border-radius: 16px; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(10px);">
                <i class="fas fa-users" style="color: white; font-size: 28px;"></i>
              </div>
            </div>
            <p style="color: rgba(255, 255, 255, 0.7); font-size: 13px; margin: 0;">All time client relationships</p>
          </div>
        </div>

        <div style="background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); padding: 32px; 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: 16px;">
              <div>
                <p style="color: rgba(255, 255, 255, 0.9); font-size: 14px; font-weight: 600; margin: 0 0 8px 0;">Active Clients</p>
                <p style="font-size: 48px; font-weight: 800; color: white; margin: 0; line-height: 1;"><?= $activeClients ?></p>
              </div>
              <div style="width: 64px; height: 64px; background: rgba(255, 255, 255, 0.15); border-radius: 16px; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(10px);">
                <i class="fas fa-user-check" style="color: white; font-size: 28px;"></i>
              </div>
            </div>
            <p style="color: rgba(255, 255, 255, 0.7); font-size: 13px; margin: 0;">Sessions within last 30 days</p>
          </div>
        </div>

        <div style="background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); padding: 32px; 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: 16px;">
              <div>
                <p style="color: rgba(255, 255, 255, 0.9); font-size: 14px; font-weight: 600; margin: 0 0 8px 0;">Engagement Rate</p>
                <p style="font-size: 48px; font-weight: 800; color: white; margin: 0; line-height: 1;"><?= $totalClients > 0 ? round(($activeClients / $totalClients) * 100) : 0 ?>%</p>
              </div>
              <div style="width: 64px; height: 64px; background: rgba(255, 255, 255, 0.15); border-radius: 16px; display: flex; align-items: center; justify-content: center; backdrop-filter: blur(10px);">
                <i class="fas fa-chart-line" style="color: white; font-size: 28px;"></i>
              </div>
            </div>
            <p style="color: rgba(255, 255, 255, 0.7); font-size: 13px; margin: 0;">Active vs total clients</p>
          </div>
        </div>
      </div>

      <!-- Clients 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-address-book" style="color: #10b981;"></i>
          Client Directory
        </h3>
        
        <?php if (empty($clients)): ?>
          <div style="background: #f9fafb; padding: 60px 40px; border-radius: 12px; text-align: center;">
            <div style="width: 96px; height: 96px; background: linear-gradient(135deg, #f0f9f6, #e0f2fe); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 24px;">
              <i class="fas fa-users" style="font-size: 48px; color: #10b981;"></i>
            </div>
            <h4 style="font-size: 20px; font-weight: 700; color: #0b3d2e; margin: 0 0 12px 0;">No clients yet</h4>
            <p style="color: #64748b; margin: 0; font-size: 15px;">Your clients will appear here once they book sessions with you.</p>
          </div>
        <?php else: ?>
          <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(360px, 1fr)); gap: 20px;">
            <?php foreach ($clients as $client): 
              $lastSessionDate = $client['last_session_date'] ? new DateTime($client['last_session_date']) : null;
              $isActive = false;
              if ($lastSessionDate) {
                $diff = (new DateTime())->diff($lastSessionDate);
                $isActive = $diff->days <= 30;
              }
            ?>
              <div style="background: linear-gradient(135deg, #f0f9f6, #fef9e7); padding: 24px; border-radius: 16px; border: 2px solid #e5e7eb; transition: all 0.3s; position: relative;" onmouseover="this.style.borderColor='#10b981'; this.style.boxShadow='0 8px 20px rgba(16, 185, 129, 0.15)'" onmouseout="this.style.borderColor='#e5e7eb'; this.style.boxShadow='none'">
                <?php if ($isActive): ?>
                <div style="position: absolute; top: 16px; right: 16px; background: linear-gradient(135deg, #10b981, #059669); color: white; padding: 6px 14px; border-radius: 20px; font-size: 11px; font-weight: 700; text-transform: uppercase; box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);">
                  <i class="fas fa-circle" style="font-size: 6px; margin-right: 6px;"></i>Active
                </div>
                <?php endif; ?>
                
                <!-- Client Header -->
                <div style="display: flex; gap: 16px; align-items: start; margin-bottom: 20px;">
                  <div style="width: 64px; height: 64px; background: linear-gradient(135deg, #10b981, #059669); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-weight: 800; font-size: 22px; flex-shrink: 0; box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);">
                    <?= strtoupper(substr($client['first_name'], 0, 1) . substr($client['last_name'], 0, 1)) ?>
                  </div>
                  <div style="flex: 1;">
                    <h4 style="font-size: 18px; font-weight: 700; color: #0b3d2e; margin: 0 0 6px 0;">
                      <?= htmlspecialchars($client['first_name'] . ' ' . $client['last_name']) ?>
                    </h4>
                    <p style="color: #64748b; font-size: 13px; margin: 0;">
                      <i class="far fa-calendar" style="color: #10b981;"></i>
                      Member since <?= date('M Y', strtotime($client['created_at'])) ?>
                    </p>
                  </div>
                </div>

                <!-- Contact Info -->
                <div style="background: white; padding: 16px; border-radius: 12px; margin-bottom: 16px;">
                  <div style="display: flex; flex-direction: column; gap: 10px;">
                    <div style="display: flex; align-items: center; gap: 10px; font-size: 14px;">
                      <i class="far fa-envelope" style="color: #10b981; width: 18px;"></i>
                      <span style="color: #475569; word-break: break-all;"><?= htmlspecialchars($client['email']) ?></span>
                    </div>
                    <?php if ($client['phone']): ?>
                    <div style="display: flex; align-items: center; gap: 10px; font-size: 14px;">
                      <i class="fas fa-phone" style="color: #10b981; width: 18px;"></i>
                      <span style="color: #475569;"><?= htmlspecialchars($client['phone']) ?></span>
                    </div>
                    <?php endif; ?>
                  </div>
                </div>

                <!-- Session Stats -->
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; margin-bottom: 16px;">
                  <div style="background: white; padding: 12px; border-radius: 10px; text-align: center;">
                    <div style="font-size: 24px; font-weight: 800; color: #10b981; margin-bottom: 4px;"><?= $client['total_sessions'] ?></div>
                    <div style="font-size: 11px; color: #64748b; font-weight: 600; text-transform: uppercase;">Total Sessions</div>
                  </div>
                  <div style="background: white; padding: 12px; border-radius: 10px; text-align: center;">
                    <div style="font-size: 24px; font-weight: 800; color: #8b5cf6; margin-bottom: 4px;"><?= $client['completed_sessions'] ?></div>
                    <div style="font-size: 11px; color: #64748b; font-weight: 600; text-transform: uppercase;">Completed</div>
                  </div>
                </div>

                <!-- Last Session -->
                <?php if ($lastSessionDate): ?>
                <div style="background: white; padding: 12px 16px; border-radius: 10px; margin-bottom: 16px; display: flex; align-items: center; gap: 12px;">
                  <i class="fas fa-clock" style="color: #10b981; font-size: 16px;"></i>
                  <div style="flex: 1;">
                    <div style="font-size: 11px; color: #64748b; font-weight: 600; text-transform: uppercase; margin-bottom: 2px;">Last Session</div>
                    <div style="font-size: 13px; font-weight: 700; color: #0b3d2e;">
                      <?= $lastSessionDate->format('M j, Y') ?> at <?= $lastSessionDate->format('g:i A') ?>
                    </div>
                  </div>
                </div>
                <?php endif; ?>

                <!-- Actions -->
                <div style="display: flex; gap: 8px;">
                  <a href="/atasteofafricanmarketplace/dashboard/coach/sessions.php?search=<?= urlencode($client['email']) ?>" style="flex: 1; background: linear-gradient(135deg, #10b981, #059669); color: white; padding: 12px; border-radius: 10px; 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); text-align: center; text-decoration: none; display: flex; align-items: center; justify-content: center; gap: 8px;">
                    <i class="fas fa-calendar-check"></i> View Sessions
                  </a>
                  <button onclick="messageClient(<?= $client['id'] ?>)" style="background: white; color: #10b981; padding: 12px 16px; border-radius: 10px; font-size: 14px; font-weight: 700; border: 2px solid #10b981; cursor: pointer; transition: all 0.3s;">
                    <i class="fas fa-comment"></i>
                  </button>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </main>
  </div>
</div>

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

button:active, a:active {
  transform: translateY(0);
}
</style>

<script>
function messageClient(clientId) {
  alert(`Messaging feature for client #${clientId} coming soon!`);
}

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

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