<?php

namespace App\Models;

use CodeIgniter\Model;

class RoleModel extends Model
{
    protected $table         = 'roles';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';

    protected $allowedFields = ['name', 'slug', 'description', 'is_system'];

    protected $validationRules = [
        'name' => 'required|min_length[2]|max_length[100]|is_unique[roles.name,id,{id}]',
    ];

    public function optionsForSelect(): array
    {
        return array_column($this->orderBy('name', 'ASC')->findAll(), 'name', 'id');
    }

    public function isInUse(int $roleId): bool
    {
        $db = \Config\Database::connect();

        return $db->table('users')->where('role_id', $roleId)->where('deleted_at', null)->countAllResults() > 0;
    }

    public function generateSlug(string $name): string
    {
        return strtolower(preg_replace('/[^a-z0-9]+/i', '-', trim($name)));
    }
}
