<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
Kernel::handle(['auth' => false, 'public' => true]);
require_once __DIR__ . '/../../engine/Logger.php';

$b      = json_decode(file_get_contents('php://input'), true) ?? [];
$sector = trim($b['sector'] ?? ($_GET['sector'] ?? ''));
$query  = trim($b['query']  ?? ($_GET['q'] ?? ''));

$sectorMap = [
    'legal'    => ['service_provider'],
    'medical'  => ['doctor'],
    'business' => ['academic','service_provider'],
    'academic' => ['academic'],
    'pharmacy' => ['pharmacist'],
];

if (!$sector && $query) {
    $map = ['legal'=>'/قانون|محامي|عقد/i','medical'=>'/طبيب|مرض/i','business'=>'/مشروع|أعمال/i','academic'=>'/تعليم|درس|IGCSE/i'];
    foreach ($map as $s=>$p) { if (preg_match($p,$query)){$sector=$s;break;} }
}

$types = $sectorMap[$sector] ?? ['academic','service_provider','doctor'];

try {
    $in = implode(',', array_fill(0,count($types),'?'));
    $st = db()->prepare("SELECT id,name,provider_specialty,avg_rating,state,city FROM users WHERE user_type IN ($in) AND provider_verified=1 ORDER BY avg_rating DESC LIMIT 5");
    $st->execute($types);
    $experts = $st->fetchAll();
} catch (Throwable $e) { $experts = []; }

if (empty($experts)) {
    json_response(['success'=>true,'experts'=>[],'sector'=>$sector,
        'empty_state'=>['message'=>"لا خبراء في هذا المجال بعد — كن الأول! 🌟",'cta_label'=>'انضم كخبير','cta_url'=>'#providers']]);
}

json_response(['success'=>true,'experts'=>$experts,'sector'=>$sector,
    'actions'=>[['label'=>'احجز استشارة','url'=>'/api/booking/create.php','icon'=>'📅']]]);
