<?php
namespace App\Controller;
use App\Controller\AppController;

use Cake\Core\Configure;
use Cake\Http\Client;
use Cake\Routing\Router; 

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->viewBuilder()->layout('blank');
    }

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

    #Signup
    public function createAccount()
    {
        $this->viewBuilder()->layout('blank');

        $data = $this->request->data();
	
        if(!empty($data)){
		if($this->validateAccount($data)){
			$data['data']['ip'] = $this->request->clientIp();#prr($data);
				
			$api_core_create_account = Configure::read('Config.apiCore.createAccount');
			$http = new Client();			
			$response = $http->post($api_core_create_account,$data)->body();#prd($response);
			$response = json_decode($response,'_full');
                        //debug($response);exit();
			if(!empty($response)){
				if(trim($response['status']) == 'Success'){
					$this->Flash->success(__('create Account completed.'));
					return $this->redirect(['controller' => 'Users', 'action' => 'pinCode/'.$response['result']['data']['token']]);
                                } elseif ($response['result']['message'] == 'Email Duplicate'){
                                        $this->Flash->error(__('Email Duplicate'));
					return $this->redirect(['controller' => 'Users', 'action' => 'signup']);
				}else{
					$this->Flash->error(__('create Account Fail'));
					return $this->redirect(['controller' => 'Users', 'action' => 'signup']);	
				}
			}
				
		}else{
			$this->Flash->error(__('Data Empty'));
			return $this->redirect(['controller' => 'Users', 'action' => 'signin']);		
		}				
        }
	die;
    }
    
    #---------------------------------------------------------------------------------------------------    
    
    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()
    {
        $this->viewBuilder()->layout('blank');

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

			if(!empty($response)){
				#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 signout()
    {
	$this->checkToken();
    
    }    
}
