<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link      http://cakephp.org CakePHP(tm) Project
 * @since     0.2.9
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace App\Controller;

use Cake\Core\Configure;
use Cake\View\Helper\HtmlHelper;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\Routing\Router;
use Cake\Auth\DefaultPasswordHasher;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;

use Cake\View\Helper\PaginatorHelper;
use Cake\I18n\Time;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

require_once('jwt/autoload.php');


/**
 * Static content controller
 *
 * This controller will render views from Template/Pages/
 *
 * @link http://book.cakephp.org/3.0/en/controllers/pages-controller.html
 */

$req_dump = '-------------------------'.date('Y-m-d H:i:s').'---------------------';
$inputJSON = file_get_contents('php://input');
if($inputJSON){
	$input = json_decode($inputJSON, TRUE);
$req_dump .= print_r($input, TRUE);
}
$req_dump .= print_r($_POST, TRUE);
$req_dump .= print_r($_FILES, TRUE);
$fp = fopen('request.log', 'a');
fwrite($fp, $req_dump);
fclose($fp);

class ServicesController extends AppController
{
    var $profilePath 		= 'https://demo4.evirtualservices.net/jbgapp/img/uploads/users/';
	var $catPath 			= 'https://demo4.evirtualservices.net/jbgapp/img/uploads/category/';
	var $baseUrl 			= 'https://demo4.evirtualservices.net/jbgapp/';
	
    

	function index(){
		//header("Content-type:application/json");
		Configure::write('Session.checkAgent', false);
		$response=array();
		//$this->layout='';
		//print_r($this->request->header('token')); die('ggggg');
		if($this->request->data('action') !=''){
			$this->request->data=$this->request->data;
		}else{
			$inputJSON = file_get_contents('php://input');
			if($inputJSON){
				$this->request->data = json_decode($inputJSON, TRUE);
			}
		}
		if(@$this->request->data['action']){
			$skipArray = ['registration','bannerlist'];
			$token = $this->request->header('token');
			$auth = '';
			if(@$token){
				$getres = $this->decodetoken($token);
				$auth =  $getres['status'];
			}
			//echo $auth."<br>".$token; die;
			if(in_array($this->request->data['action'], $skipArray) || $auth == 200){
				$action = trim($this->request->data['action']);
					//echo $action;
					//pr($this->request->data); die;
				if(!empty($action)){
						$response = $this->$action();
				}else{
					$response['status'] = 'Fails';
					$response['msg'] = 'Invalid action key';
					$response['currentTime date'] = date('Y-m-d H:i:s');
					$response['milisecond'] = time();
				}
			}else{
				$response['status'] = 'Fails';
				$response['msg'] = 'You are not authorize to access the API';
			}
		}else{
			$response['status'] = 'Fails';
			$response['msg'] = 'Invalid action key';
		}
		echo json_encode($response); die;
	}

	function decodetoken($token=null){
		$jwt = ($token) ? $token : @$this->request->data['token'];
		$key  = '68V0zWFrS72GbpPreidkQFLfj4v9m3Ti+DXc8OB0gcM=';
		//$secret_Key  = '68V0zWFrS72GbpPreidkQFLfj4v9m3Ti+DXc8OB0gcM=';
		//$body = JWT::decode($tokenData, new Key($secret_Key, 'HS512'));

		try {

			//$decoded = JWT::decode($jwt, $key, array('HS256'));
			$decodedata = JWT::decode($jwt, new Key($key, 'HS512'));
			//echo "<pre>";
			//pr($decodedata); die;
			//$refresh_token=$decoded->data->refresh_token;
			//die('!!!!!!!23432!!!!!!!!!!!');
			$decoded['status'] = 200;
			$decoded['data'] = $decodedata;
			}
			
			catch (\Exception $e){
			   //die('!!!!!!!!!!!!!!!!!!');
				$decoded['status'] = 'Fails';
				$decoded['msg'] = $e->getMessage();
			}
		//echo json_encode($decoded); die;
		return $decoded;
	}
	function decodejwt($token=null){
		$jwt = ($token) ? $token : @$this->request->data['token'];
		$key  = '68V0zWFrS72GbpPreidkQFLfj4v9m3Ti+DXc8OB0gcM=';
		//$secret_Key  = '68V0zWFrS72GbpPreidkQFLfj4v9m3Ti+DXc8OB0gcM=';
		//$body = JWT::decode($tokenData, new Key($secret_Key, 'HS512'));

		try {
			//$decoded = JWT::decode($jwt, $key, array('HS256'));
			$decodedata = JWT::decode($jwt, new Key($key, 'HS512'));
			//echo "<pre>";
			pr($decodedata); die;
			//$refresh_token=$decoded->data->refresh_token;
			//die('!!!!!!!23432!!!!!!!!!!!');
			$decoded['status'] = 200;
			$decoded['data'] = $decodedata;
			}
			
			catch (\Exception $e){
			   //die('!!!!!!!!!!!!!!!!!!');
				$decoded['status'] = 'Fails';
				$decoded['msg'] = $e->getMessage();
			}
		echo "<pre>"; print_r($decoded); die;
		return $decoded;
	}
	function encodejwtreturn($data=NULL){
		$secret_Key  = '68V0zWFrS72GbpPreidkQFLfj4v9m3Ti+DXc8OB0gcM=';
		$date   = time();
		$expire_at     = $date + 1000;      // Add 1 seconds = 60
		$domainName = "evirtualservices.com";
		$body   = $this->request->data; // Retrieved from filtered POST data
		$request_data = [
			'iat'  => $date,         // Issued at: time when the token was generated
			'iss'  => $domainName,  // Issuer
			'nbf'  => $date,         // Not before
			'exp'  => $expire_at,    // Expire
		];
		
		$jwt = JWT::encode(
			$request_data,
			$secret_Key,
			'HS512'
		);
		return $jwt;
		//die;
	}
	function encodejwt(){
		$secret_Key  = '68V0zWFrS72GbpPreidkQFLfj4v9m3Ti+DXc8OB0gcM=';
		$date   = time();
		$expire_at = $date + 100;      // Add 60 seconds
		$domainName = "EVS";
		$body   = $this->request->data;                                           // Retrieved from filtered POST data
		$request_data = [
			'iat'  => $date,         // Issued at: time when the token was generated
			'iss'  => $domainName,  // Issuer
			'nbf'  => $date,         // Not before
			'exp'  => $expire_at,    // Expire
		];
		
		echo $jwt = JWT::encode(
			$request_data,
			$secret_Key,
			'HS512'
		);
		die;
	}

	function checkjwt(){
		$secret_Key  = '68V0zWFrS72GbpPreidkQFLfj4v9m3Ti+DXc8OB0gcM=';
		$date   = time();
		$expire_at     = $date + 6;      // Add 60 seconds
		$domainName = "evirtualservices.comn";
		$username   = "raushan";                                           // Retrieved from filtered POST data
		$request_data = [
			'iat'  => $date,         // Issued at: time when the token was generated
			'iss'  => $domainName,                   // Issuer
			'nbf'  => $date,         // Not before
			'exp'  => $expire_at,                    // Expire
			'userName' => $username,                 // User name
		];
		
		echo $jwt = JWT::encode(
			$request_data,
			$secret_Key,
			'HS512'
		);
		echo "<br>";
		
		//$secret_Key  = '68V0zWFrS72GbpPreidkQFLfj4v9m3Ti+DXc8OB0gcM=';
		$token = JWT::decode($jwt, new Key($secret_Key, 'HS512'));
		echo "<pre>";
		print_r($token);
		die;
	}


	
	function bannerlist($user_id=NULL){
		$this->loadModel('Users');
		$this->loadModel('Categories');
		$userId = ($user_id) ? $user_id : $this->request->data('userId');
		$pageNo = ($this->request->data('pageNo')) ? $this->request->data('pageNo') : '1';
		
		$condition[] = ['Categories.status' => 1];
		$userservices =array();    
		$userservices = $this->Categories->find('all')->where($condition);
		$Darray = array();
		$i=0;
		//echo "<pre>"; print_r($userservices); die;
		foreach($userservices as $userD){
			$Darray[$i]['bannerId'] = ($userD->id) ? $userD->id : '';
			$Darray[$i]['name'] 	= ($userD->name) ? $userD->name : '';
			$Darray[$i]['link'] 	= ($userD->link) ? $userD->link : '';
			$Darray[$i]['description'] 	= ($userD->description) ? $userD->description : '';
			$Darray[$i]['image'] 	= ($userD->image) ? $this->catPath.$userD->image : '';
			$Darray[$i]['created'] 	= ($userD->created) ? date('m-d-Y H:i:s', strtotime($userD->created)) : '';
			$i++;
		}
		$response['status'] = 'success';
		$response['data'] = $Darray;

		return $response;
	}

	
	function registration(){
		$this->loadModel('Users');
		if($this->request->data('email') !='' && $this->request->data('fullName') !='' && $this->request->data('contactNumber') !=''){
			$this->loadModel('Users');
			$usr = $this->Users->find()->where(['OR'=>[['Users.email' => $this->request->data('email')],['Users.contactNumber' => $this->request->data('contactNumber')]]])->first();
			if(!empty($usr)){
				// $usr = $this->Users->patchEntity($usr, $this->request->data, ['validate' => false]);
				// $this->Users->save($usr);
				$response['status'] = 'Fails';
				$response['msg'] = 'Email or Phone number is already registered.';
			}else{
				$this->request->data['password'] = '123456';
				$this->request->data['email'] = str_replace(' ', '', $this->request->data('email'));
				$users = $this->Users->newEntity();
				$users = $this->Users->patchEntity($users, $this->request->data, ['validate' => false]);
				$users['created'] 	= date('Y-m-d H:i:s');
				$users['username'] 	= $this->request->data('email');
				$users['status'] 	= '1';
				$users['role'] 	= 'Member';
				
				if ($this->Users->save($users)) {
					// $dd = $this->profile($users->id);
					// $response['data'] = $dd['data'];
					$response['status'] = 'success';
					$response['msg'] = 'Registration successfully';
				}
			}
		}else{
			$response['status'] = 'Fails';
			$response['msg'] = 'Email, contactNumber,fullName and password required';
		}
		return $response;
	}
	


	
}
