<?php
require_once __DIR__ . '/../includes/init.php';
require_role('admin');

$pdo = db();
$stmt = $pdo->query('SELECT * FROM users ORDER BY created_at DESC');
$users = $stmt->fetchAll();

$page_title = 'Użytkownicy';
?>
<?php require_once __DIR__ . '/../includes/html_head.php'; ?>
<body>

<?php include __DIR__ . '/menu.php'; ?>

<main class="container my-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h2"><?php echo $page_title; ?></h1>
        <a href="edit_user.php" class="btn btn-primary">
            <i class="bi bi-plus-lg"></i> Dodaj użytkownika
        </a>
    </div>

    <div class="card">
        <div class="card-body">
            <table class="table table-striped table-hover">
                <thead class="table-light">
                    <tr>
                        <th>ID</th>
                        <th>Email</th>
                        <th>Rola</th>
                        <th>Aktywny</th>
                        <th>Data utworzenia</th>
                        <th>Akcje</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($users)):
                        ?>
                        <tr>
                            <td colspan="6" class="text-center">Nie znaleziono użytkowników.</td>
                        </tr>
                    <?php else:
                        ?>
                        <?php foreach ($users as $user): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($user['id']); ?></td>
                            <td><?php echo htmlspecialchars($user['email']); ?></td>
                            <td><span class="badge bg-secondary"><?php echo htmlspecialchars($user['role']); ?></span></td>
                            <td>
                                <?php if ($user['is_active']): ?>
                                    <span class="badge bg-success">Tak</span>
                                <?php else: ?>
                                    <span class="badge bg-danger">Nie</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo htmlspecialchars(date('d.m.Y H:i', strtotime($user['created_at']))); ?></td>
                            <td>
                                <a href="edit_user.php?id=<?php echo $user['id']; ?>" class="btn btn-sm btn-secondary">
                                    <i class="bi bi-pencil-fill"></i> Edytuj
                                </a>                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
</body>
</html>
