<?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;
use Cake\Auth\AbstractPasswordHasher;

class UsersController extends AppController {

    /**
     * 
     * Function initialize make for automatically trigger when contructure
     */
    public function initialize() {
        parent::initialize();

       // $this->Auth->allow(['signin', 'signout', 'signup', 'verify', 'forgotPassword', 'createAccount', 'pinCode', 'pinCodepassword', 'changeForgotpassword']);

        $this->Auth->allow(['signin', 'signout', 'signup', 'verify','forgotPassword','createAccount','pinCode','pinCodepassword','registersendpin','forgotsendpin','changeForgotpassword']);

    }

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

    /**
     * 
     * Function signin / login make for user authentication
     * @author  sarawutt.b
     * @since   20108/05/24 10:49:20
     * @license Pakgon
     * @return  void
     */
    public function signin() {
        $this->viewBuilder()->layout('blank');
    }

    #Signin

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

        if ($this->request->is('post')) {
            $data = $this->request->getData();
            if (!empty($data)) {
                $data['data']['ip'] = $this->request->clientIp();
                $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');

                if (!empty($response)) {
                    if (strtolower(trim($response['status'])) == 'success') {
                        $response['result']['user']['id'] = $response['result']['user']['user_id'];
                        $this->Auth->setUser($response['result']['user']);
                        //$url = Router::url(['controller' => 'Homes', 'action' => 'index'], true);
                        // Before chan logic to OAUTH
                        // echo "<script>setTimeout(function(){Login.onLogin('" . $response['result']['token'] . "','" . $url . "','" . $response['result']['topic'] . "')},1000);</script>";
                        $statusCode = '200';
                        // echo "<script type='text/javascript'>setTimeout(function(){Login.onLogin('" . $statusCode . "','" . $this->_redirectApplicationURL . "','" . $response['result']['topic'] . "')},1000);</script>";
                        $RedirectApplicationURL = Configure::read('RedirectApplicationURL');
                        $topic = $response['result']['topic'];
                        $token = $response['result']['token'];
                        $this->set(compact('statusCode', 'RedirectApplicationURL', 'topic', 'token'));

                        #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);
                        #------------------------------------------------------------------						
                        //$this->redirect($this->_redirectApplicationURL);
                        //header('Location: ' . $this->_redirectApplicationURL);
                        //return $this->redirect($redirectApplicationURL);
                    } 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']);
            }
        }
    }

    /**
     * 
     * Function mobile re-authorized use automatically by mobile application
     * @author  sarawutt.b
     * @return  void
     */
    public function reautorize() {
        $this->viewBuilder()->layout(false);
        $reauthorizeAPI = Configure::read('Config.apiCore.reauthorize');
        $http = new Client();
        $data['data']['username'] = 'pakgon.demo';
        $data['data']['password'] = 'deio$5679@qETY';
        $data['data']['ip'] = $this->request->clientIp();
        $response = $http->post(
                        $reauthorizeAPI, $data['data'], ['headers' => [
                        'Authorization' => $this->request->getHeaderLine('Authorization'),
                        'Accept-Language' => $this->request->getHeaderLine('Accept-Language')
            ]])->body();
        $response = json_decode($response, true);
        if (!empty($response['result']['user'])) {
            $response['result']['user']['id'] = $response['result']['user']['user_id'];
            $this->Auth->setUser($response['result']['user']);
            return $this->redirect(Configure::read('RedirectApplicationURL'));
        } else {
            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');
    }

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

    #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'] = false;
            $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) {



        $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')));
    }

    /**
     * 
     * Function user forgot password
     * @return void
     */
    public function forgotPassword() {
        $this->viewBuilder()->layout('blank');
        $this->loadModel('UserPersonals');
        if ($this->request->is('post')) {
            $hasher = new DefaultPasswordHasher();
            $email = $this->request->data['email'];
            $user_personals = $this->UserPersonals->find('all', [
                        'conditions' => [
                            'UserPersonals.email' => $email
                        ]
                    ])->first();
            if (!empty($user_personals)) {

                $users = $this->Users->find('all', [
                            'conditions' => [
                                'Users.id' => $user_personals['user_id']
                            ]
                        ])->first();
                $digits = 4;
                $users['pin_pass'] = str_pad(rand(0, pow(10, $digits) - 1), $digits, '0', STR_PAD_LEFT);
                $token = $users['token'];

                //--------------------ตัวส่ง Email ---------------------------------------------------------
                //pr($user_personals);die;
                $data_notification = [];
                $data_notification['email'] = $this->request->data['email'];
                $data_notification['pin_code'] = $users['pin_pass'];
                $this->notification($data_notification);
                //----------------------------------------------------------------------------------------
                $this->Users->save($users);

                $this->Flash->success(__('send password to email success'));
                return $this->redirect(['action' => 'pinCodepassword/' . $token]);
            } else {
                $this->Flash->error(__('Invalid Email.'));
                return $this->redirect(['action' => 'forgot-password']);
            }
        }
    }

	public function pinCodepassword($token=null)    
    {
		$this->viewBuilder()->layout('blank');
		$users = $this->Users->find('all',[
			'conditions'=>[
				'Users.token'=>$token
			]
		])->first();

		if($this->request->is('post')){
			$data = $this->request->data();	
			$data['pin_pass'] = $data['pin_code_1'].$data['pin_code_2'].$data['pin_code_3'].$data['pin_code_4'];
			if($data['pin_pass']==$users['pin_pass']){
				$this->Flash->success(__('Pin Completed.'));
				return $this->redirect(['controller' => 'Users', 'action' => 'changeForgotpassword/'.$token]);	
			}
			$this->Flash->error(__('Pin Invalid'));
			return $this->redirect(['controller' => 'Users', 'action' => 'pinCodepassword/'.$token]);
		}
		$this->set(array('token' => $token, '_serialize' => array('token'))); 
	}
	
	public function changePassword()
    {
    
    		$id = $this->Auth->user('id');
			$this->viewBuilder()->layout('blank');
			$users = $this->Users->get($id);
			if ($this->request->is('post')) {

			$hasher = new DefaultPasswordHasher();
			$password = $this->request->data['password'];
			$confirm_password = $this->request->data['confirm_password'];
			$oldpassword = $this->request->data['oldpassword'];
			$this->request->data['password'] = $hasher->hash($this->request->data['password']);			
			//------- เทียบ password ที่เข้ารหัส ---------------password_verify($password,hashed_password)---------------------------
			
			if (password_verify($oldpassword, $users['password'])) {
				$users = $this->Users->patchEntity($users, $this->request->getData());
				$this->Users->save($users);
				$this->Flash->success(__('You are now logged out.'));
				return $this->redirect(['action' => 'signout']);

			} else {
				$this->Flash->error(__('Invalid password.'));
				return $this->redirect(['action' => 'change-password']);
			}
		}
	}

	public function changeForgotpassword($token=null)
    {
			$this->viewBuilder()->layout('blank');
			$users = $this->Users->find('all',[
				'conditions' => [
					'Users.token' => $token
				]
			])->first();
			if ($this->request->is('post')) {
			$hasher = new DefaultPasswordHasher();
			$password = $this->request->data['password'];
			$confirm_password = $this->request->data['confirm_password'];
			$this->request->data['password'] = $hasher->hash($this->request->data['password']);			
			//------- เทียบ password ที่เข้ารหัส ---------------password_verify($password,hashed_password)---------------------------
				$users = $this->Users->patchEntity($users, $this->request->getData());
				$this->Users->save($users);
				$this->Flash->success(__('You are now logged out.'));
				return $this->redirect(['action' => 'signin']);
		}
		$this->set(array('token' => $token, '_serialize' => array('token'))); 
	}


  //      if ($this->request->is('post')) {
    //        $data = $this->request->data();
  //          $data['pin_pass'] = $data['pin_code_1'] . $data['pin_code_2'] . $data['pin_code_3'] . $data['pin_code_4'];
    //        if ($data['pin_pass'] == $users['pin_pass']) {
    //            $this->Flash->success(__('Pin Completed.'));
    //            return $this->redirect(['controller' => 'Users', 'action' => 'changeForgotpassword/' . $token]);
   //         }
   //         $this->Flash->error(__('Pin Invalid'));
   //         return $this->redirect(['controller' => 'Users', 'action' => 'pinCodepassword/' . $token]);
   //     }
  //      $this->set(array('token' => $token, '_serialize' => array('token')));
  //  }

    // public function changePassword($token = null) {

    //     $id = $this->Auth->user('id');
    //     $this->viewBuilder()->layout('blank');
    //     $users = $this->Users->get($id);
    //     if ($this->request->is('post')) {

    //         $hasher = new DefaultPasswordHasher();
    //         $password = $this->request->data['password'];
    //         $confirm_password = $this->request->data['confirm_password'];
    //         $oldpassword = $this->request->data['oldpassword'];
    //         $this->request->data['password'] = $hasher->hash($this->request->data['password']);
    //         //------- เทียบ password ที่เข้ารหัส ---------------password_verify($password,hashed_password)---------------------------


    //         if (password_verify($oldpassword, $users['password'])) {
    //             $users = $this->Users->patchEntity($users, $this->request->getData());
    //             $this->Users->save($users);
    //             $this->Flash->success(__('change password success'));

    //             $this->Flash->success(__('You are now logged out.'));
    //             return $this->redirect(['action' => 'signout']);
    //         } else {
    //             $this->Flash->error(__('Invalid password.'));
    //             return $this->redirect(['action' => 'change-password']);
    //         }
    //     }
    //     $this->set(array('token' => $token, '_serialize' => array('token')));
    // }

    // public function changeForgotpassword($token = null) {
    //     $this->viewBuilder()->layout('blank');
    //     $users = $this->Users->find('all', [
    //                 'conditions' => [
    //                     'Users.token' => $token
    //                 ]
    //             ])->first();
    //     if ($this->request->is('post')) {
    //         $hasher = new DefaultPasswordHasher();
    //         $password = $this->request->data['password'];
    //         //$confirm_password = $this->request->data['confirm_password'];
    //         $this->request->data['password'] = $hasher->hash($this->request->data['password']);
    //         //------- เทียบ password ที่เข้ารหัส ---------------password_verify($password,hashed_password)---------------------------
    //         $users = $this->Users->patchEntity($users, $this->request->getData());
    //         if ($this->Users->save($users)) {
    //             $this->Flash->success(__('change password success'));
    //             return $this->redirect(['action' => 'signin']);
    //         }
    //         $this->Flash->error(__('Invalid password.'));
    //         return $this->redirect(['action' => 'change_forgotpassword']);
    //     }
    //     $this->set(array('token' => $token, '_serialize' => array('token')));
    // }

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


	public function forgotsendpin($token=null) {
		$this->loadModel('UserPersonals');
		$users = $this->Users->find('all',[
			'conditions'=>[
				'Users.token'=>$token
			]
		])->first();
		$digits = 4;
		$users['pin_pass'] = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

		$user_personals = $this->UserPersonals->find('all',[
			'conditions'=>[
				'UserPersonals.user_id'=>$users['id']
			]
		])->first();
		//--------------------ตัวส่ง Email ---------------------------------------------------------
		 //pr($user_personals);die;
		$data_notification = [];
		$data_notification['email'] = $user_personals['email'];
		$data_notification['pin_code'] = $users['pin_pass'].'<br>'." Username: ".$users['username'];
		$this->notification($data_notification);
		//----------------------------------------------------------------------------------------
		if($this->Users->save($users)){
			$this->Flash->success(__('send pin success.'));
			return $this->redirect(['action' => 'pin_codepassword/'.$token]);
		}
		$this->Flash->success(__('send pin false.'));
		return $this->redirect(['action' => 'pin_codepassword/'.$token]);
    }
	
	public function registersendpin($token=null) {
		$this->loadModel('UserPersonals');
		$users = $this->Users->find('all',[
			'conditions'=>[
				'Users.token'=>$token
			]
		])->first();
		$digits = 4;
		$users['pin_pass'] = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

		$user_personals = $this->UserPersonals->find('all',[
			'conditions'=>[
				'UserPersonals.user_id'=>$users['id']
			]
		])->first();
		//--------------------ตัวส่ง Email ---------------------------------------------------------
		 //pr($user_personals);die;
		$data_notification = [];
		$data_notification['email'] = $user_personals['email'];
		$data_notification['pin_code'] = $users['pin_pass'].'<br>'." Username: ".$users['username'];
		$this->notification($data_notification);
		//----------------------------------------------------------------------------------------
		if($this->Users->save($users)){
			$this->Flash->success(__('send pin success.'));
			return $this->redirect(['action' => 'pin_code/'.$token]);
		}
		$this->Flash->success(__('send pin false.'));
		return $this->redirect(['action' => 'pin_code/'.$token]);
    }



    /**
     * 
     * Function user logout / signout
     * @author sarawutt.b
     * @since  2018/05/22 16:44:20
     * @license PAKGON
     * @return void
     */
    public function signout() {
        $http = new Client();
        $result = $http->delete(Configure::read('OAUTH2_PROVIDER.TOKEN_DETETE') . '/' . $this->Auth->user('id'))->body();
        $this->Flash->success(__('You are now logged out.'));
        return $this->redirect($this->Auth->logout());
    }

}
