<?php

namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;/**
 * Everythings Model
 *
 * @property \App\Model\Table\MembersTable|\Cake\ORM\Association\BelongsTo $Members
 * @property \App\Model\Table\ActionBiesTable|\Cake\ORM\Association\BelongsTo $ActionBies
 * @property \App\Model\Table\ActionOnsTable|\Cake\ORM\Association\BelongsTo $ActionOns
 *
 * @method \App\Model\Entity\Everything get($primaryKey, $options = [])
 * @method \App\Model\Entity\Everything newEntity($data = null, array $options = [])
 * @method \App\Model\Entity\Everything[] newEntities(array $data, array $options = [])
 * @method \App\Model\Entity\Everything|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
 * @method \App\Model\Entity\Everything|bool saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = [])
 * @method \App\Model\Entity\Everything patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
 * @method \App\Model\Entity\Everything[] patchEntities($entities, array $data, array $options = [])
 * @method \App\Model\Entity\Everything findOrCreate($search, callable $callback = null, $options = [])
 */

class EverythingsTable extends AppTable {

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config) {
        parent::initialize($config);
        $this->setTable('everythings');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');
        $this->belongsTo('Members', [
            'foreignKey' => 'member_id',
            'joinType' => 'INNER'
        ]);
        $this->belongsTo('ActionBies', [
            'foreignKey' => 'action_by_id',
            'joinType' => 'INNER'
        ]);
        $this->belongsTo('ActionOns', [
            'foreignKey' => 'action_on_id',
            'joinType' => 'INNER'
        ]);
    }

    /**
     * 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->scalar('action_by_name')->maxLength('action_by_name', 30)->requirePresence('action_by_name', 'create')->notEmpty('action_by_name');
        $validator->scalar('action_on_name')->maxLength('action_on_name', 30)->requirePresence('action_on_name', 'create')->notEmpty('action_on_name');
        $validator->scalar('display_message')->maxLength('display_message', 150)->requirePresence('display_message', 'create')->notEmpty('display_message');
        $validator->dateTime('created_at')->requirePresence('created_at', 'create')->notEmpty('created_at');
        $validator->requirePresence('action_by_usertype', 'create')->notEmpty('action_by_usertype');
        $validator->requirePresence('action_on_usertype', 'create')->notEmpty('action_on_usertype');
        return $validator;
    }

    
    public function inserEverything($inputData) {
        $result = false;
        if(!empty($inputData)){
            $current_date_time = $this->getSystemCurrentTimeStamp();
            $query = $this->query();
            $inputData['created_at'] = $current_date_time;
            $column = array_keys($inputData); 
            $query = $query
                        ->insert($column)
                        ->values($inputData);
            
            if($query->execute()){
                $result = true;
            }
        }
        
        return $result;
    }
    
    
    public function getEverythingByMemberId($member_id) {
        $result = [];
        if($member_id > 0){
            $userTypeName = $this->getCurrentUserType();
            if($userTypeName == "MEMBER"){
                $clause['member_id'] = $member_id;
            }else if($userTypeName == "EMPLOYEE"){
                $clause['action_by_id'] = $_SESSION['Auth']['User']['user_id'];
                $clause['action_by_usertype'] = 2;
            }
            
            $everythings = $this->find()
                                ->where($clause)
                                ->orderDesc('created_at')
                                ->toArray();
            if(!empty($everythings)){
                foreach($everythings as $e){
                    
                    $created_at = date('Y-m-d', strtotime($e->created_at));
                    $created_at_time = date('Y-m-d H:i:s', strtotime($e->created_at));
                    
                    $result[$created_at]['date'] = $created_at_time;
                    $result[$created_at]['everything'][] = $e;
                }
            }
        }
        return $result;
    }
    
    public function getEveryThingByActionOnUserType($member_id, $action_on_user_type, $action_on_id = 0) { //	2 = crmuser, 1 = member, 3 = contact user, 4 = staff user	
        $result = [];
        if($member_id > 0){
            $userTypeName = $this->getCurrentUserType();
            if($userTypeName == "MEMBER"){
                $clause['member_id'] = $member_id;
            }else if($userTypeName == "EMPLOYEE"){
                $clause['action_by_id'] = $_SESSION['Auth']['User']['user_id'];
                $clause['action_by_usertype'] = 2;
            }
            
            $clause['action_on_usertype'] = $action_on_user_type;
            if($action_on_id > 0){
                $clause['action_on_id'] = $action_on_id;
            }
            
            //pr($clause);exit;
            $everythings = $this->find()
                                ->where($clause)
                                ->orderDesc('created_at')
                                ->toArray();
            if(!empty($everythings)){
                foreach($everythings as $e){
                    
                    $created_at = date('Y-m-d', strtotime($e->created_at));
                    $created_at_time = date('Y-m-d H:i:s', strtotime($e->created_at));
                    
                    $result[$created_at]['date'] = $created_at_time;
                    $result[$created_at]['everything'][] = $e;
                }
            }
        }
        return $result;
    }
    
    public function getEveryThingByActionByUserType($member_id, $action_by_user_type, $action_by_id = 0) { //	2 = crmuser, 1 = member, 3 = contact user, 4 = staff user	
        $result = [];
        
        if($member_id > 0){
            $clause['member_id'] = $member_id;
            $clause['action_by_usertype'] = $action_by_user_type;
            if($action_by_id > 0){
                $clause['action_by_id'] = $action_by_id;
            }
            $everythings = $this->find()
                                ->where($clause)
                                ->orderDesc('created_at')
                                ->toArray();
            
            if(!empty($everythings)){
                foreach($everythings as $e){
                    
                    $created_at = date('Y-m-d', strtotime($e->created_at));
                    $created_at_time = date('Y-m-d H:i:s', strtotime($e->created_at));
                    
                    $result[$created_at]['date'] = $created_at_time;
                    $result[$created_at]['everything'][] = $e;
                }
            }
        }
        
        return $result;
    }
    /**
     * 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(['member_id'], 'Members'));
//        $rules->add($rules->existsIn(['action_by_id'], 'ActionBies'));
//        $rules->add($rules->existsIn(['action_on_id'], 'ActionOns'));
//        return $rules;
//    }

}
