500) { json_error('السؤال طويل جداً (الحد 500 حرف)', 422); } $tenantId = $decoded['tenant_id']; $userId = $decoded['user_id']; try { // 1. Gather user context (last month stats) $contextStmt = $db->prepare(" SELECT COUNT(*) as total_invoices, COALESCE(SUM(grand_total), 0) as total_revenue, COALESCE(SUM(tax_amount), 0) as total_tax FROM invoices WHERE tenant_id = ? AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) "); $contextStmt->execute([$tenantId]); $context = $contextStmt->fetch(); $companyStmt = $db->prepare("SELECT COUNT(*) FROM companies WHERE tenant_id = ? AND deleted_at IS NULL"); $companyStmt->execute([$tenantId]); $companyCount = (int)$companyStmt->fetchColumn(); // 2. Build AI prompt $systemPrompt = <<prepare(" INSERT INTO chatbot_history (id, user_id, tenant_id, question, answer, created_at) VALUES (UUID(), ?, ?, ?, ?, NOW()) ")->execute([$userId, $tenantId, $question, $aiResponse]); json_success([ 'answer' => $aiResponse, 'question' => $question, 'timestamp' => date('c'), ], 'إجابة مُصادَق'); } catch (\Exception $e) { safe_error($e, 'chatbot/ask', 'حدث خطأ في المساعد الذكي.'); }