<?php
require_once __DIR__ . '/../includes/auth.php';
requireLogin();
requirePermission('roles.manage');

require_once __DIR__ . '/../config/database.php';

/* =============================
   REQUIRE PERMISSION
============================= */

requirePermission('manage_roles');

/* =============================
   FETCH ROLES SAFELY
============================= */

try {

    $stmt = $pdo->query("
        SELECT 
            r.id,
            r.name,
            COUNT(u.id) AS user_count
        FROM roles r
        LEFT JOIN users u ON u.role_id = r.id
        GROUP BY r.id, r.name
        ORDER BY r.name ASC
    ");

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

} catch (PDOException $e) {
    die("Database error loading roles.");
}

/* =============================
   LOAD LAYOUT
============================= */

require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>

<div class="main-content">

    <div class="page-header">
        <h2>Roles</h2>
        <p class="page-subtitle">
            Enterprise role structure with permission-based access control.
        </p>
    </div>

    <div style="margin-bottom:20px;">
        <a href="add_role.php" class="btn-primary">+ Add Role</a>
    </div>

    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Role</th>
                    <th>Users</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>

            <?php if (!empty($roles)): ?>

                <?php foreach ($roles as $r): ?>
                    <tr>
                        <td><?= htmlspecialchars($r['name'] ?? '') ?></td>

                        <td>
                            <strong><?= (int)$r['user_count'] ?></strong>
                        </td>

                        <td>
                            <a class="action-link"
                               href="edit_role.php?id=<?= (int)$r['id'] ?>">
                                Edit
                            </a>

                            &nbsp;|&nbsp;

                            <a class="action-link"
                               href="role_permissions.php?id=<?= (int)$r['id'] ?>">
                                Permissions
                            </a>

                         <?php if ((int)$r['user_count'] === 0 && (int)$r['id'] !== 1): ?>
    &nbsp;|&nbsp;
    <a class="action-link"
       href="delete_role.php?id=<?= (int)$r['id'] ?>"
       onclick="return confirm('Delete this role?');">
        Delete
    </a>
<?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>

            <?php else: ?>

                <tr>
                    <td colspan="3">No roles found.</td>
                </tr>

            <?php endif; ?>

            </tbody>
        </table>
    </div>

</div>

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