<?php
namespace App\Model\Table;

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

/**
 * Users Model
 *
 * @property \App\Model\Table\AddressesTable|\Cake\ORM\Association\HasMany $Addresses
 * @property \App\Model\Table\LinesTable|\Cake\ORM\Association\HasMany $Lines
 * @property \App\Model\Table\SalesTable|\Cake\ORM\Association\HasMany $Sales
 *
 * @method \App\Model\Entity\User get($primaryKey, $options = [])
 * @method \App\Model\Entity\User newEntity($data = null, array $options = [])
 * @method \App\Model\Entity\User[] newEntities(array $data, array $options = [])
 * @method \App\Model\Entity\User|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
 * @method \App\Model\Entity\User patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
 * @method \App\Model\Entity\User[] patchEntities($entities, array $data, array $options = [])
 * @method \App\Model\Entity\User findOrCreate($search, callable $callback = null, $options = [])
 *
 * @mixin \Cake\ORM\Behavior\TimestampBehavior
 */
class UsersTable extends Table
{

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

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

        $this->addBehavior('Timestamp');

        $this->hasMany('Addresses', [
            'foreignKey' => 'user_id'
        ]);
        $this->hasMany('Lines', [
            'foreignKey' => 'user_id'
        ]);
        $this->hasMany('Sales', [
            'foreignKey' => 'user_id'
        ]);
        
        $this->hasOne('Leads');
    }

    /**
     * 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
            ->scalar('member_num')
            ->maxLength('member_num', 255)
            ->allowEmpty('member_num');

        $validator
            ->scalar('salutation')
            ->maxLength('salutation', 45)
            ->allowEmpty('salutation');

        $validator
            ->scalar('first_name')
            ->maxLength('first_name', 45)
            ->allowEmpty('first_name');

        $validator
            ->scalar('last_name')
            ->maxLength('last_name', 45)
            ->allowEmpty('last_name');

        $validator
            ->email('email')
            ->allowEmpty('email');

        $validator
            ->scalar('password')
            ->maxLength('password', 255)
            ->allowEmpty('password')
            ->add('password', 'unique', ['rule' => 'validateUnique', 'provider' => 'table']);

        $validator
            ->scalar('mobile_no')
            ->maxLength('mobile_no', 255)
            ->allowEmpty('mobile_no');

        $validator
            ->scalar('nationality')
            ->maxLength('nationality', 45)
            ->allowEmpty('nationality');

        $validator
            ->integer('id_type')
            ->allowEmpty('id_type');

        $validator
            ->scalar('nric')
            ->maxLength('nric', 45)
            ->allowEmpty('nric');

        $validator
            ->scalar('fin')
            ->maxLength('fin', 45)
            ->allowEmpty('fin');

        $validator
            ->integer('status')
            ->allowEmpty('status');
        
        $validator
            ->scalar('token')
            ->allowEmpty('token');
        
        $validator
            ->boolean('tc')
            ->allowEmpty('tc');
        
        $validator
            ->boolean('tc_sms')
            ->allowEmpty('tc_sms');
        
        $validator
            ->boolean('tc_phone')
            ->allowEmpty('tc_phone');
        
        $validator
            ->boolean('tc_email')
            ->allowEmpty('tc_email');
        
        $validator
            ->scalar('stripe_customer_id')
            ->maxLength('stripe_customer_id', 255)
            ->allowEmpty('stripe_customer_id');

        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->isUnique(['email']));
        
        return $rules;
    }
    
    
    public function beforeSave( \Cake\Event\Event $event, \Cake\ORM\Entity $entity, $options ) {
        
        if ( $entity->isNew() ) {
            $user = $this->find( 'all', ['fields' => array('max_no' => 'MAX(Users.member_num)')] )->first();
            
            $max_no = ($user->max_no) ? $user->max_no : 0;
            
            $next_no = (0 == $max_no)? User::CUSTOMER_NO_START_FROM : $max_no + 1;
            
            $event->data( 'entity' )->member_num = $next_no;
        }
    }
}
