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

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

$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$userFilter = isset($_GET['user_filter']) ? trim($_GET['user_filter']) : '';

$sessionQuery = 'SELECT s.*, u.username, COUNT(m.id) as message_count FROM sessions s 
                 LEFT JOIN users u ON s.username = u.username 
                 LEFT JOIN messages m ON s.id = m.session_id';
$sessionParams = [];

if ($search) {
    $sessionQuery .= " WHERE (s.id LIKE :search OR u.username LIKE :search)";
    $sessionParams[':search'] = '%' . $search . '%';
}

if ($userFilter) {
    if (strpos($sessionQuery, 'WHERE') !== false) {
        $sessionQuery .= " AND s.username = :user_filter";
    } else {
        $sessionQuery .= " WHERE s.username = :user_filter";
    }
    $sessionParams[':user_filter'] = $userFilter;
}

$sessionQuery .= ' GROUP BY s.id ORDER BY s.last_use_time DESC';

$stmt = $db->prepare($sessionQuery);
foreach ($sessionParams as $param => $value) {
    $stmt->bindValue($param, $value);
}
$sessions = $stmt->execute();

$users = $db->query('SELECT DISTINCT username FROM users');
?>
<!DOCTYPE html>
<html lang="en" class="h-full">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Sessions</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <style>
        .scrollbar-hide::-webkit-scrollbar {
            display: none;
        }
        .scrollbar-hide {
            -ms-overflow-style: none;
            scrollbar-width: none;
        }
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }
        .main-container {
            display: flex;
            flex-direction: column;
            height: 100vh;
        }
        .content-area {
            flex: 1;
            overflow: hidden;
            display: flex;
        }
        #sessionsContainer, #messagesContainer {
            height: 100%;
            overflow-y: auto;
        }
        .session-card {
            transition: all 0.3s ease;
        }
        .session-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .message-bubble {
            max-width: 80%;
            padding: 10px 15px;
            border-radius: 18px;
            margin-bottom: 10px;
        }
        .message-bubble.user {
            background-color: #DCF8C6;
            align-self: flex-end;
        }
        .message-bubble.bot {
            background-color: #E8E8E8;
            align-self: flex-start;
        }
    </style>
</head>
<body class="bg-gray-100">
    <div class="main-container">
        <div class="bg-white shadow-md p-4">
            <div class="flex items-center space-x-4">
                <input type="text" id="searchInput" placeholder="Search sessions or messages..." class="flex-grow px-3 py-2 border rounded-md">
                <select id="userFilter" class="px-3 py-2 border rounded-md">
                    <option value="">All Users</option>
                    <?php while ($user = $users->fetchArray(SQLITE3_ASSOC)): ?>
                        <option value="<?= htmlspecialchars($user['username']) ?>"><?= htmlspecialchars($user['username']) ?></option>
                    <?php endwhile; ?>
                </select>
                <button id="reloadSessions" class="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600 transition duration-300">
                    <i class="fas fa-sync-alt"></i> Reload
                </button>
            </div>
        </div>
        <div class="content-area">
            <!-- Sessions Container -->
            <div class="w-1/3 border-r flex flex-col bg-gray-50">
                <div class="p-4 bg-gray-200 font-bold text-lg">Sessions</div>
                <div id="sessionsContainer" class="flex-1  p-4 space-y-4">
                    <?php
                    while ($session = $sessions->fetchArray(SQLITE3_ASSOC)):
                    ?>
                        <div class="bg-white rounded-lg shadow-md p-4 hover:shadow-lg transition duration-300 cursor-pointer session-card" data-session-id="<?= htmlspecialchars($session['id']) ?>">
                            <h3 class="text-lg font-semibold mb-2">Session ID: <?= htmlspecialchars($session['id']) ?></h3>
                            <p class="text-sm text-gray-600">Username: <?= htmlspecialchars($session['username']) ?></p>
                            <p class="text-sm text-gray-600">Messages: <?= htmlspecialchars($session['message_count']) ?></p>
                            <p class="text-sm text-gray-600">Start Time: <?= htmlspecialchars($session['start_time']) ?></p>
                            <p class="text-sm text-gray-600">Last Use Time: <?= htmlspecialchars($session['last_use_time']) ?></p>
                        </div>
                    <?php endwhile; ?>
                </div>
            </div>
            <!-- Messages Container -->
            <div class="flex-1 flex flex-col bg-gray-100">
                <div class="p-4 bg-gray-200 font-bold text-lg flex justify-between items-center">
                    <span>Messages</span>
                    <button id="closeConversation" class="text-gray-600 hover:text-gray-800 hidden">
                        <i class="fas fa-times"></i> Close
                    </button>
                </div>
                <div id="messagesContainer" class="flex-1  p-4 space-y-4">
                    <div id="noConversationSelected" class="flex flex-col items-center justify-center h-full">
                        <i class="fas fa-comments text-gray-400 text-6xl mb-4"></i>
                        <p class="text-xl text-gray-600">Select a conversation to view messages</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
    $(document).ready(function() {
        function loadMessages(sessionId) {
            $.get('admin/get_messages.php', { session_id: sessionId }, function(data) {
                $('#messagesContainer').html(data);
                $('#noConversationSelected').hide();
                $('#closeConversation').show();
            });
        }

        function attachSessionClickHandlers() {
            $('.session-card').click(function() {
                const sessionId = $(this).data('session-id');
                $('.session-card').removeClass('bg-blue-100');
                $(this).addClass('bg-blue-100');
                loadMessages(sessionId);
            });
        }

        function loadSessions(search = '', userFilter = '') {
            $.get('admin/sessions.php', { search: search, user_filter: userFilter }, function(data) {
                $('#sessionsContainer').html($(data).find('#sessionsContainer').html());
                attachSessionClickHandlers();
            });
        }

        attachSessionClickHandlers();

        $('#searchInput, #userFilter').on('input change', function() {
            const search = $('#searchInput').val();
            const userFilter = $('#userFilter').val();
            loadSessions(search, userFilter);
        });

        $('#reloadSessions').click(function() {
            $('#searchInput').val('');
            $('#userFilter').val('');
            loadSessions();
        });

        $('#closeConversation').click(function() {
            $('#messagesContainer').html(`
                <div id="noConversationSelected" class="flex flex-col items-center justify-center h-full">
                    <i class="fas fa-comments text-gray-400 text-6xl mb-4"></i>
                    <p class="text-xl text-gray-600">Select a conversation to view messages</p>
                </div>
            `);
            $('.session-card').removeClass('bg-blue-100');
            $(this).hide();
        });
    });
    </script>
</body>
</html>