<?php

class Role extends Model
{
    protected string $table = 'roles';

    public function allWithUserCount(): array
    {
        return $this->db->query(
            "SELECT r.*, (SELECT COUNT(*) FROM users u WHERE u.role_id = r.id) as user_count
             FROM roles r ORDER BY r.id ASC"
        )->fetchAll();
    }

    public function permissionMatrix(int $roleId): array
    {
        $stmt = $this->db->prepare(
            "SELECT p.id as permission_id, p.module_key, p.module_label,
                    COALESCE(rp.can_view,0) as can_view,
                    COALESCE(rp.can_add,0) as can_add,
                    COALESCE(rp.can_edit,0) as can_edit,
                    COALESCE(rp.can_delete,0) as can_delete
             FROM permissions p
             LEFT JOIN role_permissions rp ON rp.permission_id = p.id AND rp.role_id = :role_id
             ORDER BY p.id ASC"
        );
        $stmt->execute(['role_id' => $roleId]);
        return $stmt->fetchAll();
    }
}
