<?php namespace App\Models;

use App\Entities\Permissao\Permissao;
use CodeIgniter\Model;
use Exception;

class PermissaoModel extends ModelEntity
{
    protected $table = 'permissao';
    protected $primaryKey = 'id';
    protected $returnType = 'array';
    protected $allowedFields = [
        'descricao',
        'id_endpoint',
        'id_perfil',
        'ativo',
    ];
    protected $useSoftDeletes = false;
    protected $skipValidation = true;
    protected $useTimestamps = false;

    public function registerPermissao (Permissao &$permissao) : void {
        $permissao_data = $permissao->toArray();
        $id_new_permissao = $this->insert($permissao_data);
        $permissao->setId($id_new_permissao);
    }

    public function updatePermissao (int $id_pefil, $permissao) : bool {
        if (count($permissao) > 0) {
            $binds = [
                'id_perfil' => $id_pefil
            ];
            $permissoes =  implode(",", $permissao);

            $sql = "
                UPDATE permissao 
                SET ativo = 1 
                WHERE id_perfil = :id_perfil: 
                    and id_endpoint in ($permissoes)
            ";

            $query = $this->db->query($sql, $binds);
            $errors = $this->errors();
            return !$errors;
        } else {
            return true;
        }
    }

    public function limpaPermissao (int $id_pefil) : bool {
            $binds = [
                'id_perfil' => $id_pefil
            ];

            $sql = "
                UPDATE permissao 
                SET ativo = 0 
                WHERE id_perfil = :id_perfil: 
            ";

            $query = $this->db->query($sql, $binds);
            $errors = $this->errors();
            return !$errors;
    }

}
