'Message is required']); exit; } $userMsg = $data['message']; $mode = $data['mode'] ?? 'regular'; $chatId = $data['chat_id'] ?? null; $creativity = $data['creativity'] ?? 0.7; $limitsOff = (int)($data['limits_off'] ?? 0); $model = $data['model'] ?? 'gpt-4o'; try { // 1. Verify/Create chat if ($chatId) { $stmt = db()->prepare("SELECT id FROM chats WHERE id = ?"); $stmt->execute([$chatId]); if (!$stmt->fetch()) { $chatId = null; // Reset if ID not found } } if (!$chatId) { $stmt = db()->prepare("INSERT INTO chats (mode, title) VALUES (?, ?)"); $title = mb_substr($userMsg, 0, 50) . (mb_strlen($userMsg) > 50 ? '...' : ''); $stmt->execute([$mode, $title]); $chatId = db()->lastInsertId(); } // 2. Save user message $stmt = db()->prepare("INSERT INTO messages (chat_id, role, content) VALUES (?, 'user', ?)"); $stmt->execute([$chatId, $userMsg]); // 3. Prepare AI Prompt based on mode $systemPrompt = "You are a helpful, intelligent AI assistant. Respond in clear, concise language."; if ($mode === 'coding') { $systemPrompt = "You are an elite senior software engineer. Provide clean, secure, efficient code snippets. Always use triple backticks with the language specified. Briefly explain the logic."; } elseif ($mode === 'game' || $mode === 'app') { $systemPrompt = "You are a world-class single-file application developer. Generate a complete, functional, and visually stunning HTML/CSS/JS application in a SINGLE message. Wrap the entire code in a triple-backtick block starting with ```html. Include CSS in