<?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;

/**
 * Proyectos Model
 *
 * @property \App\Model\Table\EmpresasTable&\Cake\ORM\Association\BelongsTo $Empresas
 * @property \App\Model\Table\PalabrasClavesTable&\Cake\ORM\Association\BelongsToMany $PalabrasClaves
 *
 * @method \App\Model\Entity\Proyecto newEmptyEntity()
 * @method \App\Model\Entity\Proyecto newEntity(array $data, array $options = [])
 * @method array<\App\Model\Entity\Proyecto> newEntities(array $data, array $options = [])
 * @method \App\Model\Entity\Proyecto 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\Proyecto findOrCreate($search, ?callable $callback = null, array $options = [])
 * @method \App\Model\Entity\Proyecto patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
 * @method array<\App\Model\Entity\Proyecto> patchEntities(iterable $entities, array $data, array $options = [])
 * @method \App\Model\Entity\Proyecto|false save(\Cake\Datasource\EntityInterface $entity, array $options = [])
 * @method \App\Model\Entity\Proyecto saveOrFail(\Cake\Datasource\EntityInterface $entity, array $options = [])
 * @method iterable<\App\Model\Entity\Proyecto>|\Cake\Datasource\ResultSetInterface<\App\Model\Entity\Proyecto>|false saveMany(iterable $entities, array $options = [])
 * @method iterable<\App\Model\Entity\Proyecto>|\Cake\Datasource\ResultSetInterface<\App\Model\Entity\Proyecto> saveManyOrFail(iterable $entities, array $options = [])
 * @method iterable<\App\Model\Entity\Proyecto>|\Cake\Datasource\ResultSetInterface<\App\Model\Entity\Proyecto>|false deleteMany(iterable $entities, array $options = [])
 * @method iterable<\App\Model\Entity\Proyecto>|\Cake\Datasource\ResultSetInterface<\App\Model\Entity\Proyecto> deleteManyOrFail(iterable $entities, array $options = [])
 */
class ProyectosTable 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('proyectos');
        $this->setDisplayField('nombre');
        $this->setPrimaryKey('id');
        $this->addBehavior('Register');

        $this->belongsTo('Empresas', [
            'foreignKey' => 'empresa_id',
            'joinType' => 'INNER',
        ]);
        $this->belongsToMany('PalabrasClaves', [
            'foreignKey' => 'proyecto_id',
            'targetForeignKey' => 'palabra_clave_id',
            'joinTable' => 'proyectos_palabras_claves',
        ])->setDependent(true);
    }

    /**
     * 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('empresa_id')
            ->requirePresence('empresa_id', 'create',$messageEmpty)
            ->notEmptyString('empresa_id',$messageEmpty);

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

        $validator
            ->scalar('descripcion')
            ->allowEmptyString('descripcion', $messageEmpty);


        $validator
            ->requirePresence('palabras_claves', 'create',$messageEmpty)
            ->notEmptyString('palabras_claves',$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(['empresa_id'], 'Empresas'), ['errorField' => 'empresa_id']);

        return $rules;
    }

    public function dataKeyWords($data){
        if(empty($data['palabras_claves']))
        {
            return [];
        }
        $keyWords = trim($data['palabras_claves']);
        $keyWordsArray = explode(',',$keyWords);
        if(empty($keyWordsArray))
        {
            return [];
        }
        $dataWords = [];
        foreach($keyWordsArray as $keyWord)
        {
            $keyWord = trim($keyWord);
            $word = $this->PalabrasClaves->find()->where(['LOWER(PalabrasClaves.palabra)' => strtolower($keyWord)])->first();
            if(empty($word))
            {
                $dataWords[] = [
                    'palabra' => $keyWord,
                ];
            }
            else
            {
                $dataWords[] = [
                    'id' => $word->id,
                ];
            }
        }
        if(empty($dataWords))
        {
            return [];
        }
        return $dataWords;
        return $resultSaveKeyWords;

    }
}
