<?php
/**
 * AJAX endpoint for the legacy (non-streaming) RBC AI chat router.
 *
 * The dashboard uses ai_agent_stream.php; this endpoint remains for the
 * chat_router path. It is now gated identically — previously it checked only
 * that a session existed, and returned raw exception text (file paths, SQL,
 * driver detail) straight to the client.
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

header('Content-Type: application/json');

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../ai/agent_guard.php';
require_once __DIR__ . '/../ai/chat_router.php';

$input = json_decode((string) file_get_contents('php://input'), true) ?? [];

// Login + role + module licence + CSRF.
$user_id = rbcRequireAgentAccess('json', true, (string) ($input['csrf_token'] ?? ''));

$message = trim((string) ($input['message'] ?? ''));
if ($message === '') {
    echo json_encode(['success' => false, 'message' => 'Empty message']);
    exit;
}

$session_id = $_SESSION['ai_chat_session'] ?? session_id();
$_SESSION['ai_chat_session'] = $session_id;

try {
    $response = RBCChatRouter::route($message, $session_id, $user_id);
    echo json_encode(['success' => true, 'response' => $response]);
} catch (Throwable $e) {
    // Log the detail; never return it. The previous version echoed
    // $e->getMessage() back to the caller.
    error_log('RBC Chat error: ' . $e->getMessage() . ' @ ' . $e->getFile() . ':' . $e->getLine());
    http_response_code(500);
    echo json_encode([
        'success'  => false,
        'message'  => 'An internal error occurred.',
        'response' => ['type' => 'error', 'message' => 'Something went wrong. Please try again.'],
    ]);
}
