<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/SafetyEngine.php';
require_once __DIR__ . '/../../engine/Kernel.php';        // BRIDGE
require_once __DIR__ . '/../../engine/BillingEngine.php'; // BRIDGE: AI limit
$ctx = Kernel::handle(['auth' => true, 'rate' => 'api']);
$u   = $ctx['user'];
$b      = json_decode(file_get_contents('php://input'), true) ?? [];
$action = $b['action'] ?? 'send';

// ── إرسال رسالة ────────────────────────────────────────────────
if ($action === 'send') {
    $consult_id = (int)($b['consultation_id'] ?? 0);
    $message    = mb_substr(trim($b['message'] ?? ''), 0, 2000);
    if (!$consult_id || !$message) Kernel::fail('missing_fields', '', 400);

    // تحقق من صلاحية
    $c = db()->prepare('SELECT * FROM provider_consultations WHERE id = ? LIMIT 1');
    $c->execute([$consult_id]);
    $consult = $c->fetch();
    if (!$consult || !in_array($u['id'], [(int)$consult['user_id'], (int)$consult['provider_id']]))
        Kernel::fail('forbidden', '', 403);

    $sender_type = $u['id'] == $consult['provider_id'] ? 'provider' : 'user';

    db()->prepare('INSERT INTO consultation_messages (consultation_id, sender_id, sender_type, message) VALUES (?,?,?,?)')
        ->execute([$consult_id, $u['id'], $sender_type, $message]);

    db()->prepare('UPDATE provider_consultations SET updated_at = NOW(), status = "active" WHERE id = ?')
        ->execute([$consult_id]);

    // إشعار الطرف الآخر
    $notify_id = $sender_type === 'provider' ? (int)$consult['user_id'] : (int)$consult['provider_id'];
    $fcm = get_user_token($notify_id);
    if ($fcm) send_push($fcm, '💬 رسالة جديدة', mb_substr($message, 0, 80), ['consultation_id' => (string)$consult_id]);
    save_notification($notify_id, 'consultation_message', 'رسالة جديدة في استشارتك', mb_substr($message, 0, 100));

    // إذا المزود يرد — Gemini يُرفّق نصيحة إضافية للمستخدم
    $ai_suggestion = '';
    if ($sender_type === 'provider' && $consult['type'] === 'medical' && strlen($message) > 50) {
        // BRIDGE: AI daily limit check before ask_ai
        $_msg_plan = $u['plan_key'] ?? 'free';
        $_msg_limit = BillingEngine::checkAILimit((int)$u['id'], $_msg_plan);
        if (!empty($_msg_limit['exceeded'])) {
            $ai_suggestion = ''; // skip AI if daily limit reached
        } else {
                // Safety: evaluate user input before AI call
        $_se_in = SafetyEngine::evaluateInput($message ?? '', ['endpoint' => 'consultation/message.php']);
        if ($_se_in['action'] === SafetyEngine::BLOCK) {
            Logger::warn('ai_input_blocked', ['endpoint' => 'consultation/message.php']);
            $ai_suggestion = null;
        } elseif ($_se_in['action'] === SafetyEngine::WARN) {
            $ai_suggestion = SafetyEngine::emergencyResponse();
        } else {
            $ai_suggestion = ask_ai(
            "الطبيب أجاب على استشارة طبية: \"$message\"\nأضف تحذيراً مختصراً جداً (جملة واحدة) للمريض إذا لزم.",
            'أنت مساعد طبي. أضف فقط تحذير ضروري أو لا تضف شيئاً.',
            'fast', 60, 0.3
        );
    if ($ai_suggestion) Logger::aiUsage((int)$u['id'], 'consultation_ai', ['service' => 'consultation']);

            // Safety: evaluate AI output
            if ($ai_suggestion) {
                $_se_out = SafetyEngine::evaluateOutput($ai_suggestion, 'medical');
                if ($_se_out['action'] === SafetyEngine::WARN && !empty($_se_out['replace'])) {
                    $ai_suggestion = $_se_out['replace'];
                } elseif ($_se_out['action'] === SafetyEngine::BLOCK) {
                    $ai_suggestion = null;
                }
            }
        }

        } // end AI limit check
    }

    json_response(['success' => true, 'ai_note' => $ai_suggestion]);
}

// ── قراءة رسائل استشارة ────────────────────────────────────────
if ($action === 'messages') {
    $consult_id = (int)($b['consultation_id'] ?? 0);
    $c = db()->prepare('SELECT * FROM provider_consultations WHERE id = ? LIMIT 1');
    $c->execute([$consult_id]);
    $consult = $c->fetch();
    if (!$consult || !in_array($u['id'], [(int)$consult['user_id'], (int)$consult['provider_id']]))
        Kernel::fail('forbidden', '', 403);

    $msgs = db()->prepare(
        'SELECT cm.*, u.name AS sender_name FROM consultation_messages cm
         JOIN users u ON u.id = cm.sender_id WHERE cm.consultation_id = ? ORDER BY cm.created_at'
    );
    $msgs->execute([$consult_id]);
    json_response(['success' => true, 'messages' => $msgs->fetchAll(), 'consultation' => $consult,
        'trace_id' => Logger::traceId()]);
}

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