<?php
namespace App\Model\Table;

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

/**
 * Personalizes Model
 *
 * @property \App\Model\Table\MembersTable&\Cake\ORM\Association\BelongsTo $Members
 * @property \App\Model\Table\CompaniesTable&\Cake\ORM\Association\BelongsTo $Companies
 *
 * @method \App\Model\Entity\Personalize get($primaryKey, $options = [])
 * @method \App\Model\Entity\Personalize newEntity($data = null, array $options = [])
 * @method \App\Model\Entity\Personalize[] newEntities(array $data, array $options = [])
 * @method \App\Model\Entity\Personalize|false save(\Cake\Datasource\EntityInterface $entity, $options = [])
 * @method \App\Model\Entity\Personalize saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = [])
 * @method \App\Model\Entity\Personalize patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
 * @method \App\Model\Entity\Personalize[] patchEntities($entities, array $data, array $options = [])
 * @method \App\Model\Entity\Personalize findOrCreate($search, callable $callback = null, $options = [])
 */
class PersonalizesTable extends Table
{
    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

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

        $this->belongsTo('Members', [
            'foreignKey' => 'member_id',
            'joinType' => 'INNER',
        ]);
        $this->belongsTo('Companies', [
            'foreignKey' => 'company_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')
            ->allowEmptyString('id', null, 'create');

        $validator
            ->requirePresence('is_smtp', 'create')
            ->notEmptyString('is_smtp');

        $validator
            ->scalar('username')
            ->maxLength('username', 100)
            ->allowEmptyString('username');

        $validator
            ->scalar('password')
            ->maxLength('password', 100)
            ->allowEmptyString('password');

        $validator
            ->integer('smtp_port')
            ->allowEmptyString('smtp_port');

        $validator
            ->scalar('smtp_host')
            ->maxLength('smtp_host', 50)
            ->allowEmptyString('smtp_host');

        $validator
            ->scalar('smtp_from')
            ->maxLength('smtp_from', 50)
            ->allowEmptyString('smtp_from');

        $validator
            ->scalar('email_signature')
            ->maxLength('email_signature', 100)
            ->allowEmptyString('email_signature');

        $validator
            ->scalar('domain_type')
            ->maxLength('domain_type', 10)
            ->notEmptyString('domain_type');

        $validator
            ->notEmptyString('is_www');

        $validator
            ->scalar('domain')
            ->maxLength('domain', 50)
            ->allowEmptyString('domain');

        $validator
            ->dateTime('created_at')
            ->allowEmptyDateTime('created_at');

        $validator
            ->dateTime('updated_at')
            ->allowEmptyDateTime('updated_at');

        $validator
            ->scalar('header')
            ->maxLength('header', 100)
            ->allowEmptyString('header');

        $validator
            ->scalar('footer')
            ->maxLength('footer', 255)
            ->allowEmptyString('footer');

        return $validator;
    }

    public function processPersonalize($inputData,$is_data_needed = false){

        $result = false;
        $personalizeInfo = $this->find()->where(['company_id'=>$inputData['company_id']])->first();

        if(!empty($personalizeInfo)){
            $personalize = $this->get($personalizeInfo->id);
        }
        else{
            $personalize = $this->newEntity();
        }

        //$personalize->is_www = $inputData['is_www'];
        //$personalize->domain_type = $inputData['domain_type'];

        $personalize->member_id = empty($personalize->member_id) ? $inputData['member_id'] : $personalize->member_id;
        $personalize->company_id = $inputData['company_id'];
        $personalize->is_smtp = isset($inputData['is_smtp']) ? $inputData['is_smtp'] : 0;
        $personalize->username = trim($inputData['username']);
        $personalize->password = trim($inputData['password']);
        $personalize->smtp_host = trim($inputData['smtp_host']);
        $personalize->smtp_port = trim($inputData['smtp_port']);
        $personalize->smtp_from = trim($inputData['smtp_from']);
        $personalize->email_signature = trim($inputData['email_signature']);
        //$personalize->domain = trim($inputData['domain']);
        $personalize->header = trim($inputData['header']);
        $personalize->footer = trim($inputData['footer']);
        $personalize->created_at = date('Y-m-d H:i:s');
        //pr($personalize);exit;
        if($savedData = $this->save($personalize)){

            if($is_data_needed){
                $result = $savedData;
            }else{
                $result = true;
            }

        }

        return $result;
    }

    public function insertSmtp($inputData){
        $result = false;

        if(!empty($inputData)){

            $member_id = $inputData['member_id'];

            $personalizeInfo = $this->find()->where(['member_id'=>$member_id])->first();
            if(!empty($personalizeInfo)){
                $personalize = $this->get($personalizeInfo->id);
            }else{
                $personalize = $this->newEntity();
            }

            $personalize->member_id = $inputData['member_id'];
            $personalize->company_id = $inputData['company_id'];
            $personalize->is_smtp = 1;
            $personalize->username = trim($inputData['username']);
            $personalize->password = trim($inputData['password']);
            $personalize->smtp_host = trim($inputData['smtp_host']);
            $personalize->smtp_port = trim($inputData['smtp_port']);
            $personalize->smtp_from = trim($inputData['smtp_from']);
            $personalize->email_signature = trim($inputData['email_signature']);

            if($this->save($personalize)){
                $result = true;
            }
        }
        return $result;
    }

    public function getPersonalizeByDomain($domain){
        $result = array();
        $personalize = $this->find()->where(['domain'=>$domain])->first();
        if(!empty($personalize)){
            $result = $personalize;
        }

        return $result;
    }

    public function getPersonalizeByMemberId($member_id){

        $personalize = $this->find()->where(['member_id'=>$member_id])->first();
        return $personalize;
    }

    public function getPersonalizeByMemberIds($member_ids){
        $personalize = [];
        if(is_array($member_ids) && !empty($member_ids)){
            $personalize = $this->find()->where(['member_id IN '=>$member_ids])->toArray();

        }
        return $personalize;
    }
    public function deletePersonalizeByMemberId($member_id){
        $result = false;
        if($member_id > 0){
            $personalize = $this->find()->where(['member_id'=>$member_id])->first();
            if($this->delete($personalize)){
                $result = $personalize;
            }
        }
        return $result;
    }

    public function getAllPersonalizeEmails(){
        $result = [];
        $personalizes = $this->find()->where(['is_smtp'=>1])->toArray();
        if(!empty($personalizes)){
            foreach($personalizes as $pesonalize){
                if($pesonalize->member_id > 0){
                    //$result[$pesonalize->member_id] = json_decode(json_encode($pesonalize),true);
                    $result[$pesonalize->member_id]['id'] = $pesonalize->id;
                    $result[$pesonalize->member_id]['member_id'] = $pesonalize->member_id;
                    $result[$pesonalize->member_id]['is_smtp'] = $pesonalize->is_smtp;
                    $result[$pesonalize->member_id]['username'] = $pesonalize->username;
                    $result[$pesonalize->member_id]['password'] = $pesonalize->password;
                    $result[$pesonalize->member_id]['smtp_port'] = $pesonalize->smtp_port;
                    $result[$pesonalize->member_id]['smtp_host'] = $pesonalize->smtp_host;
                    $result[$pesonalize->member_id]['smtp_from'] = $pesonalize->smtp_from;
                    $result[$pesonalize->member_id]['email_signature'] = $pesonalize->email_signature;
                    $result[$pesonalize->member_id]['domain_type'] = $pesonalize->domain_type;
                    $result[$pesonalize->member_id]['is_www'] = $pesonalize->is_www;
                    $result[$pesonalize->member_id]['domain'] = $pesonalize->domain;
                    $result[$pesonalize->member_id]['created_at'] = $pesonalize->created_at;
                }
            }
        }
        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->isUnique(['username']));
        $rules->add($rules->existsIn(['member_id'], 'Members'));
        $rules->add($rules->existsIn(['company_id'], 'Companies'));

        return $rules;
    }
    */
}
