<?php
namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

/**
 * Supervisings Model
 *
 * @property \Cake\ORM\Association\BelongsTo $Schooltypes
 * @property \Cake\ORM\Association\HasMany $Departments
 *
 * @method \App\Model\Entity\Supervising get($primaryKey, $options = [])
 * @method \App\Model\Entity\Supervising newEntity($data = null, array $options = [])
 * @method \App\Model\Entity\Supervising[] newEntities(array $data, array $options = [])
 * @method \App\Model\Entity\Supervising|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
 * @method \App\Model\Entity\Supervising patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
 * @method \App\Model\Entity\Supervising[] patchEntities($entities, array $data, array $options = [])
 * @method \App\Model\Entity\Supervising findOrCreate($search, callable $callback = null, $options = [])
 *
 * @mixin \Cake\ORM\Behavior\TimestampBehavior
 */
class SupervisingsTable extends Table
{

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

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

        $this->addBehavior('Timestamp');

        $this->belongsTo('Schooltypes', [
            'foreignKey' => 'schooltype_id',
            'joinType' => 'INNER'
        ]);
        $this->hasMany('Departments', [
            'foreignKey' => 'supervising_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
            ->requirePresence('code', 'create')
            ->notEmpty('code');

        $validator
            ->requirePresence('token', 'create')
            ->notEmpty('token');

        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(['schooltype_id'], 'Schooltypes'));

        return $rules;
    }
}
