company_id); $response->json([ 'status' => 'success', 'data' => $rules ]); } /** * Store or update a chatbot rule */ public function store(Request $request, Response $response) { $errors = $this->validate($request, [ 'trigger_type' => 'required', 'is_active' => 'required' ]); if (!empty($errors)) { $response->status(400)->json(['status' => 'error', 'errors' => $errors]); return; } $body = $request->getBody(); // Find existing rule or create one $rules = ChatbotRule::findAllByCompany($request->company_id); $ruleId = null; if (!empty($rules)) { $ruleId = $rules[0]['id']; } $saveData = [ 'company_id' => $request->company_id, 'session_id' => !empty($body['session_id']) ? (int)$body['session_id'] : null, 'trigger_type' => $body['trigger_type'], 'keyword' => $body['keyword'] ?? null, 'ai_prompt' => $body['ai_prompt'] ?? null, 'is_active' => $body['is_active'] ? 1 : 0 ]; if ($ruleId) { $saveData['id'] = $ruleId; } // If gemini_api_key is provided, update it. If not, and we have an existing rule, retain it. // If it's a password placeholder like '••••••••' or similar, don't overwrite the existing one. if (isset($body['gemini_api_key']) && $body['gemini_api_key'] !== '••••••••' && $body['gemini_api_key'] !== '') { $saveData['gemini_api_key'] = $body['gemini_api_key']; } $id = ChatbotRule::saveSecure($saveData); $response->json([ 'status' => 'success', 'message' => 'Chatbot rule saved successfully', 'id' => $id ]); } }