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

$providerId = (int)($_GET['id'] ?? 0);
if (!$providerId) Kernel::fail('id_required', '', 400);

try { // start provider query
$prov = db()->prepare("
    SELECT u.id, u.name, u.provider_specialty, u.avg_rating, u.state, u.city,
           u.provider_verified, u.user_type, u.created_at,
           COUNT(DISTINCT br.id) AS review_count,
           COUNT(DISTINCT bk.id) AS completed_bookings
    FROM users u
    LEFT JOIN booking_ratings br ON br.provider_id = u.id
    LEFT JOIN bookings bk ON bk.provider_id = u.id AND bk.status = 'completed'
    WHERE u.id = ? AND u.provider_verified = 1
    GROUP BY u.id LIMIT 1
");
$prov->execute([$providerId]);
$provider = $prov->fetch();

if (!$provider) Kernel::fail('not_found', 'المزود غير موجود', 404);

// Get active services
$svc = db()->prepare("SELECT id, title, description, pricing_type, price_sdg, duration_min, location_type, category FROM provider_services WHERE provider_id=? AND is_active=1 LIMIT 50");
$svc->execute([$providerId]);
$services = $svc->fetchAll();

// Get latest reviews
$rev = db()->prepare("SELECT br.rating, br.comment, br.created_at, CASE WHEN br.is_anonymous=1 THEN 'مستخدم مجهول' ELSE u.name END AS reviewer_name FROM booking_ratings br JOIN users u ON u.id=br.user_id WHERE br.provider_id=? ORDER BY br.created_at DESC LIMIT 5");
$rev->execute([$providerId]);
$reviews = $rev->fetchAll();

// Empty state CTA if no services
$emptyCta = empty($services) ? [
    'message' => 'المزود لم يُضف خدماته بعد',
    'suggestion' => 'تواصل مباشرة عبر الاستشارة',
] : null;

json_response([
    'success'  => true,
    'provider' => $provider,
    'services' => $services,
    'reviews'  => $reviews,
    'empty_cta'=> $emptyCta,
    'actions'  => [
        ['label'=>'احجز الآن','url'=>"/api/booking/create.php",'icon'=>'📅'],
        ['label'=>'أرسل رسالة','url'=>'#consultation','icon'=>'💬'],
    ],
]);
} catch(Throwable $e) { error_log('[profile] '.$e->getMessage()); Kernel::fail('db_error', '', 500); }
