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

// Fetch the profile associated with the logged-in user
$dbFile = 'chat_history.sqlite';
$db = new SQLite3($dbFile);

$stmt = $db->prepare('SELECT p.name AS profile_name FROM users u JOIN profiles p ON u.profile_id = p.id WHERE u.username = :username');
$stmt->bindValue(':username', $_SESSION['user'], SQLITE3_TEXT);
$result = $stmt->execute();
$row = $result->fetchArray(SQLITE3_ASSOC);
$profileName = $row ? $row['profile_name'] : 'Default Profile';

?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تطبيق المحادثة Bedrock</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@400;700&display=swap');
        body {
            font-family: 'Tajawal', sans-serif;
        }
    </style>
</head>
<body class="bg-gray-100 h-screen flex items-center justify-center">
    <div class="w-full max-w-2xl bg-white rounded-lg shadow-md p-6">
        <div class="flex justify-between items-center mb-4">
            <div>
                <h1 class="text-2xl font-bold text-center">تطبيق المحادثة </h1>
                <p class="text-sm text-gray-600"><?= htmlspecialchars($profileName) ?></p>
            </div>
            <form action="logout.php" method="post">
                <button type="submit" class="bg-red-500 text-white px-4 py-2 rounded hover:bg-red-600 transition duration-300">تسجيل الخروج</button>
            </form>
        </div>
        <div id="chat-messages" class="h-96 overflow-y-auto mb-4 p-4 bg-gray-50 rounded" aria-live="polite">
            <!-- Messages will be displayed here -->
        </div>
        <form id="message-form" class="flex">
            <input type="text" id="message-input" class="flex-grow p-2 border rounded-l" placeholder="اكتب رسالة..." aria-label="اكتب رسالة">
            <button type="submit" class="bg-blue-500 text-white px-4 py-2 rounded-r hover:bg-blue-600 transition duration-300">
                <i class="fas fa-paper-plane" aria-hidden="true"></i>
                <span class="sr-only">إرسال</span>
            </button>
        </form>
    </div>
    <script src="chat.js"></script>
</body>
</html>