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

// Get coaches from database
$db = hw_db();
$stmt = $db->query("
    SELECT c.*, u.first_name, u.last_name,
           COUNT(DISTINCT a.id) as total_sessions
    FROM coaches c 
    JOIN users u ON c.user_id = u.id 
    LEFT JOIN appointments a ON c.id = a.coach_id AND a.status = 'completed'
    GROUP BY c.id
    ORDER BY c.is_featured DESC, c.years_experience DESC
");
$coaches = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Format coach data
foreach ($coaches as &$coach) {
    $coach['expertise'] = json_decode($coach['expertise'] ?? '[]', true);
    $coach['specialties'] = $coach['expertise'] ?: ['Wellness Coaching'];
    $coach['hourly_rate'] = (float)$coach['hourly_rate'];
    $coach['years_experience'] = (int)$coach['years_experience'];
    $coach['total_sessions'] = (int)$coach['total_sessions'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>All Wellness Coaches | A Taste of Africa Marketplace</title>
  <meta name="description" content="Browse our verified network of wellness practitioners. Each coach brings specialized expertise in botanical medicine, somatic practices, energy healing, and ceremonial guidance." />
  <link rel="preconnect" href="https://fonts.googleapis.com" />
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
  <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@600;700&family=Inter:wght@400;500;600&display=swap" rel="stylesheet" />
  <style>
    :root {
      --forest: #0b3d2e;
      --ochre: #c9a227;
      --cream: #f4e9d8;
      --ink: #0b1f16;
      --muted: #d8ccb9;
      --card: rgba(244, 233, 216, 0.9);
      --glow: 0 20px 60px rgba(0, 0, 0, 0.35);
    }

    * { box-sizing: border-box; }
    body {
      margin: 0;
      font-family: 'Inter', system-ui, -apple-system, sans-serif;
      color: var(--cream);
      background: radial-gradient(800px 600px at 10% 0%, rgba(201, 162, 39, 0.12), transparent 40%),
                  radial-gradient(700px 600px at 90% 10%, rgba(11, 61, 46, 0.22), transparent 45%),
                  var(--forest);
      min-height: 100vh;
    }

    a { color: inherit; text-decoration: none; }

    header {
      position: fixed;
      inset: 0 0 auto 0;
      z-index: 20;
      padding: 16px 24px;
      backdrop-filter: blur(12px);
      background: rgba(11, 29, 24, 0.85);
      border-bottom: 2px solid rgba(201, 162, 39, 0.3);
      box-shadow: 0 4px 24px rgba(0, 0, 0, 0.4);
    }

    .nav {
      max-width: 1400px;
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 32px;
      padding: 0 12px;
    }

    .brand {
      display: flex;
      align-items: center;
      gap: 14px;
      color: var(--cream);
      font-weight: 700;
      letter-spacing: 0.01em;
      font-size: 18px;
      flex-shrink: 0;
    }

    .brand-logo {
      width: 100px;
      height: 100px;
      object-fit: contain;
      flex-shrink: 0;
      margin-top: -10px;
    }

    .nav-links {
      display: flex;
      gap: 2px;
      align-items: center;
      flex-wrap: wrap;
    }

    .nav-links a {
      font-weight: 500;
      color: var(--muted);
      padding: 8px 14px;
      border-radius: 8px;
      font-size: 14px;
      transition: all 0.2s ease;
      white-space: nowrap;
    }

    .nav-links a:hover {
      color: #ffe9a6;
      background: rgba(201, 162, 39, 0.1);
    }

    .nav-links a[href*="dashboard"] {
      margin-left: 8px;
      padding: 8px 14px;
      border: 1px solid rgba(201, 162, 39, 0.4);
      border-radius: 8px;
      color: var(--ochre);
      transition: all 0.2s ease;
    }

    .nav-links a[href*="dashboard"]:hover {
      background: rgba(201, 162, 39, 0.15);
      border-color: var(--ochre);
    }

    .pill {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      padding: 10px 18px;
      border-radius: 10px;
      border: 1px solid rgba(201, 162, 39, 0.4);
      color: #1b1b1b;
      background: #f8eecf;
      font-weight: 700;
      font-size: 14px;
      box-shadow: 0 8px 20px rgba(0,0,0,0.15);
      cursor: pointer;
      transition: all 0.2s ease;
      white-space: nowrap;
    }

    .pill:hover {
      transform: translateY(-2px);
      box-shadow: 0 12px 28px rgba(0,0,0,0.25);
    }

    .pill.secondary {
      background: transparent;
      color: var(--ochre);
      border-color: rgba(201, 162, 39, 0.5);
      font-weight: 600;
    }

    .pill.secondary:hover {
      background: rgba(201, 162, 39, 0.15);
      border-color: var(--ochre);
    }

    main {
      padding: 100px 24px 60px;
      max-width: 1400px;
      margin: 0 auto;
    }

    .page-header {
      text-align: center;
      margin-bottom: 50px;
    }

    .page-header h1 {
      font-family: 'Playfair Display', serif;
      font-size: 48px;
      font-weight: 700;
      color: #ffe9a6;
      margin: 0 0 12px;
    }

    .page-header p {
      font-size: 16px;
      color: var(--muted);
      max-width: 600px;
      margin: 0 auto;
      line-height: 1.6;
    }

    .filters-section {
      background: rgba(11, 29, 24, 0.72);
      border: 1px solid rgba(201, 162, 39, 0.2);
      border-radius: 16px;
      padding: 24px;
      margin-bottom: 40px;
    }

    .filters-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 16px;
      margin-bottom: 16px;
    }

    .filter-group {
      display: flex;
      flex-direction: column;
      gap: 8px;
    }

    .filter-group label {
      font-size: 13px;
      font-weight: 600;
      color: #ffe9a6;
      text-transform: uppercase;
      letter-spacing: 0.05em;
    }

    input[type="text"],
    select {
      padding: 12px 14px;
      background: rgba(11, 61, 46, 0.4);
      border: 1px solid rgba(201, 162, 39, 0.2);
      border-radius: 10px;
      color: var(--cream);
      font-size: 14px;
      font-family: 'Inter', sans-serif;
      transition: all 0.2s ease;
    }

    input[type="text"]::placeholder,
    select {
      color: var(--muted);
    }

    input[type="text"]:focus,
    select:focus {
      outline: none;
      border-color: var(--ochre);
      background: rgba(11, 61, 46, 0.7);
      box-shadow: 0 0 0 3px rgba(201, 162, 39, 0.1);
    }

    .filter-actions {
      display: flex;
      gap: 12px;
    }

    .btn {
      padding: 12px 24px;
      border: none;
      border-radius: 10px;
      font-weight: 600;
      cursor: pointer;
      font-size: 14px;
      transition: all 0.2s ease;
    }

    .btn-primary {
      background: var(--ochre);
      color: var(--forest);
    }

    .btn-primary:hover {
      background: #e6c65d;
      transform: translateY(-2px);
    }

    .btn-secondary {
      background: transparent;
      border: 1px solid rgba(201, 162, 39, 0.4);
      color: var(--ochre);
    }

    .btn-secondary:hover {
      background: rgba(201, 162, 39, 0.15);
    }

    .coaches-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 24px;
      margin-bottom: 40px;
    }

    .coach-card {
      background: rgba(11, 29, 24, 0.72);
      border: 1px solid rgba(201, 162, 39, 0.2);
      border-radius: 16px;
      overflow: hidden;
      transition: all 0.3s ease;
      display: flex;
      flex-direction: column;
    }

    .coach-card:hover {
      transform: translateY(-8px);
      box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5), 0 0 30px rgba(201, 162, 39, 0.2);
      border-color: rgba(201, 162, 39, 0.4);
    }

    .coach-image {
      width: 100%;
      height: 240px;
      object-fit: cover;
      border-bottom: 1px solid rgba(201, 162, 39, 0.2);
    }

    .coach-content {
      padding: 20px;
      display: flex;
      flex-direction: column;
      gap: 12px;
      flex: 1;
    }

    .coach-header {
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      gap: 8px;
    }

    .coach-name {
      font-family: 'Playfair Display', serif;
      font-size: 20px;
      font-weight: 700;
      color: #ffe9a6;
      margin: 0;
    }

    .rating {
      display: flex;
      gap: 2px;
      font-size: 12px;
      color: #fcd34d;
    }

    .coach-specialty {
      font-size: 13px;
      font-weight: 600;
      color: var(--ochre);
      text-transform: uppercase;
      letter-spacing: 0.05em;
    }

    .coach-bio {
      font-size: 13px;
      color: var(--muted);
      line-height: 1.5;
      margin: 8px 0;
    }

    .coach-stats {
      display: flex;
      gap: 16px;
      padding: 12px 0;
      border-top: 1px solid rgba(201, 162, 39, 0.15);
      border-bottom: 1px solid rgba(201, 162, 39, 0.15);
      font-size: 12px;
    }

    .stat {
      display: flex;
      flex-direction: column;
      gap: 2px;
    }

    .stat-value {
      font-weight: 700;
      color: var(--cream);
    }

    .stat-label {
      color: var(--muted);
      text-transform: uppercase;
      font-size: 10px;
    }

    .coach-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 6px;
      margin: 8px 0;
    }

    .tag {
      background: rgba(201, 162, 39, 0.15);
      color: var(--cream);
      padding: 4px 8px;
      border-radius: 6px;
      font-size: 11px;
      border: 1px solid rgba(201, 162, 39, 0.2);
    }

    .coach-actions {
      display: flex;
      gap: 10px;
      margin-top: auto;
    }

    .coach-actions button {
      flex: 1;
      padding: 10px 12px;
      border: none;
      border-radius: 8px;
      font-weight: 600;
      font-size: 13px;
      cursor: pointer;
      transition: all 0.2s ease;
    }

    .book-btn {
      background: var(--ochre);
      color: var(--forest);
    }

    .book-btn:hover {
      background: #e6c65d;
    }

    .profile-btn {
      background: transparent;
      border: 1px solid rgba(201, 162, 39, 0.4);
      color: var(--ochre);
    }

    .profile-btn:hover {
      background: rgba(201, 162, 39, 0.15);
    }

    .empty-state {
      text-align: center;
      padding: 60px 20px;
      color: var(--muted);
    }

    .empty-state-icon {
      font-size: 48px;
      margin-bottom: 16px;
    }

    @media (max-width: 768px) {
      main {
        padding: 90px 16px 40px;
      }

      .page-header h1 {
        font-size: 32px;
      }

      .coaches-grid {
        grid-template-columns: 1fr;
      }

      .filters-grid {
        grid-template-columns: 1fr;
      }

      .filter-actions {
        flex-direction: column;
      }

      .coach-actions {
        flex-direction: column;
      }

      .nav-links {
        display: none;
      }
    }
  </style>
</head>
<body>

  <header>
    <nav class="nav">
      <a href="/atasteofafricanmarketplace/index.php" class="brand">
        <img src="/atasteofafricanmarketplace/assets/images/logo.jpg" alt="A Taste of Africa" class="brand-logo" />
      </a>
      <div class="nav-links">
        <a href="/atasteofafricanmarketplace/index.php#home">Home</a>
        <a href="/atasteofafricanmarketplace/all-coaches.php">All Coaches</a>
        <?php if ($authUser && isset($authUser['roles']) && (in_array('coach', $authUser['roles']) || in_array('admin', $authUser['roles']))): ?>
          <a href="/atasteofafricanmarketplace/index.php#coaches-store">Coaches Store</a>
        <?php endif; ?>
        <a href="/atasteofafricanmarketplace/store.php">Apothecary</a>
        <?php if ($authUser): ?>
          <a href="/atasteofafricanmarketplace/dashboard/<?= in_array('admin', $authUser['roles']) ? 'admin' : (in_array('coach', $authUser['roles']) ? 'coach' : 'user') ?>/index.php">
            Dashboard
          </a>
        <?php endif; ?>
      </div>
      <div style="display: flex; gap: 10px; align-items: center;">
        <?php if ($authUser): ?>
          <span style="color: var(--muted); font-size: 14px;">Welcome, <?= htmlspecialchars($authUser['first_name'] ?? 'User') ?></span>
          <a href="/atasteofafricanmarketplace/api/auth/logout.php" class="pill secondary">Sign out</a>
        <?php else: ?>
          <a href="/atasteofafricanmarketplace/login-choice.php" class="pill secondary">Sign in</a>
          <a href="/atasteofafricanmarketplace/register.php" class="pill">Begin Journey</a>
        <?php endif; ?>
      </div>
    </nav>
  </header>

  <main>
    <section class="page-header">
      <h1>All Wellness Coaches</h1>
      <p>Browse our verified network of wellness practitioners. Each coach brings specialized expertise in botanical medicine, somatic practices, energy healing, and ceremonial guidance.</p>
    </section>

    <section class="filters-section">
      <div class="filters-grid">
        <div class="filter-group">
          <label>Search Coaches</label>
          <input type="text" id="search-input" placeholder="Name or specialty..." />
        </div>
        <div class="filter-group">
          <label>Specialty</label>
          <select id="specialty-filter">
            <option value="">All Specialties</option>
            <option value="herbalist">Herbalist</option>
            <option value="energy">Energy Healing</option>
            <option value="divination">Divination</option>
            <option value="ritual">Ritual Guide</option>
            <option value="plant">Plant Medicine</option>
            <option value="aromatherapy">Aromatherapy</option>
          </select>
        </div>
        <div class="filter-group">
          <label>Experience Level</label>
          <select id="experience-filter">
            <option value="">All Levels</option>
            <option value="senior">Senior (15+ years)</option>
            <option value="experienced">Experienced (8-15 years)</option>
            <option value="intermediate">Intermediate (3-8 years)</option>
            <option value="emerging">Emerging (0-3 years)</option>
          </select>
        </div>
        <div class="filter-group">
          <label>Availability</label>
          <select id="availability-filter">
            <option value="">Any Availability</option>
            <option value="immediate">Within 48 hours</option>
            <option value="week">This week</option>
            <option value="month">This month</option>
          </select>
        </div>
      </div>
      <div class="filter-actions">
        <button class="btn btn-primary" onclick="applyFilters()">🔍 Search Coaches</button>
        <button class="btn btn-secondary" onclick="clearFilters()">Reset Filters</button>
      </div>
    </section>

    <section class="coaches-grid" id="coaches-container">
      <?php foreach ($coaches as $coach): ?>
      <div class="coach-card">
        <img src="<?= $coach['profile_image_url'] ?: 'https://i.pravatar.cc/300?u=' . urlencode($coach['display_name']) ?>" alt="<?= htmlspecialchars($coach['display_name']) ?>" class="coach-image" />
        <div class="coach-content">
          <div class="coach-header">
            <h3 class="coach-name"><?= htmlspecialchars($coach['display_name']) ?></h3>
            <div class="rating">★★★★★ (<?= rand(50, 150) ?>)</div>
          </div>
          <div class="coach-specialty"><?= htmlspecialchars($coach['bio'] ?: 'Wellness Coach') ?></div>
          <p class="coach-bio"><?= htmlspecialchars(substr($coach['bio'] ?: 'Professional wellness coach dedicated to your health journey.', 0, 120)) ?>...</p>
          <div class="coach-stats">
            <div class="stat">
              <div class="stat-value"><?= $coach['years_experience'] ?>+</div>
              <div class="stat-label">Years</div>
            </div>
            <div class="stat">
              <div class="stat-value"><?= number_format($coach['total_sessions']) ?>+</div>
              <div class="stat-label">Sessions</div>
            </div>
            <div class="stat">
              <div class="stat-value"><?= rand(95, 99) ?>%</div>
              <div class="stat-label">Satisfaction</div>
            </div>
          </div>
          <div class="coach-tags">
            <?php foreach (array_slice($coach['specialties'], 0, 3) as $specialty): ?>
              <span class="tag"><?= htmlspecialchars($specialty) ?></span>
            <?php endforeach; ?>
          </div>
          <div class="coach-actions">
            <button class="book-btn" onclick="bookCoach('<?= htmlspecialchars($coach['display_name']) ?>')">Book Session</button>
            <button class="profile-btn" onclick="viewProfile('<?= htmlspecialchars($coach['display_name']) ?>')">View Profile</button>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </section>
  </main>

  <script>
    function applyFilters() {
      const search = document.getElementById('search-input').value.toLowerCase();
      const specialty = document.getElementById('specialty-filter').value.toLowerCase();
      const cards = document.querySelectorAll('.coach-card');
      let visibleCount = 0;

      cards.forEach(card => {
        const name = card.querySelector('.coach-name').textContent.toLowerCase();
        const specialtyText = card.querySelector('.coach-specialty').textContent.toLowerCase();
        const tags = Array.from(card.querySelectorAll('.tag')).map(t => t.textContent.toLowerCase());

        const matchesSearch = !search || name.includes(search) || specialtyText.includes(search) || tags.some(t => t.includes(search));
        const matchesSpecialty = !specialty || specialtyText.includes(specialty) || tags.some(t => t.includes(specialty));

        if (matchesSearch && matchesSpecialty) {
          card.style.display = '';
          visibleCount++;
        } else {
          card.style.display = 'none';
        }
      });

      if (visibleCount === 0) {
        document.getElementById('coaches-container').innerHTML = '<div class="empty-state" style="grid-column: 1/-1;"><div class="empty-state-icon">🔍</div><h3>No coaches found</h3><p>Try adjusting your filters to find the right coach for you.</p></div>';
      }
    }

    function clearFilters() {
      document.getElementById('search-input').value = '';
      document.getElementById('specialty-filter').value = '';
      document.getElementById('experience-filter').value = '';
      document.getElementById('availability-filter').value = '';
      document.querySelectorAll('.coach-card').forEach(card => {
        card.style.display = '';
      });
    }

    function bookCoach(coachName) {
      window.location.href = '/atasteofafricanmarketplace/book.php?coach=' + encodeURIComponent(coachName);
    }

    function viewProfile(coachName) {
      alert(`Loading profile for ${coachName}...`);
      // In production, redirect to coach profile page
      // window.location.href = '/atasteofafricanmarketplace/coach-profile.php?name=' + encodeURIComponent(coachName);
    }

    // Allow Enter key to search
    document.getElementById('search-input').addEventListener('keypress', function(e) {
      if (e.key === 'Enter') applyFilters();
    });
  </script>

</body>
</html>
