<?php
class Permission extends Model {
    protected static string $table = 'permissions';

    public static function getAll(): array {
        $stmt = db()->prepare("SELECT * FROM permissions ORDER BY category, display_name");
        $stmt->execute();
        return $stmt->fetchAll();
    }

    public static function getByCategory(string $category): array {
        $stmt = db()->prepare("SELECT * FROM permissions WHERE category=? ORDER BY display_name");
        $stmt->execute([$category]);
        return $stmt->fetchAll();
    }

    public static function getGroupedByCategory(): array {
        $stmt = db()->prepare("SELECT * FROM permissions ORDER BY category, display_name");
        $stmt->execute();
        $permissions = $stmt->fetchAll();

        $grouped = [];
        foreach ($permissions as $perm) {
            $grouped[$perm['category']][] = $perm;
        }

        return $grouped;
    }

    public static function findById(int $id): ?array {
        $stmt = db()->prepare("SELECT * FROM permissions WHERE id=?");
        $stmt->execute([$id]);
        return $stmt->fetch() ?: null;
    }

    public static function findByName(string $name): ?array {
        $stmt = db()->prepare("SELECT * FROM permissions WHERE name=?");
        $stmt->execute([$name]);
        return $stmt->fetch() ?: null;
    }

    public static function getCategories(): array {
        $stmt = db()->prepare("SELECT DISTINCT category FROM permissions ORDER BY category");
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_COLUMN);
    }
}
