<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['GET']);

$q = hw_sanitize_string($_GET['q'] ?? '');
$expertise = hw_sanitize_string($_GET['expertise'] ?? '');
$limit = (int)($_GET['limit'] ?? 12);
$offset = (int)($_GET['offset'] ?? 0);
if ($limit < 1 || $limit > 100) $limit = 12;
if ($offset < 0) $offset = 0;

try {
    $pdo = hw_db();

    $where = [];
    $params = [];

    if ($q !== '') {
        $where[] = '(c.display_name LIKE ? OR c.bio LIKE ? OR c.certifications LIKE ?)';
        $like = '%' . $q . '%';
        $params[] = $like; $params[] = $like; $params[] = $like;
    }

    if ($expertise !== '') {
        // Expect c.expertise to be a JSON array of strings
        $where[] = "JSON_CONTAINS(c.expertise, JSON_QUOTE(?), '$')";
        $params[] = $expertise;
    }

    $whereSql = count($where) ? ('WHERE ' . implode(' AND ', $where)) : '';

    // Count total
    $stmt = $pdo->prepare("SELECT COUNT(1) AS cnt FROM coaches c $whereSql");
    $stmt->execute($params);
    $total = (int)($stmt->fetch()['cnt'] ?? 0);

    // Fetch paginated list
    $sql = "SELECT c.id, c.display_name, c.bio, c.certifications, c.expertise, c.hourly_rate, c.created_at,
                   u.first_name, u.last_name,
                   (SELECT COUNT(1) FROM coach_availability a WHERE a.coach_id = c.id) AS availability_slots
            FROM coaches c
            JOIN users u ON u.id = c.user_id
            $whereSql
            ORDER BY c.created_at DESC
            LIMIT ? OFFSET ?";
    $stmt = $pdo->prepare($sql);
    $exec = array_merge($params, [$limit, $offset]);
    $stmt->execute($exec);

    $rows = $stmt->fetchAll();
    $coaches = [];
    foreach ($rows as $r) {
        $coaches[] = [
            'id' => (int)$r['id'],
            'display_name' => $r['display_name'],
            'first_name' => $r['first_name'],
            'last_name' => $r['last_name'],
            'bio' => $r['bio'],
            'certifications' => $r['certifications'],
            'expertise' => $r['expertise'] ? json_decode($r['expertise'], true) : [],
            'hourly_rate' => $r['hourly_rate'] !== null ? (float)$r['hourly_rate'] : null,
            'has_availability' => ((int)$r['availability_slots']) > 0,
            'created_at' => $r['created_at'],
        ];
    }

    hw_json([
        'total' => $total,
        'limit' => $limit,
        'offset' => $offset,
        'coaches' => $coaches,
    ]);
} catch (Throwable $e) {
    hw_json(['message' => 'Server error', 'error' => $e->getMessage()], 500);
}
