<?php

use Mtc\Plugins\Agent\Models\AIChatHistory;

$path = '../../../';
require_once $path.'core/includes/header.inc.php';
require_once $path . 'core/admin/templates/adminheader.html.php';


$id = isset($_GET['id']) ? (int)$_GET['id'] : null;

if ($id === null) {
    echo "<p>No ID provided.</p>";
    require_once $path . 'core/admin/templates/adminfooter.html.php';
    exit();
}

$model = new AIChatHistory();
$chatHistory = $model->find($id);
?>

    <ul class="breadcrumbs el">
        <li><a href="/admin/">Home</a> /</li>
        <li><a href="index.php">AI Chatbot</a> /</li>
        <li class="end">View Chat History</li>
    </ul>
<h1>Chat History</h1>
<?php

/**
 * Recursively renders arrays/objects in a readable, HTML-safe format.
 */
function render_value($value) {
    if (is_array($value)) {
        echo "<ul>";
        foreach ($value as $key => $item) {
            echo "<li><strong>" . htmlspecialchars($key) . "</strong>: ";
            render_value($item);
            echo "</li>";
        }
        echo "</ul>";
    } else {
        echo htmlspecialchars((string)$value);
    }
}

/**
 * Renders a single chat entry.
 */
function render_entry($entry) {
    $role = $entry["role"] ?? "system";
    $content = $entry["content"] ?? "";
    $tools = $entry["tools"] ?? null;

    // Choose styling based on role
    $class = match ($role) {
        "user" => "user-msg",
        "assistant" => "assistant-msg",
        "system" => "system-msg",
        default => "other-msg"
    };

    echo "<div class='msg $class'>";
    echo "<div class='msg-role'>" . strtoupper($role) . "</div>";

    // Main content
    if ($content !== null && $content !== "") {
        echo "<div class='msg-content'>" . htmlspecialchars($content) . "</div>";
    }

    // Tool call results (if present)
    if ($tools) {
        echo "<div class='tool-section'><strong>Tool Calls / Results:</strong>";
        render_value($tools);
        echo "</div>";
    }

    echo "</div>";
}
if ($chatHistory) {
    $messages = json_decode($chatHistory->messages, true);
    if (!empty($messages) && is_array($messages)) {
        foreach ($messages as $message) {
            render_entry($message);
        }
    } else {
        echo "<p>No messages found in this chat history.</p>";
    }
} else {
    echo "<p>Chat history not found.</p>";
}

require_once $path . 'core/admin/templates/adminfooter.html.php';
