<?php
namespace App\Model\Table;

use App\Model\Entity\Admission;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

/**
 * Admissions Model
 *
 * @property \Cake\ORM\Association\BelongsTo $Screenings
 * @property \Cake\ORM\Association\HasMany $HabitualMedications
 * @property \Cake\ORM\Association\HasMany $Hpps
 * @property \Cake\ORM\Association\HasMany $PhysicalExams
 * @property \Cake\ORM\Association\HasMany $RelevantComplementaryExams
 */
class AdmissionsTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('admissions');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('Screenings', [
            'foreignKey' => 'screening_id',
            'joinType' => 'INNER'
        ]);
        $this->hasMany('HabitualMedications', [
            'foreignKey' => 'admission_id'
        ]);
        $this->hasMany('Hpps', [
            'foreignKey' => 'admission_id'
        ]);
        $this->hasMany('PhysicalExams', [
            'foreignKey' => 'admission_id'
        ]);
        $this->hasMany('RelevantComplementaryExams', [
            'foreignKey' => 'admission_id'
        ]);
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator)
    {
        $validator
            ->integer('id')
            ->allowEmpty('id', 'create');

        $validator
            ->allowEmpty('motivo');

        $validator
            ->allowEmpty('hda');

        $validator
            ->allowEmpty('int_hb');

        $validator
            ->allowEmpty('int_cti');

        $validator
            ->allowEmpty('equipe_assistente');

        $validator
            ->allowEmpty('alergias');

        $validator
            ->boolean('isolamento')
            ->allowEmpty('isolamento');

        $validator
            ->allowEmpty('motivo_hda');

        $validator
            ->allowEmpty('outras_patologia');

        $validator
            ->allowEmpty('status');

        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)
    {
        $rules->add($rules->existsIn(['screening_id'], 'Screenings'));
        return $rules;
    }
}
