Files
nabeh/backend/app/Models/ChatbotRule.php

103 lines
2.9 KiB
PHP

<?php
namespace App\Models;
use App\Core\Security;
use App\Core\Database;
/**
* ChatbotRule Model
* Handles the chatbot_rules table with encryption for Gemini API key.
*/
class ChatbotRule extends BaseModel
{
protected static string $table = 'chatbot_rules';
/**
* Find chatbot rules for a company
*/
public static function findAllByCompany(int $companyId)
{
self::ensureColumnsExist();
$rules = Database::select(
"SELECT * FROM " . static::$table . " WHERE company_id = ? ORDER BY id DESC",
[$companyId]
);
foreach ($rules as &$rule) {
if (!empty($rule['gemini_api_key'])) {
$rule['gemini_api_key'] = Security::decrypt($rule['gemini_api_key']);
}
}
return $rules;
}
/**
* Find active chatbot rule for a specific company and session
*/
public static function findActiveForRule(int $companyId, ?int $sessionId = null)
{
self::ensureColumnsExist();
if ($sessionId) {
$rule = Database::selectOne(
"SELECT * FROM " . static::$table . " WHERE company_id = ? AND (session_id = ? OR session_id IS NULL) AND is_active = 1 LIMIT 1",
[$companyId, $sessionId]
);
} else {
$rule = Database::selectOne(
"SELECT * FROM " . static::$table . " WHERE company_id = ? AND is_active = 1 LIMIT 1",
[$companyId]
);
}
if ($rule && !empty($rule['gemini_api_key'])) {
$rule['gemini_api_key'] = Security::decrypt($rule['gemini_api_key']);
}
return $rule;
}
/**
* Create or update chatbot rule securely
*/
public static function saveSecure(array $data)
{
self::ensureColumnsExist();
if (!empty($data['gemini_api_key'])) {
$data['gemini_api_key'] = Security::encrypt($data['gemini_api_key']);
}
if (isset($data['id'])) {
$id = $data['id'];
unset($data['id']);
self::update($id, $data);
return $id;
} else {
return self::create($data);
}
}
/**
* Helper to run ALTER TABLE to make sure gemini_api_key exists in chatbot_rules
*/
private static function ensureColumnsExist()
{
static $checked = false;
if ($checked) return;
try {
// Check if column exists
$columns = Database::select("SHOW COLUMNS FROM " . static::$table . " LIKE 'gemini_api_key'");
if (empty($columns)) {
Database::execute("ALTER TABLE " . static::$table . " ADD COLUMN gemini_api_key VARCHAR(512) DEFAULT NULL AFTER ai_prompt");
}
$checked = true;
} catch (\Exception $e) {
error_log("Failed to ensure chatbot_rules column: " . $e->getMessage());
}
}
}