<?php
// POST /api/roles/list.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
requireAuth();
$db = getDB();

try {
    $roles = $db->query("
        SELECT r.*, COUNT(u.id) AS user_count
        FROM roles r
        LEFT JOIN users u ON u.role_id = r.id AND u.is_active = 1
        GROUP BY r.id
        ORDER BY r.sort_order ASC, r.id ASC
    ")->fetchAll();
} catch (PDOException $e) {
    // sort_order column may not exist yet — fall back
    $roles = $db->query("
        SELECT r.id, r.name, r.description, r.is_system, 0 AS sort_order, r.created_at, COUNT(u.id) AS user_count
        FROM roles r
        LEFT JOIN users u ON u.role_id = r.id AND u.is_active = 1
        GROUP BY r.id
        ORDER BY r.id ASC
    ")->fetchAll();
}

apiSuccess(['roles' => $roles]);