<?php
// ════════════════════════════════════════════════════════════════
// CLOSED BETA GATE — Consultation temporarily disabled
// Until api/consultation/start.php is migrated to Kernel + Reservation
// Remove this block when Phase 3 Replace is complete
// ════════════════════════════════════════════════════════════════
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';

$_consult_enabled = (int)PricingEngine::getSetting('enable_consultation_booking', 0);
if (!$_consult_enabled) {
        http_response_code(503);
    echo json_encode([
        'error'   => 'service_temporarily_unavailable',
        'message' => 'خدمة الاستشارات ستتوفر قريباً. يمكنك حجز موعد عيادة حالياً.',
        'code'    => 'consultation_beta_disabled',
    ], JSON_UNESCAPED_UNICODE);
    exit;
}
unset($_consult_enabled);
// ════════════════════════════════════════════════════════════════

require_once __DIR__ . '/../../config.php';
$ctx = Kernel::handle(['auth' => true, 'rate' => 'api']);
$u   = $ctx['user'];
$b      = json_decode(file_get_contents('php://input'), true) ?? [];
$action = $b['action'] ?? 'start';

// ── بدء استشارة جديدة ──────────────────────────────────────────
if ($action === 'start') {
    $provider_id = (int)($b['provider_id'] ?? 0);
    $subject     = mb_substr(trim($b['subject'] ?? ''), 0, 200);
    $type        = in_array($b['type'] ?? '', ['medical','educational','service','general']) ? $b['type'] : 'general';
    $is_paid     = (bool)($b['is_paid'] ?? false);

    if (!$provider_id || !$subject)
        Kernel::fail('missing_fields', '', 400);

    // تحقق من المزود
    $prov = db()->prepare('SELECT id, name, user_type, provider_verified FROM users WHERE id = ? AND user_type != "user" AND provider_verified = 1 LIMIT 1');
    $prov->execute([$provider_id]);
    $provider = $prov->fetch();
    if (!$provider)
        Kernel::fail('provider_not_found', 'المزود غير موجود أو غير موثّق', 404);

    // إنشاء جلسة استشارة
    db()->prepare(
        'INSERT INTO provider_consultations (user_id, provider_id, type, subject, is_paid, status)
         VALUES (?, ?, ?, ?, ?, "open")'
    )->execute([$u['id'], $provider_id, $type, $subject, (int)$is_paid]);

    $consult_id = (int)db()->lastInsertId();

    // إشعار المزود
    $fcm = get_user_token($provider_id);
    if ($fcm) send_push($fcm, '💬 استشارة جديدة!', "طلب استشارة من {$u['name']}: $subject", ['tab' => 'consultations', 'id' => (string)$consult_id]);
    save_notification($provider_id, 'consultation_request', 'طلب استشارة جديد', "{$u['name']} يطلب استشارتك في: $subject");

    json_response(['success' => true, 'consultation_id' => $consult_id, 'message' => 'تم إرسال طلب الاستشارة. سيرد المزود قريباً.']);
}

// ── قائمة استشاراتي ────────────────────────────────────────────
if ($action === 'list') {
    $as_provider = (bool)($b['as_provider'] ?? false);
    if ($as_provider && in_array($u['user_type'], ['teacher','doctor','pharmacist','service_provider','academic','hospital'])) {
        $st = db()->prepare(
            'SELECT c.*, u.name AS client_name, u.email AS client_email
             FROM provider_consultations c JOIN users u ON u.id=c.user_id
             WHERE c.provider_id = ? ORDER BY c.updated_at DESC LIMIT 50'
        );
        $st->execute([$u['id']]);
    } else {
        $st = db()->prepare(
            'SELECT c.*, u.name AS provider_name, u.user_type, u.provider_verified
             FROM provider_consultations c JOIN users u ON u.id=c.provider_id
             WHERE c.user_id = ? ORDER BY c.updated_at DESC LIMIT 50'
        );
        $st->execute([$u['id']]);
    }
    json_response(['success' => true, 'consultations' => $st->fetchAll()]);
}

Kernel::fail('unknown_action', '', 400);
