<?php

namespace App\Models;

use CodeIgniter\Model;

class PermissionModel extends Model
{
    protected $table         = 'permissions';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = false;

    protected $allowedFields = ['group', 'slug', 'label', 'is_system', 'created_at'];

    protected $validationRules = [
        'group' => 'required|max_length[100]',
        'slug'  => 'required|max_length[150]|is_unique[permissions.slug,id,{id}]',
        'label' => 'required|max_length[150]',
    ];

    /**
     * All permissions grouped by module, e.g. ['users' => [...], 'roles' => [...]]
     */
    public function grouped(): array
    {
        $rows    = $this->orderBy('group', 'ASC')->orderBy('slug', 'ASC')->findAll();
        $grouped = [];
        foreach ($rows as $row) {
            $grouped[$row['group']][] = $row;
        }

        return $grouped;
    }
}
