Files
bot_palmas/services/ConversationContext.php
2026-06-12 12:18:21 -05:00

82 lines
2.8 KiB
PHP

<?php
declare(strict_types=1);
class ConversationContext
{
public static function getOrCreate(int $companyId, string $phoneNumber, string $botType = 'normal'): array
{
$stmt = db()->prepare("SELECT * FROM bot_context WHERE company_id = ? AND phone_number = ? LIMIT 1");
$stmt->execute([$companyId, $phoneNumber]);
$ctx = $stmt->fetch();
if ($ctx) {
return $ctx;
}
$stmt = db()->prepare("INSERT INTO bot_context (company_id, phone_number, bot_type, ai_history, metadata) VALUES (?, ?, ?, '[]', '{}')");
$stmt->execute([$companyId, $phoneNumber, $botType]);
return [
'id' => (int)db()->lastInsertId(),
'company_id' => $companyId,
'phone_number' => $phoneNumber,
'bot_type' => $botType,
'current_node' => null,
'ai_history' => '[]',
'metadata' => '{}',
];
}
public static function updateNode(int $id, ?string $node): void
{
$stmt = db()->prepare("UPDATE bot_context SET current_node = ?, updated_at = NOW() WHERE id = ?");
$stmt->execute([$node, $id]);
}
public static function addAiMessage(int $id, array $message): void
{
$stmt = db()->prepare("SELECT ai_history FROM bot_context WHERE id = ? LIMIT 1");
$stmt->execute([$id]);
$row = $stmt->fetch();
$history = $row ? json_decode($row['ai_history'], true) : [];
$history[] = $message;
if (count($history) > 50) {
array_shift($history);
}
$stmt = db()->prepare("UPDATE bot_context SET ai_history = ?, updated_at = NOW() WHERE id = ?");
$stmt->execute([json_encode($history), $id]);
}
public static function getAiHistory(int $id): array
{
$stmt = db()->prepare("SELECT ai_history FROM bot_context WHERE id = ? LIMIT 1");
$stmt->execute([$id]);
$row = $stmt->fetch();
return $row ? json_decode($row['ai_history'], true) ?? [] : [];
}
public static function updateMetadata(int $id, array $metadata): void
{
$stmt = db()->prepare("UPDATE bot_context SET metadata = ?, updated_at = NOW() WHERE id = ?");
$stmt->execute([json_encode($metadata), $id]);
}
public static function getMetadata(int $id): array
{
$stmt = db()->prepare("SELECT metadata FROM bot_context WHERE id = ? LIMIT 1");
$stmt->execute([$id]);
$row = $stmt->fetch();
return $row ? json_decode($row['metadata'], true) ?? [] : [];
}
public static function reset(int $id): void
{
$stmt = db()->prepare("UPDATE bot_context SET current_node = NULL, ai_history = '[]', metadata = '{}', updated_at = NOW() WHERE id = ?");
$stmt->execute([$id]);
}
}