<?php
namespace App\Model\Table;

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

/**
 * UnitsUsers Model
 *
 * @property \Cake\ORM\Association\BelongsTo $Users
 * @property \Cake\ORM\Association\BelongsTo $Units
 */
class UnitsUsersTable extends Table
{

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

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

        $this->belongsTo('Users', [
            'foreignKey' => 'user_id',
            'joinType' => 'INNER'
        ]);
        $this->belongsTo('Units', [
            'foreignKey' => 'unit_id',
            'joinType' => 'INNER'
        ]);

        // $this->hasOne('Privileges', [
        //     'foreignKey' => 'privilege_id'            
        // ]);
        $this->belongsTo('Privileges', [
            'foreignKey' => 'privilege_id',
            'joinType' => 'INNER'
        ]);

      //    $this->belongsToMany('Units', [
      //       'foreignKey' => 'user_id',
      //       'targetForeignKey' => 'unit_id',
      //       'joinTable' => 'units_users'
      //   ]);

      // $this->belongsToMany('Units', [
      //       'foreignKey' => 'user_id',
      //       'targetForeignKey' => 'unit_id',
      //       'joinTable' => 'units_users'
      //   ]);
    }

    /**
     * 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');

        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(['privilege_id'], 'Privileges'));
        $rules->add($rules->existsIn(['user_id'], 'Users'));
        $rules->add($rules->existsIn(['unit_id'], 'Units'));
        return $rules;
    }
}
