<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/layout.php'; // includes auth, header, sidebar, topbar, and $pdo

// ----------------------
// CURRENT USER ROLE
// ----------------------
$currentUserRole = strtolower($_SESSION['admin_role'] ?? 'writer');

try {

    $stmt = $pdo->query("
        SELECT 
            id, 
            username, 
            email, 
            role, 
            last_logged_in, 
            created_at 
        FROM admin_users 
        ORDER BY created_at ASC
    ");

    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {

    die("Error fetching users: " . htmlspecialchars($e->getMessage()));

}
?>

<h1>Users</h1>

<div class="d-flex justify-content-end mb-3">

    <p>
        <a 
            href="create-user.php" 
            class="btn btn-success" 
            style="width: 150px"
        >
            Create New User
        </a>
    </p>

</div>

<table class="table table-striped table-bordered">

    <thead>

        <tr>
            <th>ID</th>
            <th>Username</th>
            <th>Email</th>
            <th>Role</th>
            <th>Last Logged In</th>
            <th>Edit</th>
        </tr>

    </thead>

    <tbody>

    <?php if (count($users) === 0): ?>

        <tr>
            <td colspan="6">No users found.</td>
        </tr>

    <?php else: ?>

        <?php foreach ($users as $user): ?>

            <?php
            $targetUserRole = strtolower($user['role']);
            $canEdit = (
                $currentUserRole === 'admin'
                || $targetUserRole !== 'admin'
            );
            ?>

            <tr>

                <td>
                    <?= (int)$user['id'] ?>
                </td>

                <td>
                    <?= htmlspecialchars($user['username']) ?>
                </td>

                <td>
                    <?= htmlspecialchars($user['email']) ?>
                </td>

                <td>
                    <?= htmlspecialchars($user['role']) ?>
                </td>

                <td>
                    <?= $user['last_logged_in'] 
                        ? htmlspecialchars($user['last_logged_in']) 
                        : 'Never' ?>
                </td>

                <td>

                    <?php if ($canEdit): ?>

                        <a 
                            href="edit-user?id=<?= (int)$user['id'] ?>"
                            class="btn btn-sm btn-dark"
                        >
                            Edit
                        </a>

                    <?php else: ?>

                        <span class="text-muted small">
                            Restricted
                        </span>

                    <?php endif; ?>

                </td>

            </tr>

        <?php endforeach; ?>

    <?php endif; ?>

    </tbody>

</table>