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

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

$users = $db->query('SELECT users.*, profiles.name as profile_name FROM users LEFT JOIN profiles ON users.profile_id = profiles.id');
$profiles = $db->query('SELECT * FROM profiles');
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Users</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">
</head>

<body class="bg-gray-100 min-h-screen">
    <div class="container mx-auto px-4 py-8">
        <h1 class="text-3xl font-bold mb-6 text-center text-gray-800">Manage Users</h1>

        <button id="addUserBtn" class="mb-4 bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition duration-300">Add User</button>

        <div class="bg-white rounded-lg shadow-md overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="bg-gray-200 text-gray-600 uppercase text-sm leading-normal">
                        <th class="py-3 px-6 text-left">Username</th>
                        <th class="py-3 px-6 text-left">Profile</th>
                        <th class="py-3 px-6 text-center">Actions</th>
                    </tr>
                </thead>
                <tbody class="text-gray-600 text-sm font-light">
                    <?php while ($user = $users->fetchArray(SQLITE3_ASSOC)): ?>
                        <tr class="border-b border-gray-200 hover:bg-gray-100">
                            <td class="py-3 px-6 text-left whitespace-nowrap">
                                <?= htmlspecialchars($user['username']) ?>
                            </td>
                            <td class="py-3 px-6 text-left">
                                <?= htmlspecialchars($user['profile_name'] ?? 'None') ?>
                            </td>
                            <td class="py-3 px-6 text-center">
                                <button class="editUserBtn bg-yellow-500 text-white px-3 py-1 rounded hover:bg-yellow-600 transition duration-300" data-id="<?= $user['id'] ?>">Edit</button>
                                <button class="deleteUserBtn bg-red-500 text-white px-3 py-1 rounded hover:bg-red-600 transition duration-300" data-id="<?= $user['id'] ?>">Delete</button>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Add/Edit User Modal -->
    <div id="userModal" class="fixed z-10 inset-0 overflow-y-auto hidden" aria-labelledby="modal-title" role="dialog" aria-modal="true">
        <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true"></div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <form id="userForm">
                    <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                        <h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title"></h3>
                        <div class="mt-2">
                            <input type="hidden" id="userId" name="id">
                            <div class="mb-4">
                                <label for="username" class="block text-gray-700 text-sm font-bold mb-2">Username</label>
                                <input type="text" id="username" name="username" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" required>
                            </div>
                            <div class="mb-4">
                                <label for="password" class="block text-gray-700 text-sm font-bold mb-2">Password</label>
                                <input type="password" id="password" name="password" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline">
                            </div>
                            <div class="mb-4">
                                <label for="profile" class="block text-gray-700 text-sm font-bold mb-2">Profile</label>
                                <select id="profile" name="profile_id" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline">
                                    <option value="">None</option>
                                    <?php
                                    $profiles->reset();
                                    while ($profile = $profiles->fetchArray(SQLITE3_ASSOC)):
                                    ?>
                                        <option value="<?= $profile['id'] ?>"><?= htmlspecialchars($profile['name']) ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                        <button type="submit" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm">
                            Save
                        </button>
                        <button type="button" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm" onclick="closeUserModal()">
                            Cancel
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        function openUserModal(title, userId = '', username = '', profileId = '') {
            $('#modal-title').text(title);
            $('#userId').val(userId);
            $('#username').val(username);
            $('#password').val('');
            $('#profile').val(profileId);
            $('#userModal').removeClass('hidden');
        }

        function closeUserModal() {
            $('#userModal').addClass('hidden');
        }

        $(document).ready(function() {
            $('#addUserBtn').click(function() {
                openUserModal('Add User');
            });

            $('.editUserBtn').click(function() {
                var userId = $(this).data('id');
                var username = $(this).closest('tr').find('td:first').text().trim();
                var profileName = $(this).closest('tr').find('td:eq(1)').text().trim();
                var profileId = $('#profile option').filter(function() {
                    return $(this).text() === profileName;
                }).val();
                openUserModal('Edit User', userId, username, profileId);
            });

            $('.deleteUserBtn').click(function() {
                var userId = $(this).data('id');
                if (confirm('Are you sure you want to delete this user?')) {
                    $.post('admin/user_actions.php', {
                        action: 'delete',
                        id: userId
                    }, function(response) {
                        if (response.success) {
                            location.reload();
                        } else {
                            alert('Error: ' + response.message);
                        }
                    }, 'json');
                }
            });

            $('#userForm').submit(function(e) {
                e.preventDefault();
                var formData = $(this).serialize();
                formData += '&action=' + ($("#userId").val() ? 'update' : 'create');
                $.post('admin/user_actions.php', formData, function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert('Error: ' + response.message);
                    }
                }, 'json');
            });
        });
    </script>
</body>

</html>