<?php
namespace App\Model\Table;

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

/**
 * PlanAddons Model
 *
 * @property \App\Model\Table\PlansTable|\Cake\ORM\Association\BelongsTo $Plans
 * @property \App\Model\Table\AddonsTable|\Cake\ORM\Association\BelongsTo $Addons
 * @property \App\Model\Table\SaleAddonsTable|\Cake\ORM\Association\HasMany $SaleAddons
 *
 * @method \App\Model\Entity\PlanAddon get($primaryKey, $options = [])
 * @method \App\Model\Entity\PlanAddon newEntity($data = null, array $options = [])
 * @method \App\Model\Entity\PlanAddon[] newEntities(array $data, array $options = [])
 * @method \App\Model\Entity\PlanAddon|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
 * @method \App\Model\Entity\PlanAddon patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
 * @method \App\Model\Entity\PlanAddon[] patchEntities($entities, array $data, array $options = [])
 * @method \App\Model\Entity\PlanAddon findOrCreate($search, callable $callback = null, $options = [])
 *
 * @mixin \Cake\ORM\Behavior\TimestampBehavior
 */
class PlanAddonsTable extends Table
{

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

        $this->setTable('plan_addons');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('Plans', [
            'foreignKey' => 'plan_id',
            'joinType' => 'INNER'
        ]);
        $this->belongsTo('Addons', [
            'foreignKey' => 'addon_id',
            'joinType' => 'INNER'
        ]);
        $this->hasMany('SaleAddons', [
            'foreignKey' => 'plan_addon_id'
        ]);
    }

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

        $validator
            ->decimal('price')
            ->allowEmpty('price');

        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(['plan_id'], 'Plans'));
        $rules->add($rules->existsIn(['addon_id'], 'Addons'));

        return $rules;
    }
}
