<?php
/**
 * Static content controller.
 *
 * This file will render views from views/pages/
 *
 * 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
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

use Cake\Network\Email\Email;
use Cake\ORM\TableRegistry;

App::uses('AppController', 'Controller');


/**
 * Static content controller
 *
 * Override this controller by placing a copy in controllers directory of an application
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers/pages-controller.html
 */
class PagesController extends AppController {

/**
 * This controller does not use a model
 *
 * @var array
 */
	public $uses = array('Comment','GroupExpense','FamilyExpense','Meal','LogAppVisitors','UserGroup','UserSubscription');
	
	var $helpers = array('Html', 'Form');
	
	public $components = array('Captcha','MobileDetect','Permission');

    private $group_status = ['Active' => 1,'Archived' => 2];
	
	public function beforeRender() {
		parent::beforeRender();
	 
		$this->layout = 'visitor'; 
		
		if($this->Session->check("mobile_app_layout")){
			$this->layout = 'mobile';
			$this->Session->delete("mobile_app_layout");
				
		}
	}
	
	
	function index()
	{
	 
	}
	
	public function termscondition(){
	 
		
	}
	
	public function privacypolicy(){
	    
	    
	}
	
	public function faq(){
	 
		
	}
	
	public function news(){
	 
		
	}
	
	public function downloadAndroidApp(){
		
		$this->render('download_android_app');
	
	}
	
	
	public function feedback()
    {
        

        if ($this->request->is('Post') && $this->request->data["Comment"]) {

            $error = "";
            //validate email and comment
            $email = trim($this->request->data['Comment']["feedbackemail"]);
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $error = "EMAIL_ERR";
                $this->set('email_error', "Email is invalid");
            }

            $comment = trim($this->request->data['Comment']["comment"]);

            if (empty($comment)) {
                $error = "COMMENT_ERR";
                $this->set("comment_error", __("LBL_WRITE_IN_COMMENT_BOX"));
            }

            if (isset($_COOKIE['ecc']) && $_COOKIE['ecc'] !== $this->request->data['captcha']){
                $message = '<div class="alert alert-danger alert-dismissible" role="alert">' . 'Captcha doesn\'t not match' . '</div>';
                $this->Session->write('system.message', $message);
                $error ='captcha';
            }else{
                $this->Session->write('system.message','');
            }

//            $responseData = $this->getCaptchaResponse($this->request->data['captcha-response']);
//            if($responseData->success){
            if( $error == "" ) {
                $captcha = $this->Session->read('captcha_code');
                if (strlen($captcha) > 0 && ($captcha == $this->request->data['Comment']['captcha'])) {
                    $this->Session->delete('captcha_code');
                    //if ( $error == "" && strlen($captcha)> 0 && ($captcha == $this->request->data['Comment']['captcha']) ){
                    //insert into comment table
                    $this->request->data['Comment']["ip"] = $this->getClientIp();
                    $this->request->data['Comment']["create_date"] = date("Y-m-d h:i:s");
                    $result = $this->Comment->createFeedback($this->request->data['Comment']);
                    if (!empty($result)) {
                        $this->set("error", __("LBL_DATA_SAVING_FAILED"));
                    } else {
                        $this->request->data["Comment"]["captcha"] = "";
                        $this->set("success", "Message  Sent!");

                        $params = array();
                        $params["email"] = trim($this->request->data['Comment']["feedbackemail"]);
                        $trimed_comment = trim($this->request->data['Comment']["comment"]);
                        $params["comment"] = nl2br($trimed_comment);
                        $params["ip"] = $this->request->data['Comment']["ip"];
                        $this->sendEmail($params);
                    }
                } else {
                    $this->request->data["Comment"]["captcha"] = "";
                    $this->set("captcha_error", __("LBL_CAPTCHA_ERROR"));
                }
            }
        } else {
            $token = $this->getSecretKey(5);
            $this->set("captcha",$token);
            $this->Session->write("captcha_code",$token);
            $this->Session->write('system.message', '');
        }

	}

    private function getSecretKey($length = 10){
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }
	
	private function sendEmail($params){ 
		
			$data = array();
			$data["email_from"] =  $params["email"];
			$data["comment"] = $params["comment"];
			$data["ip"] = $params["ip"];
			
			$default = array(
					'host' => Configure::read('expensecount.email.smtp.host'),
					'port' => 587,
					'auth' => 'plain',
					'username' => Configure::read('expensecount.email.smtp.username'),
					'password' => Configure::read('expensecount.email.smtp.password'),
					'tsl' => false,
					'transport' => 'Smtp',
					'from' => array(Configure::read('expensecount.email.smtp.from') => 'ExpenseCount'),
					'returnPath' => Configure::read('expensecount.email.smtp.from'),
					'layout' => false,
					'emailFormat' => 'html',
					//'template' => 'only_text',
					'charset' => 'utf-8',
					'headerCharset' => 'utf-8',
			);
				
			App::uses('CakeEmail', 'Network/Email');
				
			//echo $Email->
			$Email = new CakeEmail($default);
			$Email->to(array(SUPPORT_EMAIL,"asoftbd07@gmail.com"));
			$Email->emailFormat('html');
			$Email->template('feedback',null)->viewVars( array('data' => $data));
			$Email->subject('ExpenseCount-Feedback on "'.date("Y-m-d h:i:s").'" ');
					$Email->replyTo($data["email_from"]);
			$Email->from(array(Configure::read('expensecount.email.smtp.from') => "ExpenseCount.com"));
			//$Email->smtpOptions =  $default;
			$Email->delivery = 'Smtp';
			$Email->send(); 
	}
	
	public function aboutus(){/*   
		$data = array();
		$data["email"] =  "rajibcuetcse@gmail.com";
		$data["expense_title"] = "PAGE CONTROLLER";
		$data["unique_url"] = "UTF34234";
			
	 
		$default = array(
				'host' => Configure::read('expensecount.email.smtp.host'),
				'port' => 25,
				'auth' => 'plain',
				'username' => Configure::read('expensecount.email.smtp.username'),
				'password' => Configure::read('expensecount.email.smtp.password'),
				'tsl' => false,
				'transport' => 'smtp',
				'from' => array(Configure::read('expensecount.email.smtp.from') => 'ExpenseCount'),
				'returnPath' => Configure::read('expensecount.email.smtp.from'),
				'layout' => false,
				'emailFormat' => 'html',
			//	'template' => 'email',
				'charset' => 'utf-8',
				'headerCharset' => 'utf-8',
		);
		
		 
		
	 
		App::uses('CakeEmail', 'Network/Email');
			//echo $Email->			
			$Email = new CakeEmail();
	        $Email->to($data["email"]);
	        $Email->emailFormat('html');
	        $Email->template('email',null)->viewVars( array('data' => $data));
	        $Email->subject('ExpenseCount "'.$data["expense_title"].'" ');
	        $Email->replyTo(Configure::read('expensecount.email.smtp.from'));
	        $Email->from(array(Configure::read('expensecount.email.smtp.from') => "ExpenseCount"));
	        $Email->smtpOptions =  $default;
	        $Email->delivery = 'smtp';
			$Email->send();
		  
			
			exit;
		
	  */}
	
	public function mobileApps($expense_type="")
    {

	   if($this->request->is('post')){

           $expense_type = $this->request->data('expense_type');
           $app_type = $this->request->data('app_type');
           $this->saveAppVisitorsInfo($expense_type,$app_type);

           if($expense_type == 1 && $app_type == 1){
               return $this->redirect("https://play.google.com/store/apps/details?id=com.expensecount.groupExpense");
           }elseif ($expense_type == 1 && $app_type == 2){
               return $this->redirect("https://itunes.apple.com/us/app/groupexpense/id1150902475?mt=8");
           }elseif ($expense_type == 2 && $app_type == 1){
               return $this->redirect("https://play.google.com/store/apps/details?id=com.expensecount.messExpense");
           }elseif ($expense_type == 2 && $app_type == 2){
               return $this->redirect("https://itunes.apple.com/us/app/messexpense/id1179871989?mt=8");
           }elseif ($expense_type == 3 && $app_type == 1){
               return $this->redirect("https://play.google.com/store/apps/details?id=com.expensecount.familyExpense");
           }elseif ($expense_type == 3 && $app_type == 2){
               return $this->redirect("https://itunes.apple.com/us/app/familyexpense/id1193007779?mt=8");
           }



       }

		$detect = new MobileDetectComponent();
		if($this->Session->check("mobile_app_layout")){			 
			$this->Session->delete("mobile_app_layout");
		
		}
		
		
		if ($detect->isAndroid()) {
			$this->Session->write("mobile_app_layout","true");
			$this->set("device","android");
		} else if($detect->isIphone()){
			$this->Session->write("mobile_app_layout","true");
			$this->set("device","iphone");
		} else if($detect->isWindows()){
			$this->Session->write("mobile_app_layout","true");
			$this->set("device","windows");
			 
		} else {
			$this->set("device","pc");
		}
		
		
		
		$this->set("expenseType",$expense_type);
		
	}


	private function saveAppVisitorsInfo($expense_type,$app_type){
	    $result = false;
        $inputData["expense_type"] = $expense_type;
        $inputData["app_type"] = $app_type;
        $inputData["visiting_date"] = $this->getSystemCurrentTimeStamp();
        $inputData["ip"] = $this->getClientIp();
        $inputData["device_info"] = $this->getUserAgent();
        //pr($inputData);exit;
       $result =  $this->LogAppVisitors->insertLogAppVisitors($inputData);

       return $result;
    }

	
	public function facebookApp(){
		
	}
	
	 

	public function get_captcha()
	{
		$this->autoRender = false;
		App::import('Component','Captcha');
	
		//generate random charcters for captcha
		$random = mt_rand(100, 99999);
			
		//save characters in session
		$this->Session->write('captcha_code', $random);
	
		$settings = array(
				'characters' => $random,
				'winHeight' => 70,         // captcha image height
				'winWidth' => 220,		   // captcha image width
				'fontSize' => 25,          // captcha image characters fontsize
				'fontPath' => WWW_ROOT.'tahomabd.ttf',    // captcha image font
				'noiseColor' => '#ccc',
				'bgColor' => '#fff',
				'noiseLevel' => '100',
				'textColor' => '#000'
		);
	
		$img = $this->Captcha->ShowImage($settings);
		echo $img;
	}
	
	public function convertDateToString(){
		
		/* $this->loadModel('GroupExpense'); 
		$this->loadModel('FamilyExpense');
		$this->loadModel('Meal');
		 
		  $result = $this->GroupExpense->find('all', array(
				'conditions' => array('expense_date_new' => null),
				'limit' => 500
				
		));
		   

		foreach($result as $key=>$value){ 
			$id = $value["GroupExpense"]["id"];
			$oldDate = $value["GroupExpense"]["expense_date"];
			
			$data = array();
			 
			$data["id"] = $id;
			
			$newDateStr = date("d-M-Y",$oldDate);
			$newDateStrArray = explode("-",$newDateStr);
			 
			$newDateStrArray[1] = ucfirst($newDateStrArray[1]);
		 
			$newDateStr = implode("-",$newDateStrArray);
			
			$data["expense_date_new"] = "'".$newDateStr."'";
			//$data["expense_date"] = 0;
			
			
			$this->GroupExpense->updateAll(
					array('expense_date_new'=> $data["expense_date_new"]), 
					array('id' => $data["id"]));
		}

		echo "<pre>";
		print_r($result);  */
		 
		 /* $result = $this->FamilyExpense->find('all', array(
				'conditions' => array('expense_date_new' => null),
				'limit' => 500
		
		));
		foreach($result as $key=>$value){
			 
				
			$id = $value["FamilyExpense"]["id"];
			$oldDate = $value["FamilyExpense"]["expense_date"];
				
				
			$data = array();
			 
			$data["id"] = $id;
				
			$newDateStr = date("d-M-Y",$oldDate);
			$newDateStrArray = explode("-",$newDateStr);
		
			$newDateStrArray[1] = ucfirst($newDateStrArray[1]);
				
			$newDateStr = implode("-",$newDateStrArray);
				
			$data["expense_date_new"] = "'".$newDateStr."'";
			//$data["expense_date"] = 0;
				
				
			$this->FamilyExpense->updateAll(
					array('expense_date_new'=> $data["expense_date_new"]),
					array('id' => $data["id"]));
		
		}
		echo "<pre>";
		print_r($result);  */
		 
		 
		/*  $result = $this->Meal->find('all', array(
				'conditions' => array('date_new' => null),
				'limit' => 500
		
		));
		foreach($result as $key=>$value){
		
		
			$id = $value["Meal"]["id"];
			$oldDate = $value["Meal"]["date"];
		
		
			$data = array();
		
			$data["id"] = $id;
		
			$newDateStr = date("d-M-Y",$oldDate);
			$newDateStrArray = explode("-",$newDateStr);
		
			$newDateStrArray[1] = ucfirst($newDateStrArray[1]);
		
			$newDateStr = implode("-",$newDateStrArray);
		
			$data["date_new"] = "'".$newDateStr."'";
			//$data["date"] = 0;
		
		
			$this->Meal->updateAll(
					array('date_new'=> $data["date_new"]),
					array('id' => $data["id"]));
		
		}
		  
		 
		 
	    echo "<pre>";
		print_r($result);  */
		   
		 
					
	 //	$unique_url = $this->Expense->createExpense($data,false);
		exit;
	}

	public function myExpenses($unique_url=null)
    {
            $this->Session->write('system.message', '');
            $session_user_id = $this->Session->read('userData.id');
            $session_user_id = isset($session_user_id) ? $session_user_id : '';
            $userExpenses = [];
            // If the user is logged in, get the expense group from the database; otherwise, get it from the cookie.
            $this->Session->write('system.is_now_login', false);

            if($this->Session->check('userData.id')){
                $conditions = array('UserGroup.user_id' => $session_user_id, 'UserGroup.status' => $this->group_status['Active']);
                $fields = array('UserGroup.unique_url','UserGroup.participant_id','Expense.title','Expense.create_date');
                $userExpenses = $this->UserGroup->groupListWithExpense($fields, $conditions);

                $archive_conditions = array('UserGroup.user_id' => $session_user_id, 'UserGroup.status' => $this->group_status['Archived']);
                $archive_fields = array('UserGroup.unique_url','UserGroup.participant_id','Expense.title','Expense.create_date');
                $archivedExpenses = $this->UserGroup->groupListWithExpense($archive_fields, $archive_conditions);
            }else{
                $userExpenses = $this->Cookie->read('Expenses');
                $archivedExpenses=[];
            }

            $this->set('user_id', $session_user_id);
            $this->set('my_expenses', $userExpenses);
            $this->set('archived_expenses', $archivedExpenses);

    }
	public function removeGroup($unique_url)
    {
            $this->Session->write('system.message', '');
            $session_user_id = $this->Session->read('userData.id');
            $session_user_id = isset($session_user_id) ? $session_user_id : '';

            if(!empty($unique_url)){

                // delete a group from myExpense
                if($this->Session->check('userData.id')) {
                    $userGrpdata['skip_process_validation'] = 1;
                    $userGrpdata['user_id'] = $session_user_id;
                    $userGrpdata['unique_url'] = $unique_url;
                    $this->callAPI(HTTP_SITE_URL . "/users/groupdelete.json", 'POST', json_encode($userGrpdata));

                }
                if (empty($session_user_id)) {
                    $expenses = $this->Cookie->read('Expenses');
                    foreach ($expenses as $key => $expense) {
                        if ($expense['unique_url'] == $unique_url) {
                            unset($expenses[$key]);
                            break;
                        }

                    }
                    $expenses = array_values($expenses);
                    $this->Cookie->write('Expenses', $expenses, false, '24000 hours');
                }

            }

            return $this->redirect('myExpenses');

    }
	public function archiveGroup($unique_url)
    {
            $this->Session->write('system.message', '');
            $session_user_id = $this->Session->read('userData.id');
            $session_user_id = isset($session_user_id) ? $session_user_id : '';

            if(!empty($unique_url)){

                // delete a group from myExpense
                if($this->Session->check('userData.id')) {
                    $userGrpdata['skip_process_validation'] = 1;
                    $userGrpdata['user_id'] = $session_user_id;
                    $userGrpdata['unique_url'] = $unique_url;
                    $userGrpdata['status'] = $this->group_status['Archived'];
                    $this->callAPI(HTTP_SITE_URL . "/users/groupRestore.json", 'POST', json_encode($userGrpdata));

                }

            }

            return $this->redirect('myExpenses');

    }

    public function restoreGroup($unique_url)
    {
        $this->Session->write('system.message', '');
        $session_user_id = $this->Session->read('userData.id');
        $session_user_id = isset($session_user_id) ? $session_user_id : '';

        if(!empty($unique_url)){

            // restore a group from archived Expense
            if($this->Session->check('userData.id')) {
                $userGrpdata['skip_process_validation'] = 1;
                $userGrpdata['user_id'] = $session_user_id;
                $userGrpdata['unique_url'] = $unique_url;
                $userGrpdata['status'] = $this->group_status['Active'];
                $this->callAPI(HTTP_SITE_URL . "/users/groupRestore.json", 'POST', json_encode($userGrpdata));
            }

        }

        return $this->redirect('myExpenses');

    }
	public function myExpenses_old($key=null, $refresh=null)
    {

        $session_user_id = ($this->Session->read('userData.id')) ? $this->Session->read('userData.id') : '' ;

        //if ($session_user_id == '') {
            //$this->redirect('/users/login');
        //} else {
            if(!empty($key) || (isset($key) && $key !== '')){

                // delete a group from myExpense
                $my_expenses = $this->Cookie->read('Expenses');

                $userGrpdata['skip_process_validation'] = 1;
                $userGrpdata['user_id'] = $session_user_id;
                $userGrpdata['unique_url'] = $my_expenses[$key]['unique_url'];
                $this->callAPI(HTTP_SITE_URL . "/users/groupdelete.json", 'POST', json_encode($userGrpdata));

                unset($my_expenses[$key]);
                $my_expenses = $this->Cookie->write('Expenses', $my_expenses, false, '24000 hours');
            }

            if($refresh == 1){
                $this->Cookie->write('Expenses', null, false, '24000 hours');
            }

            if($this->Cookie->read('Expenses') === null) {
                // system.is_now_login is used to check if user just loged in now. I think we might not need this.
                // If there are groups in cookie show it; otherwise load from database; Reset the cookie during logout
                $this->Session->write('system.is_now_login', false);
                if($this->Session->check('userData.id')){
                    $user_id = $this->Session->read('userData.id');
                    $conditions = array('UserGroup.user_id' => $user_id);
                    $fields = array('UserGroup.unique_url','UserGroup.participant_id','Expense.title','Expense.create_date');
                    $userExpenses = $this->UserGroup->listWithExpense($fields, $conditions);
                    if(!empty($userExpenses)){
                        $this->Cookie->write('Expenses', $userExpenses, false, '24000 hour');
                    }
                }

            }
            else {
                $this->Session->write('system.message', '');
            }

            $my_expenses = $this->Cookie->read('Expenses');
            $this->set('user_id', $session_user_id);
            $this->set('my_expenses', $my_expenses);
        //}
    }

    public function products()
    {
        $products = array();
        $requestData = $this->deviceData();

        $apiResponse = $this->callGETAPI(HTTP_SITE_URL . "/products/list.json?".http_build_query($requestData));
        $apiResponseArr = json_decode($apiResponse, true);
        if (isset($apiResponseArr['response']['status']) && ($apiResponseArr['response']['status'] == '+000')) {
            $allproducts = $apiResponseArr['response']['products'];
            if(!empty($allproducts)){
                foreach ($allproducts as $k => $product){
                    if(empty($products[$product['expense_type']])){
                        $products[$product['expense_type']] = $product;
                    }
                    $productPriceArray[$product['expense_type']][] = $product;
                }
            }
        } else {
            $this->Session->write('system.message', 'No Product Found');
        }
        $this->set(compact('products','productPriceArray'));
    }

    public function getProduct()
    {
        $this->autoRender = false;
        $product = array();
        if($this->request->is('ajax')) {
            $this->loadModel('Product');
            $conditions = array(
                'expense_type' => $this->request->data['expense_type'],
                'payment_cycle' => $this->request->data['payment_cycle']
            );
            $product = $this->Product->list($conditions);
        }
        echo json_encode($product[0]);
    }

    function preparingProductBuyInput($requestData)
    {
        /*
        "product_id":"2",
        "product_sku":"FE6M",
        "user_id":"34",
        "payment_type_id":"1",
        "platform_id":"2",
        "amount":"20",
        "access_token":"0c1d9f14e828929a9fd7c0ca46bf4a6a8d0e6bc3ce78ed61d41cd8665521fd81",
        "device_id":"234234-34234-234234-234234-324234",
        "random_number":"4537",
        */
        $item_name = explode('-',$requestData['item_name']);

        $data['product_id'] = ltrim($item_name[1],'d');
        $data['product_sku'] = ltrim($item_name[2],'s');
        $data['user_id'] = ltrim($item_name[3],'u');
        $data['expense_type'] = ltrim($item_name[0],'t');
        $data['amount'] = $requestData['amt'];
        $data['platform_id'] = 3; //1 = android, 2 = iphone 3 = web.
        $data['payment_type_id'] = 3; //1= Wallet, 2 = Credit Card, 3=Paypal
        $data["device_id"] = session_id();
        $data["random_number"] = rand(1000, 9999);
        $data["access_token"] = $this->getUserToken($data["device_id"], $data["random_number"]);

        return $data;
    }

    public function paypalipn()
    {
//        echo 'this is paypal ipn page';
//        pr($this->request->query);
//        die;

        $this->loadModel('UserSubscription');
        $this->loadModel('User');

        $raw_post_data = file_get_contents('php://input');
        $raw_post_array = explode('&', $raw_post_data);
        $myPost = array();
        foreach ($raw_post_array as $keyval) {
            $keyval = explode ('=', $keyval);
            if (count($keyval) == 2)
                $myPost[$keyval[0]] = urldecode($keyval[1]);
        }

        // Read the post from PayPal system and add 'cmd'
        $req = 'cmd=_notify-validate';
        if(function_exists('get_magic_quotes_gpc')) {
            $get_magic_quotes_exists = true;
        }
        foreach ($myPost as $key => $value) {
            if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
                $value = urlencode(stripslashes($value));
            } else {
                $value = urlencode($value);
            }
            $req .= "&$key=$value";
        }

        /*
         * Post IPN data back to PayPal to validate the IPN data is genuine
         * Without this step anyone can fake IPN data
         */
        $paypalURL = PAYPAL_URL;
        $ch = curl_init($paypalURL);
        if ($ch == FALSE) {
            return FALSE;
        }
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
        curl_setopt($ch, CURLOPT_SSLVERSION, 6);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);

        // Set TCP timeout to 30 seconds
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close', 'User-Agent: company-name'));
        $res = curl_exec($ch);

        /*
         * Inspect IPN validation result and act accordingly
         * Split response headers and payload, a better way for strcmp
         */
        $tokens = explode("\r\n\r\n", trim($res));
        $res = trim(end($tokens));
        if (strcmp($res, "VERIFIED") == 0 || strcasecmp($res, "VERIFIED") == 0) {

            // Retrieve transaction data from PayPal
            $inputData = array();
            $paypalInfo = $_POST;
            $inputData['subscr_id'] = $subscr_id = $paypalInfo['subscr_id'];
            $inputData['payer_email'] = $payer_email = $paypalInfo['payer_email'];
            $inputData['item_name'] = $item_name = $paypalInfo['item_name'];
            $inputData['item_number'] = $item_number = $paypalInfo['item_number'];
            $inputData['txn_id'] = $txn_id = !empty($paypalInfo['txn_id'])?$paypalInfo['txn_id']:'';
            $inputData['payment_gross'] = $payment_gross =  !empty($paypalInfo['mc_gross'])?$paypalInfo['mc_gross']:0;
            $inputData['currency_code'] = $currency_code = $paypalInfo['mc_currency'];
            $inputData['validity'] = $subscr_period = !empty($paypalInfo['period3'])?$paypalInfo['period3']:floor($payment_gross/$itemPrice);
            $inputData['payment_status'] = $payment_status = !empty($paypalInfo['payment_status'])?$paypalInfo['payment_status']:'';
            $inputData['user_id'] = $custom = $paypalInfo['custom'];
            $subscr_date = !empty($paypalInfo['subscr_date'])?$paypalInfo['subscr_date']:date("Y-m-d H:i:s");
            $dt = new DateTime($subscr_date);
            $inputData['valid_from'] = $subscr_date = $dt->format("Y-m-d H:i:s");
            $inputData['valid_to'] = $subscr_date_valid_to = date("Y-m-d H:i:s", strtotime(" + $subscr_period month", strtotime($subscr_date)));

            if(!empty($txn_id)){
                // Check if transaction data exists with the same TXN ID
//                $prevPayment = $db->query("SELECT id FROM user_subscriptions WHERE txn_id = '".$txn_id."'");

                // Insert transaction data into the database
                /*$insert = $db->query("INSERT INTO user_subscriptions
                                    (user_id,validity,valid_from,
                                    valid_to,item_number,txn_id,payment_gross,
                                    currency_code,subscr_id,payment_status,payer_email)

                                    VALUES('".$custom."','".$subscr_period."','".$subscr_date."','"
                    .$subscr_date_valid_to."','".$item_number."','".$txn_id."','".$payment_gross."','"
                    .$currency_code."','".$subscr_id."','".$payment_status."','".$payer_email."')");
                // Update subscription id in the users table
                if($insert && !empty($custom)){
                    $subscription_id = $db->insert_id;
                    $update = $db->query("UPDATE users SET subscription_id = {$subscription_id} WHERE id = {$custom}");
                }
                */


                $existUserSub = $this->UserSubscription->isUserSubscriptionExist($txn_id);

                if (isset($existUser[0]) && empty($existUser[0])) {
                    $UserSubObj = $this->UserSubscription->insertUserSubscription($inputData);

                    if (isset($UserSubObj[1]['id']) && ($UserSubObj[1]['id'] > 0)) {
                        $subscription_id = $UserSubObj[1]['id'];
                        $user_id = $custom;
                        $this->User->updateFieldsById($user_id, $fields = array('user_subscription_id' => $subscription_id));
                    }


                }
            }
        }
        die;
//        return false;
    }

    public function paypalcancel()
    {
        // do nothing
    }

    public function createGroup()
    {
        echo 'this is createGroup page';
        pr($this->request->query);
        die;

        $data = $this->preparingProductBuyInput($this->request->query);

        $apiResponse = $this->callAPI(HTTP_SITE_URL . "/products/buy.json", 'POST', json_encode($data));
        $apiResponseArr = json_decode($apiResponse, true);

        if (isset($apiResponseArr['response']['status']) && ($apiResponseArr['response']['status'] == '+000')) {
            $this->redirect('/pages/myExpenses');

            /*if ($data['expense_type'] == 1):
                $this->redirect('/Home/createGroupExpense');
            elseif ($data['expense_type'] == 2):
                $this->redirect('/Home/createMessExpense');
            elseif ($data['expense_type'] == 3):
                $this->redirect('/Home/createFamilyExpense');
            endif;*/
        } else {
            $message = 'Something Wrong';
            $this->Session->write('system.message', $message);
            $this->redirect('/pages/products');
        }
    }

    public function getToken(){
        $device_id = "2sdfd6788ds76f8sd6f8f";
            $random_number = "c9du5htkwwACZWLcraKrngKbKPtJ1YaY";
        $unique_number = $device_id.$random_number; // device id + six digit random number
        $salt      = 'Nop@ss%!*-+@s=_17';
        $generated_token    = hash('sha256', $unique_number . $salt);
        echo $generated_token;exit;
    }

    public function getSecretKeyss()
    {
        $device_id = "2sdfd6788ds76f8sd6f8f";
        $this->loadModel('AccessKey');
        $access_key = $this->AccessKey->getAccessToken($device_id);
        //print_r($access_key['AccessKey']['secret_key']);
        echo $access_key;
        exit;
    }

    public function addGroup()
    {
        $url = $this->request->data['unique_url'];
        $unique_url = str_replace(HTTP_SITE_URL.'/', '', $url);
        $sessionProfileId = $this->Session->read('userData.profile_id');
        $sessionUserId = $this->Session->read('userData.id');
        list($status, $status_desc, $expObj) = $this->validateUniqueUrl($unique_url);
        if (empty($status)) {
            $permission = $this->Permission->PermissionByUserId($unique_url, $sessionUserId);
            if ($permission != NO_PERMIT) {

                $user_group = $this->UserGroup->find('first', array(
                    'conditions' => array('UserGroup.unique_url' => $unique_url, 'UserGroup.user_id' => $sessionUserId)
                ));

                if (empty($user_group)) {
                    $inputData['user_id'] = $sessionUserId;
                    $inputData['unique_url'] = $unique_url;
                    $inputData['participant_id'] = '1_0';
                    $result = $this->UserGroup->save($inputData);
                    $expense_name = 'GroupExpense';
                    $expense_type = substr($data["unique_url"], 0 , 1);
                    if ($expense_type == 2) {
                        $expense_name = "MessExpense";
                    } elseif ($expense_type == 3) {
                        $expense_name = "FamilyExpense";
                    }
                    $this->userGroupUpdateOnFirebase($sessionUserId, $expense_name);
                    $this->Cookie->delete('Expenses');

                    $this->Session->setFlash(__('LBL_Add_GROUP_SUCCESS_MESSAGE'), 'default', ['class' => 'alert alert-success']);


                } else {

                    $this->Session->setFlash(__('LBL_Add_GROUP_EXISTS_MESSAGE'), 'default', ['class' => 'alert alert-danger']);
                }

            } else {

                $this->Session->setFlash('You do not have permission to access this group!', 'default', ['class' => 'alert alert-danger']);
            }
        }
        else{
            $this->Session->setFlash( __('LBL_Add_GROUP_NOT_EXISTS_MESSAGE'), 'default', ['class' => 'alert alert-danger']);
        }

        return $this->redirect(['controller' => 'pages', 'action' => 'myExpenses']);
    }
	
 
}