<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Auth\DefaultPasswordHasher;
use Cake\Core\Configure;
use Cake\Http\Client;
use Cake\Routing\Router;
use Cake\I18n\Time;
use Cake\Mailer\Email;
use Cake\Utility\Security;

class UsersController extends AppController
{

    public function index()
    {
	return $this->redirect(['controller' => 'Users', 'action' => 'signin']);
    }

    public function signin()
    {
        $this->viewBuilder()->layout('blank');
    }

    #Signin
    public function verify()
    {
        $this->viewBuilder()->layout('blank');

        $data = $this->request->data();
		#$data['data']['ip'] = $this->request->clientIp();

        if(!empty($data)){
		if(!empty($data['data']['username']) && !empty($data['data']['password'])){
			$data['data']['ip'] = $this->request->clientIp();#prr($data);
				
			$api_core_signin = Configure::read('Config.apiCore.signin');
			$http = new Client();
			$response = $http->post($api_core_signin,$data['data'])->body();			
			$response = json_decode($response,'_full');#prd($response);

			if(!empty($response)){
				if(trim($response['status']) == 'Success'){
					$url = Router::url(['controller' => 'Homes', 'action' => 'index'], true);

					echo "<script>setTimeout(function(){Login.onLogin('".$response['result']['token']."','".$url."','".$response['result']['topic']."')},1000);</script>";
					#echo "<script>setTimeout(function(){alert('".$response['result']['token']."')},1000);</script>";
					#echo "<script>Login.onLogin('".$response['result']['token']."','".$url."','".$response['result']['topic']."');</script>";
					#echo "<button onclick=Login.onLogin('".$response['result']['token']."','".$url."','".$response['result']['topic']."')>CLICK</button>";
					
					#------------------------------------------------------------------
					$param = [];
					$param['topic'] = '/topics/'.$response['result']['topic'];
					$param['title'] = '';
					$param['message'] = '';
					$param['badge'] = 1;
					
					#$api_notification = 'http://connect05.pakgon.com/api/Notifications/push';
					$api_notification = Configure::read('Config.apiCommunication.getNotification');
					
					$http = new Client();
					$options = [
					    'headers' => [
					        'Content-Type' => 'application/x-www-form-urlencoded',
					    ]
					];
					$response = $http->post($api_notification, $param, $options)->body();
					#prr($response);
					#------------------------------------------------------------------						
					
					die;
										
				}else{
					$this->Flash->error(__('Verify Fail'));
					return $this->redirect(['controller' => 'Users', 'action' => 'signin']);	
				}
			}else{
				$this->Flash->error(__('Verify Fail'));
				return $this->redirect(['controller' => 'Users', 'action' => 'signin']);			
			}
				
		}else{
			$this->Flash->error(__('Data Empty'));
			return $this->redirect(['controller' => 'Users', 'action' => 'signin']);		
		}				
        }

    }

    public function signup()
    {	
		$this->loadModel('MasterCountries');
		$this->loadModel('MasterProvinces');

		$countries = $this->MasterCountries->find('list',
			[
				'conditions' => ['is_used' => true],
				'keyField' => 'id',
				'valueField' => ['country_name_th']
			]
		);
		if(!empty($countries)) $countries = $countries->toArray();
		
		$provinces = $this->MasterProvinces->find('list',
			[
				'conditions' => ['is_used' => true],
				'keyField' => 'id',
				'valueField' => 'province_name_th'          
			]
		);
		if(!empty($provinces)) $provinces = $provinces->toArray();
		$this->set(compact('provinces','countries'));

        $this->viewBuilder()->layout('blank');
	}
	
	// public function getProvince() {
	// 	$this->autoRender = false;
	// 	$this->loadModel('MasterProvinces');
	// 	$states = array();
	// 	pr($this->request->$data);die;
	// 	if (isset($this->request['data']['id'])) {
	// 		$states = $this->MasterProvinces->find('list', array(
	// 			'keyField' => 'id',
	// 			'valueField' => ['country_name_th'],
	// 			'conditions' => array(
	// 				'State.countries_id' => $this->request['data']['id']
	// 			)
	// 		));
	// 	}
	// 	header('Content-Type: application/json');
	// 	pr($states);die;
	// 	echo json_encode($states);
	// 	exit();
	// }

    #---------------------------------------------------------------------------------------------------

    #Signup
    public function createAccount()
    {
		$this->loadModel('UserPersonals');

        $users = $this->Users->newEntity();
		$user_personals = $this->UserPersonals->newEntity();
		
        if ($this->request->is('post')) {
			// $username_check = $this->MasterProvinces->find('all')->toArray();
			// pr($username_check);die;
			// pr($this->request->data);die;
			$today = Time::now();
			$dateNow = $today->i18nFormat('yyyy-MM-dd HH:mm:ss');
			$hasher = new DefaultPasswordHasher();
            $firstname = $this->request->data['firstname'];
            // $phone_no = $this->request->data['phone_no'];
            $lastname = $this->request->data['lastname'];
            $master_country_id = $this->request->data['master_country_id'];
            $master_province_id = $this->request->data['master_province_id'];
            $password = $this->request->data['password'];
			$confirm_password = $this->request->data['confirm_password'];
			$btn = $this->request->data['btn'];

			if(!empty($this->request->data['birthdate'])){
				$birthdate = explode("/", $this->request->data['birthdate']);
				$birthdate = $birthdate[2].'-'.$birthdate[1].'-'.$birthdate[0];
				$this->request->data['birthdate'] =  $birthdate;
			}else{
				$birthdate = '2000-10-10';
			}
			
			$this->request->data['password'] = $hasher->hash($password);
            $users['created_by'] = 0;
            $users['is_used'] = true;
			$users['created'] = $dateNow;
			$users['dynamic_key'] = 'dynamic_key'; 

            // $users['point'] = 0;
			$users['dynamic_key_expiry'] = date('Y-m-d',strtotime('+3 day'));
			$users['token'] = Security::hash($this->request->data['username'].date('Y-m-d h:i:s'), 'md5', true);
			$users['token_expiry'] = date('Y-m-d',strtotime('+3 day'));
			// $users['modified_by'] = $modified_by;
			$digits = 4;
			$users['pin_code'] = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

			if(!empty($this->request->data['accept'])){

				$username_check = $this->Users->find('all',[
					'conditions' => [
						'Users.username' => $this->request->data['username']
					]
				])->toArray();
				
				$email_check = $this->UserPersonals->find('all',[
					'conditions' => [
						'UserPersonals.email' => $this->request->data['email']
					]
				])->toArray();
				
				if((empty($username_check))&&(empty($email_check))){
					$users = $this->Users->patchEntity($users, $this->request->getData());
					// pr($users);die;

//------------------------------  ส่งอีเมล์  -----------------------------------------------------					
					// $data_notification = [];
					// $data_notification['email'] = $this->request->data['email'];
					// $data_notification['pin_code'] = $users['pin_code'];
					// $this->notification($data_notification);
//----------------------------------------------------------------------------------------------
					$this->Users->save($users);
					$user_personals['master_country_id'] = $master_country_id;
					$user_personals['master_province_id'] = $master_province_id;
					$user_personals['user_id'] = $users['id'];
					$user_personals['firstname_th'] = $firstname;
					$user_personals['lastname_th'] = $lastname;
					$user_personals['created_by'] = 1;
					$user_personals['created'] = $dateNow;
					$user_personals = $this->UserPersonals->patchEntity($user_personals, $this->request->getData());
					$this->UserPersonals->save($user_personals);

					// $this->Flash->success(__('The register success.'));
					return $this->redirect(['controller' => 'Users', 'action' => 'pinCode/'.$users['token']]);
					return $this->redirect(['action' => 'signin']);		
				}
				$this->Flash->error(__('Username or Email Address already used by others.'));
				return $this->redirect(['action' => 'signup']);
			}else if(empty($this->request->data['accept'])){
				$this->Flash->error(__('please accept'));
				return $this->redirect(['action' => 'signup']);
			}
            $this->Flash->error(__('The article could not be saved. Please, try again.'));
        }
	}
	
	
	public function notification($data = null)
    {
     if(!empty($data)){
      	$verify_code = $data['pin_code'];
		$from_email = ['support@pakgon.com' => 'Support'];
		$to_emails = [$data['email']];

				$email = new Email();
				$email->transport('gmail');

				try {
					$email->template('notification_signup', 'connect');
					$email->from($from_email);
					$email->to($to_emails);
					$email->subject('Signup Connect Verify');
					$email->emailFormat('html');
					$email->viewVars(compact('verify_code'));
					#$email->send($message);
					$email->send();

				} catch (Exception $e) {
					echo 'Exception : ',  $e->getMessage(), "\n";
				}
		
				#$this->httpStatusCode = 200;
				#$this->apiResponse['message'] = 'Signup Connect Completed!!';
		
		}
 
    }
	
    #---------------------------------------------------------------------------------------------------    
    
    function validateAccount($data = null)
    {
    
    	$error = [];
	
	if(!empty($error)){	
    		$this->set('error',$error);
		return false;
	}else{
		return true;
	}
    	
    }

    // public function notification()
    // {
    //     $this->viewBuilder()->layout('blank');
    // }
    
    #Verify Pin Code
    public function pinCode($token=null)    
    {
    
    	if(empty($token)) die;
	
        $this->viewBuilder()->layout('blank');

        $data = $this->request->data();
        if(!empty($data)){
				
		$api_core_verify_pin_code = Configure::read('Config.apiCore.verifyPinCode');
		$http = new Client();
		#$response = json_decode($http->post($api_core_verify_pin_code,$data)->body(),'_full');
		$response = $http->post($api_core_verify_pin_code,$data)->body();
		$response = json_decode($response,'_full');			

		if(!empty($response)){
			if(trim($response['status']) == 'Success'){						
				$this->Flash->success(__('Verify Completed.'));
				return $this->redirect(['controller' => 'Users', 'action' => 'signin']);								
			}else{					
				$this->Flash->error(__('Pin Code Invalid'));
				return $this->redirect(['controller' => 'Users', 'action' => 'pinCode/'.$token]);	
			}
		}
		}
		$this->set(array('token' => $token, '_serialize' => array('token'))); 
    }
    
    #---------------------------------------------------------------------------------------------------        
    
    #Forgot Password
    public function forgotPassword()
    {
            $this->viewBuilder()->layout('blank');

        $data = $this->request->data();
	#$data['data']['ip'] = $this->request->clientIp();

        if(!empty($data)){
		if(!empty($data['data']['username'])){
			$data['data']['ip'] = $this->request->clientIp();#prr($data);
				
			$api_core_forgotPassword = Configure::read('Config.apiCore.forgotPassword');
			$http = new Client();
			$response = $http->post($api_core_forgotPassword,$data['data'])->body();
			$response = json_decode($response,'_full');#debug($response);

			if(!empty($response)){
				if(trim($response['status']) == 'Success'){
                                        $this->Flash->success(__('Completed.'));
					return $this->redirect(['controller' => 'Users', 'action' => 'signin']);
				}else{
					$this->Flash->error(__('Forgot Password Fail'));
					return $this->redirect(['controller' => 'Users', 'action' => 'forgotPassword']);	
				}
			}else{
				$this->Flash->error(__('Forgot Password Fail'));
				return $this->redirect(['controller' => 'Users', 'action' => 'forgotPassword']);			
			}
				
		}else{
			$this->Flash->error(__('Data Empty'));
			return $this->redirect(['controller' => 'Users', 'action' => 'forgotPassword']);		
		}				
        }    
    }

    #---------------------------------------------------------------------------------------------------    

    #Change Password
    // public function changePassword()
    // {	
	// 	$users = $this->Users->newEntity();
    //     // $this->viewBuilder()->layout('blank');

	// 	$data = $this->request->data();#debug($data);exit();
	// 	// pr($data);die;
    //     // if(!empty($data)){
	// 	// if($this->validateAccount($data)){
	// 	if ($this->request->is('post')) {

	// 		$data['ip'] = $this->request->clientIp();#debug($data);exit();
	// 		$hasher = new DefaultPasswordHasher();			
	// 		$data['id'] = 59445;
			
			
	// 		$users = $this->Users->find('all',[
	// 			'conditions'=>[
	// 				'Users.id' => $data['id'],
	// 			]
	// 		])->first();
	// 		// pr($data['password']);
	// 		// pr($users['password']);die;
	// 		// $sss = check( $data['password'] , $users['password'] );
	// 		$user['password'] = $hasher->hash($data['password']);
	// 		// pr($user);die;
			
	// 		$users = $this->Users->patchEntity($users, $this->request->getData());
	// 		$this->Users->save($users);
	// 		$this->Flash->error(__('Change Password Success'));
	// 		// return $this->redirect(['controller' => 'Users', 'action' => 'signin']);
	// 		// $response = json_decode($users['password'],'_full');		
	// 		// pr($response);die;	
	// 		#debug($response);exit();
	// 		// pr($data);die;

	// 		// if(!empty($response)){
	// 		// // pr($response);die;
				
	// 		// 	#if(trim($response['status']) == 'Success' && !empty($response['result']['type'])){
	// 		// 	if(trim($response['status']) == 'Success'){
	// 		// 		#$this->response->withHeader('Authorization', 'Bearer '.$response['result']['token']);
	// 		// 		#$url = $this->Url->build(['controller' => 'Homes', 'action' => 'index'], true);
	// 		// 		$url = Router::url(['controller' => 'Users', 'action' => 'signup'], true);
	// 		// 		#echo "<script>Login.onLogin('".$response['result']['token']."','".$url."');</script>";die;
						
	// 		// 		$this->Flash->success(__('change Password completed.'));
	// 		// 		return $this->redirect(['controller' => 'Users', 'action' => 'signin']);								
	// 		// 	}else{
	// 		// 		$this->Flash->error(__('change Password Fail'));
	// 		// 		return $this->redirect(['controller' => 'Users', 'action' => 'signup']);	
	// 		// 	}
	// 		// }
				
	// 	}else{
	// 		$this->Flash->error(__('Data Empty'));
	// 		return $this->redirect(['controller' => 'Users', 'action' => 'signin']);		
	// 	}				
    //     // }    
    // }
	
	public function changePassword()
    {
        // $users = $this->Users->newEntity();
		
        if ($this->request->is('post')) {
			$hasher = new DefaultPasswordHasher();
			$confirm_password = $this->request->data['confirm_password'];
			$this->request->data['password'] = $hasher->hash($this->request->data['password']);
			$userid = 59445;
			$users = $this->Users->find('all',[
				'conditions' => [
					'Users.id' => $userid
				]
			])->first();
			// if($this->request->data['old']!=$users['password'])
			$users = $this->Users->patchEntity($users, $this->request->getData());
			$this->Users->save($users);
			pr($users);die;
			// return $this->redirect(['controller' => 'Users', 'action' => 'pinCode/'.$users['token']]);
			return $this->redirect(['action' => 'signin']);		
				// }
				// $this->Flash->error(__('Username or Email Address already used by others.'));
				// return $this->redirect(['action' => 'signup']);
			
            // $this->Flash->error(__('The article could not be saved. Please, try again.'));
        }
	}
    #---------------------------------------------------------------------------------------------------        
    
    public function signout()
    {
	$this->checkToken();
    
	}
	
	public function getProvince() {

		$this->autoRender = false;
		$this->loadModel('MasterProvinces');
		$states = array();
	 $id = $this->request->data('id');
	  $states = $this->MasterProvinces->find('list', array(
				'keyField' => 'id',
				'valueField' => 'province_name_th',
	   'conditions' => array(
		'master_country_id' =>$id
	   )
			))->toArray();
		$arr = array();
	   if(!empty($states)){
	 echo '<option value=""> ---Select--- </option>';
	 foreach($states as $key => $val){
	  echo '<option value="' . $key . '">' . $val. '</option>';
	 }
	}else{
	 return false;
	}
   }
	 
}
