<?php
namespace App\Model\Table;

use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\Datasource\ConnectionManager;
use Cake\ORM\TableRegistry;
use Cake\Cache\Cache;

/**
 * Cmsusers Model
 *
 * @property \Cake\ORM\Association\BelongsTo $Companies
 */
class CmsusersTable extends AppTable
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);
        $this->addBehavior('SoftDeletable');
        $this->table('cmsusers');
        $this->displayField('username');
        $this->primaryKey('id');

        $this->belongsTo('Companies', [
            'foreignKey' => 'company_id',
            'joinType' => 'INNER'
        ]);

        $this->hasMany('CmsuserUsergroups', [
            'foreignKey' => 'cms_user_id'
        ]);
		
		$this->hasMany('Crmusers', [
            'foreignKey' => 'cmsuser_id'
        ]);
        $this->hasMany('Contacts', [
            'foreignKey' => 'cmsuser_id'
        ]);
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator)
    {
        $validator
            ->add('id', 'valid', ['rule' => 'numeric'])
            ->allowEmpty('id', 'create');

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

        $validator
            ->add('username', 'valid', ['rule' => [$this, 'isUserNameValid'], 'message' => 'The  user name is not unique'])
            ->requirePresence('username', 'create')
            ->notEmpty('username', 'The User name cannot be empty');

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


        $validator
            ->add('email', 'validemail', ['rule' => [$this, 'isEmailValid'], 'message' => 'The  user email address is not unique'])
            ->add('email', 'valid', ['rule' => [$this, 'isEmailWellFormed'], 'message' => 'The  user email address is not well formed'])
            ->requirePresence('email')
            ->notEmpty('email');

        $validator
            ->add('retype_password', 'compareWith', [
                    'rule' => ['compareWith', 'password'],
                    'message' => 'Passwords not equal.'
                ]
            )
            ->requirePresence('retype_password', 'create')
            ->notEmpty('retype_password');

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

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

        $validator
            ->add('status', 'valid', ['rule' => 'numeric'])
            ->requirePresence('status', 'create')
            ->notEmpty('status');

        return $validator;
    }

    public function isUserNameValid($value, $context)
    {
        $cmsUser = $context['data'];
        $condition = ['username' => $value];
        if (isset($cmsUser['id'])) {
            $condition['Cmsusers.id <>'] = $cmsUser['id'];
        }
        $result = $this->find('all', ['conditions' => $condition])->count();
        return ($result == 0);
    }

    public function isEmailValid($value, $context)
    {
        $cmsUser = $context['data'];
        $condition = ['email' => $value];
        if (isset($cmsUser['id'])) {
            $condition['Cmsusers.id <>'] = $cmsUser['id'];
        }
        $result = $this->find('all', ['conditions' => $condition])->count();

        return ($result == 0);
    }

    public function isEmailWellFormed($value, $context)
    {
        if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
            return true;
        }

        return false;
    }

    public function shellLog($time, $function_name,$file_name){
        $dir = WWW_ROOT."cronjob/"; 
        if(!is_dir($dir)){
            mkdir($dir,0777,true);
        }
        $file = fopen($dir.$file_name.".txt","a");
        fwrite($file,"Time : ".$time." function : ".$function_name."\n");
        fclose($file);
    }

    /**
     * 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(['username']));
        $rules->add($rules->isUnique(['email']));
        $rules->add($rules->existsIn(['company_id'], 'Companies'));
        return $rules;
    }
    
    
    public function getAllMemberListAssocId(){
        $cmsusers = $this->find()->join([
                                    'table' => 'cmsuser_usergroups',
                                    'alias' => 'CU',
                                    'type' => 'INNER',
                                    'conditions' => [
                                        'CU.cms_user_id = Cmsusers.id'
                                    ]
                                ])->select(['id','email'])->where(['CU.usergroup_id'=>USER_GROUP_ID])->toList();
        $result = [];
        if(!empty($cmsusers)){
            foreach ($cmsusers as $cmsuser){
                $result[$cmsuser->id] = $cmsuser->email;
            }
        }
        return $result;
    }
    
    public function getMemberIdByEmail($email,$appKey){
        $member_id = 0;
        if(!empty($email)){
            $member = $this->find()->select('id')->where(['email'=>$email,'zapier_appkey'=>$appKey])->first();
            if(!empty($member)){
                $member_id = $member->id;
            }
        }
        
        return $member_id;
    }
    
    public function getMemberIdByToken($appKey){
        $member_id = 0;
        if(!empty($appKey)){
            $member = $this->find()->select('id')->where(['zapier_appkey'=>$appKey])->first();
            if(!empty($member)){
                $member_id = $member->id;
            }
        }
        
        return $member_id;
    }
    
    public function getMemberIdByEmailPass($email,$pass){
        $result = "";
        if(!empty($email) && !empty($pass)){
            $member = $this->find()->where(['email'=>$email,'password'=>$pass])->first();
            if(!empty($member)){
                $result = $member;
            }
        }
        
        return $result;
    }
    
    public function getMemberByToken($token){
        $result = [];
        if(!empty($token)){
            $cmsuser = $this->find()->where(['zapier_appkey'=>$token])->first();
            if(!empty($cmsuser)){
                $result = $cmsuser;
            }
        }
        return $result;
    }
    
    
    public function enableEmployeeAssignmentByMemberIds($member_ids,$type){
        $result = false;
        //$connection = ConnectionManager::get('default');
        if(!empty($member_ids)){
            $query = "";
            $idList = [];
            foreach ($member_ids as $id){
                $idList[] = $id;
                //$query .= "Update cmsusers set has_employee = ".$type." where id = ".$id.";";
            }
            //$result = $connection->execute($query)->fetchAll('assoc');
            $cmsusers = $this->updateAll(['has_employee'=>$type], ['id IN'=>$idList]);
            $result = true;
        }
        return $result;
        
    }
    
    
    public function deleteMemberById($member_id){
        $result = false;
        if($member_id > 0){
            $cmsuser = $this->get($member_id);
            if($this->delete($cmsuser)){
                $result = $cmsuser;
            }
        }
        
        return $result;
    }
    
    public function deleteMemberByIds($member_id_list){
        $result = false;
        if(!empty($member_id_list)){
            if($this->deleteAll(['id IN'=>$member_id_list])){
                 $result = true;
            }
        }
        
        return $result;
    }
    
    public function updatePermissionVersionByMemberId($member_id, $package_ids = []){
        $result = false;
        if($member_id > 0){
            $cmsusers = $this->get($member_id);
            $cmsusers->permission_version++;
            if(!empty($package_ids) && !in_array(LIMITED_TIME_PKG_ID, $package_ids)){
                $cmsusers->is_trial_user = 0;
            }

            if($this->save($cmsusers)){
                $result = true;
            }
        }
        
        return $result;
    }
    
    public function getCmsuserById($member_id,$colums = []){
        $result = [];
        if($member_id > 0){
            $cmsuser = $this->find();
            $cmsuser = $cmsuser->select($colums);
            $cmsuser = $cmsuser->where(['id'=>$member_id])->first();
            if(!empty($cmsuser)){
                $result = $cmsuser;
            }
        }
        return $cmsuser;
    }
    
     public function isUniqueCheckEmail($email, $id = 0){
         $result = true;
         if(!empty($email)){
            $condition['email'] = $email;
            if($id > 0){
                $condition['id !='] = $id;
            }
            
            $user = $this->find()->where($condition)->first();
            if(!empty($user)){
                $result = false;
            }
         }
         return $result;
     }
     
     public function cmsuserSetVideoWatched($id){
         $result = false;
         if($id > 0){
             $conditions['id'] = $id;
             $fields['is_watched_video'] = 1;
             if($this->updateAll($fields, $conditions)){
                 $result = true;
             }
         }
         return $result;
     }
     
     public function isMembershipActive($member_id){
        $result = false;
         if($member_id > 0){           
            $cmsuserUsergroupsObj = TableRegistry::get("CmsuserUsergroups");

                $user = $cmsuserUsergroupsObj->find()->where([
                    'cms_user_id' => $member_id
                    // 'usergroup_id' => CUSTOMER_USER_GROUP_ID
                ])->first();
            
            if($user){
                $result = true;
            }
         }
         return $result;
     }
     
     public function setIsActive($id,$status){
         $result = false;
         if($id > 0){
             $current_date_time = $this->getSystemCurrentTimeStamp();
             $conditions['id'] = $id;
             $fields['is_active'] = $status;
             if($fields['is_active'] == 1){
                 $fields['last_active_date'] = $current_date_time;
             }else if($fields['is_active'] == 0){
                 $fields['last_inactive_date'] = $current_date_time;
             }
             if($this->updateAll($fields, $conditions)){
                 $result = true;
             }
         }
         return $result;
    }
    
    
    public function passwordAllowActionById($cmsuser_id,$new_password){
        $result = false;
        if($cmsuser_id > 0 && !empty($new_password)){
            $cmsuser = $this->find()->where(['id'=>$cmsuser_id])->first();
            $cmsuser->backup_old_password = md5($new_password);//$cmsuser->password;
           // $cmsuser->password = $new_password;
            $cmsuser->is_allow_defult_pass = 1;
            
            if($this->save($cmsuser)){
                $result = true;
            }
        }
        
        return $result;
    }
    
    public function passwordRevokeActionById($cmsuser_id){
        $result = false;
        if($cmsuser_id > 0){
            
            $cmsuser = $this->find()->where(['id'=>$cmsuser_id])->first();
            
            $conditions['id'] = $cmsuser_id;
            $conditions['is_allow_defult_pass'] = 1;
            
            $fields['is_allow_defult_pass'] = 0;
           // $fields['password'] = $cmsuser->backup_old_password;
            $fields['backup_old_password'] = "";
            
            if($this->updateAll($fields, $conditions)){
                $result = true;
            }
        }
        
        return $result;
    }
    
    
     public function statusChangeMemberRelatedInfoByMemberId($status,$member_id){
        $result = false;
        if($member_id > 0){
            
            $contactsTable = TableRegistry::get('contacts');
            $invoicesTable = TableRegistry::get('invoices');
            $letter_email_schedulesTable = TableRegistry::get('letter_email_schedules');
            $AutomationSchedulesTable = TableRegistry::get('AutomationSchedules');
            $member_campaign_clientsTable = TableRegistry::get('member_campaign_clients');
            $setup_email_automation_schedulesTable = TableRegistry::get('setup_email_automation_schedules');
            
            $contacts = $contactsTable->find()->where(['cmsuser_id'=>$member_id])->toArray();
            if(!empty($contacts)){
                foreach($contacts as $contact){
                    // letter email schedule inactive
                    $letter_email_schedulesTable->updateAll(['is_active'=>$status], ['client_email'=>$contact->email]);
                }
            }
            
            // automation schedule inactive
            $AutomationSchedulesTable->updateAll(['is_active'=>$status], ['member_id'=>$member_id]);
            
            // campaign inactive
            $setup_email_automation_schedulesTable->updateAll(['is_active'=>$status], ['member_id'=>$member_id]);
            
            // invoice recurring status change
            $invoice_status = 0;
            if($status == 0){
                $invoice_status = 1;
            }
            $invoicesTable->updateAll(['is_payment_process'=>$invoice_status], ['cmsuser_id'=>$member_id]);

            $result = true;
        }
        
        return $result;
    }
    
    public function cmsuserUpdate($cmsuser_id,$updateData){
        $result = false;
        
        if($cmsuser_id > 0 && !empty($updateData)){
            $conditions['id'] = $cmsuser_id;
            $result = $this->updateAll($updateData, $conditions);
        }
        
        return $result;
    }
    
    
    public function setLoginTime($id){
        $result = false;
        $current_date_time = $this->getSystemCurrentTimeStamp();
        $cmsuser = $this->get($id);
        
        $cmsuser->last_login_date = $current_date_time;
        if($this->save($cmsuser)){
            $result = true;
        }
        
        return $result;
    }
    
    public function getMemberInfoByAffiliateKey($unique_key){
        return $this->find()->where(['affiliate_unique_key'=>$unique_key])->first();
    }

    public function getMemberByEmailAndPassword($email,$password){
        $exceptColumn = [
                    'password',
                    'backup_old_password',
                    'reset_password_token'
                ];
        return $this->find()
                    ->selectAllExcept($this,$exceptColumn)
                    ->where(['email'=>$email,'password'=>md5($password)])->first();
    }


    public function getAllmembersTimeZoneAssoc(){
         return Cache::remember('timenones', function () {
            $cmsusers = $this->find()->select(['id','time_zone'])->toList();
            $return = [];
            if(!empty($cmsusers)){
                foreach($cmsusers as $cmsuser){
                    if(!empty($cmsuser->time_zone)){
                        $return[$cmsuser->id] = $cmsuser->time_zone;
                    }
                }
            }
            return $return;
         });

        
    }


    public function getAllMembersWithPackages($search = []){
        $this->removeBehavior('SoftDeletable');
        $member_package_joinType = 'LEFT';
        $member_tshirt_joinType = 'LEFT';
        $member_certificate_joinType = 'LEFT';
        
        $select = [
            'Cmsusers.username',
            'Cmsusers.email',
            'Cmsusers.phone',
            'Cmsusers.status',
            'Cmsusers.id',
            'Cmsusers.is_detect_trial_user',
            'Cmsusers.is_trial_user',
            'Cmsusers.is_zapier',
            'Cmsusers.has_employee',
            'Cmsusers.created_on',
        ];
        $member_packages = $this->find()
                                ->distinct(['Cmsusers.id']);
        $member_package_table = TableRegistry::get('member_packages');
        $table_user_groups_user = TableRegistry::get("CmsuserUsergroups");                        
        $is_join_member_package = true;
        $clause = [];
        $clause['Cmsusers.id NOT IN'] = ADMIN_IDS;
        if(!empty($search)){
            if(isset($search['search']) && !empty($search['search'])){
                $clause['OR'] = " (Cmsusers.email LIKE '%" . $search['search'] . "%' OR Cmsusers.username LIKE '%" . $search['search'] . "%') ";
            }
            
            if (isset($search['is_zapier'])) {
                if($search['is_zapier'] == "1" || $search['is_zapier'] == "0"){
                    $clause['Cmsusers.is_zapier'] = $search['is_zapier'];
                }
            }
            
            if (isset($search['status'])) {
                if($search['status'] == "1"){
                    $clause['Cmsusers.status'] = 1;
                    $clause['Cmsusers.is_trial_user'] = 0;
                }else if($search['status'] == "2"){
                    $clause['Cmsusers.status'] = 1;
                }else if($search['status'] == "4"){
                    $clause['Cmsusers.is_detect_trial_user'] = 1;
                }
            }
            
            if (isset($search['active_member_ids']) && !empty($search['active_member_ids'])) {
                $member_package_joinType = 'LEFT';
                //$clause['Cmsusers.id IN'] = $search['active_member_ids'];
                $member_packages = $member_packages
                ->select($select)
                ->join([
                    'table' => 'cmsuser_usergroups',
                    'alias' => 'CmsuserUsergroups',
                    'type' => "INNER",
                    'conditions' => [
                        'CmsuserUsergroups.cms_user_id = Cmsusers.id',
                        'CmsuserUsergroups.usergroup_id = '.CUSTOMER_USER_GROUP_ID
                    ]
                ]);
                
            }
            
            if (isset($search['inactive_member_ids']) && !empty($search['inactive_member_ids'])) {
                $member_package_joinType = 'LEFT';
                $is_join_member_package = false;
                $clause['AND'][] = ['Cmsusers.id NOT IN' => $table_user_groups_user->find()->select(['cms_user_id'])->where(['usergroup_id'=>CUSTOMER_USER_GROUP_ID])];
                
            }
            
            
           
            if (isset($search['active_velocity_member']) && !empty($search['active_velocity_member'])) {
                $member_package_joinType = 'INNER';//ADMIN_IDS
                $is_join_member_package = false;
                $clause['AND'][] = ['Cmsusers.id IN'=>$member_package_table->find()->select('member_id')->where(['package_id'=>SERTG_PACKAGE_ID])]; 
            }
            
            if (isset($search['inactive_velocity_member']) && !empty($search['inactive_velocity_member'])) {
                $member_package_joinType = 'LEFT OUTER';//ADMIN_IDS
                $is_join_member_package = false;
                $clause['AND'][] = ['Cmsusers.id NOT IN'=>$member_package_table->find()->select('member_id')->where(['package_id'=>SERTG_PACKAGE_ID])]; 
                
            }

            if(isset($search['velocity_active_inactive_members']) && !empty($search['velocity_active_inactive_members'])){
                $is_join_member_package = false;
                if(!empty($clause['Cmsusers.id IN']) || !empty($clause['Cmsusers.id IN'])){
                    $clause['Cmsusers.id IN'] = array_merge($clause['Cmsusers.id IN'],$search['activememberIdList']);
                }
                
            }
            
            if (isset($search['active_employee']) && !empty($search['active_employee'])) {
                if($search['active_employee'] == 2){
                    $search['active_employee'] = 0;
                }
                $clause['Cmsusers.has_employee'] = $search['active_employee'];
            }

            if (isset($search['is_certificate_download'])) {
                if($search['is_certificate_download'] == "1"){
                    $clause['Cmsusers.id IN'] = $search['certificate_download_member_ids'];
                }else if($search['is_certificate_download'] == "0"){
                    $clause['Cmsusers.id NOT IN'] = array_merge($search['certificate_download_member_ids'] , ADMIN_IDS);
                }
            }

            if (isset($search['is_tshirt_ordered'])) {
                if($search['is_tshirt_ordered'] == "1"){
                    if(!empty($search['tshirt_ordered_member_ids'])){
                        $clause['Cmsusers.id IN'] = $search['tshirt_ordered_member_ids'];
                    }else{
                        $clause['Cmsusers.id IN'] = [-1];
                    }
                    
                }else if($search['is_tshirt_ordered'] == "0"){
                    $clause['Cmsusers.id NOT IN'] = array_merge($search['tshirt_ordered_member_ids'] , ADMIN_IDS);
                }                    
            }

            
        }
        $member_package_condition[] = 'Cmsusers.id = MemberPackages.member_id';
        if($is_join_member_package)
        $member_packages = $member_packages
                                    ->select($select)
                                    ->join([
                                        'table' => 'member_packages',
                                        'alias' => 'MemberPackages',
                                        'type' => $member_package_joinType,
                                        'conditions' => $member_package_condition
                                    ]);
            
       // dd($clause);                            
        $member_packages = $member_packages->where($clause)->orderAsc('Cmsusers.id');
        return $member_packages;                            
    }


}
