<?php
session_start();
if (!isset($_SESSION['admin'])) {
    header('Location: index.php');
    exit;
}

$dbFile = '../chat_history.sqlite';
$db = new SQLite3($dbFile);

$sessionId = isset($_GET['session_id']) ? $_GET['session_id'] : '';

if (empty($sessionId)) {
    echo '<p class="text-center text-gray-500">Please select a session to view messages.</p>';
    exit;
}

$stmt = $db->prepare('SELECT * FROM messages WHERE session_id = :session_id ORDER BY timestamp ASC');
$stmt->bindValue(':session_id', $sessionId, SQLITE3_TEXT);
$messages = $stmt->execute();

while ($message = $messages->fetchArray(SQLITE3_ASSOC)):
?>
    <div class="mb-4 p-2 rounded-lg <?= $message['sender'] === 'user' ? 'bg-blue-100 ml-auto' : 'bg-gray-100' ?>" style="max-width: 70%;">
        <p class="text-sm"><?= htmlspecialchars($message['message']) ?></p>
        <p class="text-xs text-gray-500 mt-1"><?= htmlspecialchars($message['timestamp']) ?></p>
    </div>
<?php
endwhile;

if ($messages->numColumns() === 0) {
    echo '<p class="text-center text-gray-500">No messages found for this session.</p>';
}
?>