<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Query\SelectQuery;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use App\Text\Messages;

/**
 * Usuarios Model
 *
 * @property \App\Model\Table\RolesTable&\Cake\ORM\Association\BelongsTo $Rols
 * @property \App\Model\Table\EmpresasTable&\Cake\ORM\Association\BelongsTo $Empresas
 *
 * @method \App\Model\Entity\Usuario newEmptyEntity()
 * @method \App\Model\Entity\Usuario newEntity(array $data, array $options = [])
 * @method array<\App\Model\Entity\Usuario> newEntities(array $data, array $options = [])
 * @method \App\Model\Entity\Usuario get(mixed $primaryKey, array|string $finder = 'all', \Psr\SimpleCache\CacheInterface|string|null $cache = null, \Closure|string|null $cacheKey = null, mixed ...$args)
 * @method \App\Model\Entity\Usuario findOrCreate($search, ?callable $callback = null, array $options = [])
 * @method \App\Model\Entity\Usuario patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
 * @method array<\App\Model\Entity\Usuario> patchEntities(iterable $entities, array $data, array $options = [])
 * @method \App\Model\Entity\Usuario|false save(\Cake\Datasource\EntityInterface $entity, array $options = [])
 * @method \App\Model\Entity\Usuario saveOrFail(\Cake\Datasource\EntityInterface $entity, array $options = [])
 * @method iterable<\App\Model\Entity\Usuario>|\Cake\Datasource\ResultSetInterface<\App\Model\Entity\Usuario>|false saveMany(iterable $entities, array $options = [])
 * @method iterable<\App\Model\Entity\Usuario>|\Cake\Datasource\ResultSetInterface<\App\Model\Entity\Usuario> saveManyOrFail(iterable $entities, array $options = [])
 * @method iterable<\App\Model\Entity\Usuario>|\Cake\Datasource\ResultSetInterface<\App\Model\Entity\Usuario>|false deleteMany(iterable $entities, array $options = [])
 * @method iterable<\App\Model\Entity\Usuario>|\Cake\Datasource\ResultSetInterface<\App\Model\Entity\Usuario> deleteManyOrFail(iterable $entities, array $options = [])
 */
class UsuariosTable extends Table
{
    /**
     * Initialize method
     *
     * @param array<string, mixed> $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('usuarios');
        $this->setDisplayField('nombre');
        $this->setPrimaryKey('id');
        $this->addBehavior('Register');

        $this->belongsTo('Rols', [
            'foreignKey' => 'rol_id',
            'className' => 'Roles',
            'joinType' => 'INNER',
        ]);
        $this->belongsTo('Empresas', [
            'foreignKey' => 'empresa_id',
            'joinType' => 'INNER',
        ]);
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator): Validator
    {
        $messageEmpty = Messages::get('REQUIRED');
        $messageEmail = Messages::get('INVALID_EMAIL');
        $messageInteger = Messages::get('MUST_BE_INTEGER');
        $messageRangePassword = Messages::get('PASSWORD_LENGTH');
        $messageUserUnique = Messages::get('USERNAME_EXISTS');
        $messageEmailUnique = Messages::get('EMAIL_EXISTS');
        $messageRutNotValid = Messages::get('INVALID_RUT');
        $messageRutUnique = Messages::get('RUT_EXISTS');
        $validator
            ->scalar('nombre')
            ->maxLength('nombre', 255)
            ->requirePresence('nombre', 'create',$messageEmpty)
            ->notEmptyString('nombre', $messageEmpty);

        $validator
            ->scalar('apellido')
            ->maxLength('apellido', 255)
            ->requirePresence('apellido', 'create',$messageEmpty)
            ->notEmptyString('apellido',$messageEmpty);

        $validator
            ->requirePresence('email','create',$messageEmpty)
            ->notEmptyString('email',$messageEmpty)
            ->add('email','validFormat',[
                'rule' => 'email',
                'message' => $messageEmail,
            ])
            ->add('email', 'unique', ['rule' => 'validateUnique', 'provider' => 'table','message' => $messageEmailUnique]);

        $validator
            ->scalar('clave')
            ->maxLength('clave', 20, $messageRangePassword)
            ->minLength('clave', 4 ,$messageRangePassword)
            ->requirePresence('clave', 'create',$messageEmpty)
            ->notEmptyString('clave', 'create', $messageEmpty);


        $validator
             ->scalar('rol_id')
            ->requirePresence('rol_id', 'create',$messageEmpty)
            ->notEmptyString('rol_id',$messageEmpty);


        $validator
             ->scalar('empresa_id')
            ->requirePresence('empresa_id', 'create',$messageEmpty)
            ->notEmptyString('empresa_id',$messageEmpty);



        return $validator;
    }

    /**
     * Returns a rules checker object that will be used for validating
     * application integrity.
     *
     * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
     * @return \Cake\ORM\RulesChecker
     */
    public function buildRules(RulesChecker $rules): RulesChecker
    {
        $rules->add($rules->existsIn(['rol_id'], 'Rols'), ['errorField' => 'rol_id']);
        $rules->add($rules->existsIn(['empresa_id'], 'Empresas'), ['errorField' => 'empresa_id']);

        return $rules;
    }

    public function findForAuthentication(\Cake\ORM\Query $query, array $options): \Cake\ORM\Query
    {
        return $query
                ->where(
                    [
                        'activo' => 1
                    ]
                )
                ->contain(
                    [
                        'Rols',
                        'Empresas'
                    ]
                );
    }
}
