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

hw_require_method(['GET']);

$search = $_GET['search'] ?? '';
$specialty = $_GET['specialty'] ?? '';
$experience = $_GET['experience'] ?? '';
$branch = $_GET['branch'] ?? '';

try {
    $pdo = hw_db();
    
    // Build query with filters
    $where = ['c.id IS NOT NULL'];
    $params = [];
    
    if ($search) {
        $where[] = '(c.display_name LIKE ? OR c.bio LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ?)';
        $searchTerm = "%$search%";
        $params = array_merge($params, [$searchTerm, $searchTerm, $searchTerm, $searchTerm]);
    }
    
    if ($specialty) {
        $where[] = 'JSON_SEARCH(c.expertise, "one", ?) IS NOT NULL';
        $params[] = "%$specialty%";
    }
    
    if ($experience) {
        $where[] = 'c.years_experience >= ?';
        $params[] = (int)$experience;
    }
    
    if ($branch) {
        $where[] = 'c.tree_branch = ?';
        $params[] = $branch;
    }
    
    $whereClause = implode(' AND ', $where);
    
    // Get coaches with full details
    $stmt = $pdo->prepare("
        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'
        WHERE $whereClause
        GROUP BY c.id
        ORDER BY c.is_featured DESC, c.years_experience DESC
    ");
    $stmt->execute($params);
    $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['certifications'] = explode(',', $coach['certifications'] ?? 'Certified Wellness Coach');
        $coach['hourly_rate'] = (float)$coach['hourly_rate'];
        $coach['years_experience'] = (int)$coach['years_experience'];
        $coach['tree_position_x'] = (int)$coach['tree_position_x'];
        $coach['tree_position_y'] = (int)$coach['tree_position_y'];
        $coach['total_sessions'] = (int)$coach['total_sessions'];
    }
    
    // Get available specialties for filtering from expertise JSON
    $stmt = $pdo->query("SELECT DISTINCT expertise FROM coaches WHERE expertise IS NOT NULL AND expertise != ''");
    $expertiseData = $stmt->fetchAll(PDO::FETCH_COLUMN);
    $availableSpecialties = [];
    foreach ($expertiseData as $expertise) {
        $decoded = json_decode($expertise, true);
        if (is_array($decoded)) {
            $availableSpecialties = array_merge($availableSpecialties, $decoded);
        }
    }
    $availableSpecialties = array_unique($availableSpecialties);
    
    // Get tree branches for filtering
    $branches = ['roots', 'trunk', 'branches', 'leaves', 'fruits'];
    
    hw_json([
        'success' => true,
        'tree_data' => [
            'roots' => array_filter($coaches, fn($c) => $c['tree_branch'] === 'roots'),
            'trunk' => array_filter($coaches, fn($c) => $c['tree_branch'] === 'trunk'),
            'branches' => array_filter($coaches, fn($c) => $c['tree_branch'] === 'branches'),
            'leaves' => array_filter($coaches, fn($c) => $c['tree_branch'] === 'leaves'),
            'fruits' => array_filter($coaches, fn($c) => $c['tree_branch'] === 'fruits')
        ],
        'coaches' => $coaches,
        'filters' => [
            'specialties' => $availableSpecialties,
            'branches' => $branches,
            'experience_levels' => [
                ['value' => 5, 'label' => '5+ years'],
                ['value' => 10, 'label' => '10+ years'],
                ['value' => 15, 'label' => '15+ years'],
                ['value' => 20, 'label' => '20+ years']
            ]
        ]
    ]);
} catch (Throwable $e) {
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}