<?php
session_start();
include '../../includes/header.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/User.php';


$database = new Database();
$conn = $database->getConnection();


$auth = new Auth($conn);


if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}
$auth->enforceSuperAdminPrivileges($_SESSION['user_id']);


$user = new User($conn);
$users = $user->getAllUsers();
?>
    <div class="container mt-5">
        <h1 class="mb-4">Manage Users</h1>
        <div class="btn-container">
            <a href="../dashboard/admin.php" class="btn btn-secondary">Dashboard</a>
            <a href="add_user_form.php" class="btn btn-primary">Add New User</a>
        </div>

        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Username</th>
                    <th>Email</th>
                    <th>Branch</th>
                    <th>Terminal</th>
                    <th>Role</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($users)): ?>
                    <?php foreach ($users as $user): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($user['username'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($user['email'] ?? ''); ?></td>
                            <td><?php echo htmlspecialchars($user['branch_name'] ?? 'System-wide'); ?></td>
                            <td><?php echo htmlspecialchars($user['terminal_label'] ?? 'Not required'); ?></td>
                            <td><?php echo htmlspecialchars(User::getRoleLabel($user['role'] ?? '')); ?></td>
                            <td>
                                <?php if (isset($user['user_id'])): ?>
                                    <a href="edit_user.php?id=<?php echo $user['user_id']; ?>" class="btn btn-warning btn-sm">Edit</a>
                                    <a href="delete_user.php?id=<?php echo $user['user_id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete this user?');">Delete</a>
                                <?php else: ?>
                                    <span class="text-danger">ID not found</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="6" class="text-center">No users found.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
