<?php

namespace App\Models;

use CodeIgniter\Model;

class PermissionModel extends Model
{
    protected $table = 'permissions';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'group_name'];

    public function grouped(): array
    {
        $data = $this->orderBy('group_name', 'ASC')->findAll();

        $grouped = [];
        foreach ($data as $row) {
            $grouped[$row['group_name']][] = $row;
        }

        return $grouped;
    }

    public function getByRole($roleId)
    {
        return $this->db->table('permissions p')
            ->select('p.name')
            ->join('role_permissions rp', 'rp.permission_id = p.id')
            ->where('rp.role_id', $roleId)
            ->get()
            ->getResultArray();
    }
}
