<?php

namespace App\Controller;

use App\Controller\AppsController;
use Cake\I18n\I18n;
use Cake\Routing\Router;
use Cake\ORM\TableRegistry;
use Cake\Validation\Validator;
use DateTime;
use Mandrill;
use Stripe;
/**
 * Cmsusers Controller
 *
 * @property \App\Model\Table\CmsusersTable $Cmsusers
 */
class RegistrationsController extends AppsController {

    public function initialize() {
        parent::initialize();
        $this->loadModel('Cmsusers');
        $this->loadModel('Usergroups');
        I18n::locale('en_US');
        // $this->Auth->allow(['forgotPassword']);
        // $this->Auth->allow(['resetPassword']);
        // $this->Auth->allow(['termsService']);
        // $this->Auth->allow(['fbLogin']);
        // $this->Auth->allow(['fbLoginRegister']);
        // $this->Auth->allow(['checkArtistRegistered']);
        // $this->Auth->allow(['uploadPicture']);
        // $this->Auth->allow(['removeMedia']);
        // $this->Auth->allow(['uploadArtistPicture']);
        // $this->Auth->allow(['removeArtistMedia']);
        // $this->Auth->allow(['emailSent']);
        // $this->Auth->allow(['changeLanguage']);
        $this->Auth->allow(['guest']);
        $this->Auth->allow(['checkemail']);
        $this->Auth->allow(['stripeCreateCharge']);
        $this->Auth->allow(['terms']);
        $this->Auth->allow(['testSQL']);
    }

    public function isAuthorized($user) {
        $request_action = $this->request->params['action'];
        if ($request_action == "logout" || $request_action == "login" || $request_action == "bulkAction" || $request_action == "terms" || $request_action == "editProfile" || $request_action == "guest") {
            return true;
        }
        return false;
        // return parent::isAuthorized($user);
    }
    
    
    public function testSQL(){
    	
    	\Stripe\Stripe::setApiKey(APP_STRIPE_SECRET_KEY);
    	
    	$successfulCharge = false;
    	
    	$stripe = "cus_BNJ6lKuVhSNM2N";
    	
    	$chargeList = \Stripe\Charge::all(
    			array(
    					'limit'   => 110, // in the first time, put 5 then 10, 15, 20 etc....till 50
    					'created' => array(
    							'gte' => strtotime('-4380 min'),
    							'lte' => strtotime('0 min')
    					),
    					"failure_code"=>null,
    					"customer" => $stripe
    			)
    	);
    	
    	foreach ($chargeList->data as $charge) {
    		// Do something with $subscription
    		 
    		if(empty($charge->failure_code)) {
    			
    			$successfulCharge = true;
    			break;
    		}
    	}
    	
    	echo "<pre>";
    	print_r($successfulCharge);exit;
    	
    	
    	$this->loadModel('CmsuserUsergroups');
    	 
    	$availableCmsUserGroups = $this->CmsuserUsergroups->find('all',[
    			'conditions'=>[
    					'CmsuserUsergroups.cms_user_id'=>169,
    					'CmsuserUsergroups.usergroup_id'=>11
    			]
    			]);
    			 
    			echo "<pre>";
    			print_r($availableCmsUserGroups->toArray());
    			
    			exit;
    }

    /**
     * Add method
     *
     * @return void Redirects on successful add, renders view otherwise.
     */
/*     public function guest() {
        // pr($this->request->data); die;
        $cmsuser = $this->Cmsusers->newEntity();
        if ($this->request->is('post')) 
        {
            
            
            $cmsuser = $this->prepareCustomerObject($cmsuser);
            $password = $this->request->data('password');

            $this->request->session()->write('Auth.GuestUser', $cmsuser);
            $this->request->session()->write('Auth.GuestUserPass', $password);
            

            // payment here
            $payment_status = $this->paymentInStrip($cmsuser);

            // save user after payment
            if($payment_status == 'successed')
            {
                $cmsuser = $this->request->session()->read('Auth.GuestUser');
                $new_password = $this->request->session()->read('Auth.GuestUserPass');
                $cmsuser->current_plan_id = $this->request->session()->read('Auth.plan_id');
                $cmsuser->stripe_customer_id = $this->request->session()->read('Auth.stripe_customer_id');

                $this->request->session()->delete("Auth.GuestUser");
                $this->request->session()->delete("Auth.GuestUserPass");
                $this->request->session()->delete("Auth.stripe_customer_id");
                $this->request->session()->delete("Auth.plan_id");
                // pr($cmsuser);
                unset($cmsuser->token_no);
                unset($cmsuser->retype_password);
                // pr($cmsuser);die;
                
                if ($this->Cmsusers->save($cmsuser)) {

                    // add User To User Group
                    $this->addUserToUserGroup($cmsuser->id, USER_GROUP_ID);
                    // add User To Default Packages
                    $this->addUserToPackages($user_id = $cmsuser->id, $package_id = PACKAGE_ID);

                    $this->Flash->success(__('The Guest User has been created.'));

                    // $template_content = array(
                    //     array(
                    //         'name' => 'firstname',
                    //         'content' => $cmsuser->username
                    //     ),
                    //     array(
                    //         'name' => 'user_email',
                    //         'content' => $cmsuser->email
                    //     ),
                    //     array(
                    //         'name' => 'password',
                    //         'content' => $new_password
                    //     ),
                    //     array(
                    //         'name' => 'loginurl',
                    //         'content' => APP_SERVER_HOST_URL
                    // ));
                    $template_content = array(
                        'firstname' => $cmsuser->username,
                        'user_email'=> $cmsuser->email,
                        'password' => $new_password,
                        'loginurl' => APP_SERVER_HOST_URL
                    );

                    $this->sendEmail(MANDRILL_TEMPLATE_USER_CREATION, $template_content, $cmsuser->email);


                    return $this->redirect(['controller' => 'Cmsusers', 'action' => 'login']);
                } else {
                    $this->Flash->error(__('The user could not be saved. Please, try again.'));
                    $this->log($cmsuser->errors());
                    pr($cmsuser->errors());
                }
            } else {
                // $this->Flash->error(__('payment_status = '.$payment_status));
                $this->Flash->error(__('The user could not be saved. Please, try again.'));
            }
        }


        // $languages = [LANGUAGE_CODE_ENGLISH => 'English', LANGUAGE_CODE_KOREAN => 'Korean'];
        // $user_permissions = $this->request->session()->read('user_permissions');
        // $this->set('user_permission', $user_permissions);
        $this->set('cmsuser', $cmsuser);
        // $this->set('languages', $languages);
        $this->set('_serialize', ['cmsuser']);
        // $this->set('current_module', $this->getModules());
        $nav_arr[0] = array('action'=>'index','page_id'=>'3045','icon'=>'<i class="fa fa-list"></i>','label'=>'List');
        $this->set('nav_arr', $nav_arr);
        $this->viewBuilder()->layout("before_login");
    } */

    /*
    public function checkSubscription(){
    	
    	 
    	 
      $plan_id_array = $this->objectToArray(json_decode(RTG_PLAN_ID));
      
      $total_record_processed = 0;
     
      foreach($plan_id_array as $index=>$stripePlanId){
    	 
    	\Stripe\Stripe::setApiKey(APP_STRIPE_SECRET_KEY);
    	
    	$Subscriptions = \Stripe\Subscription::all(
    			array(
    					'limit'   => 110, // in the first time, put 5 then 10, 15, 20 etc....till 50 
    					'created' => array(
    							'gte' => strtotime('-25 min'),
    							'lte' => strtotime('0 min') 
    					),
    					//'starting_after' => 'sub_BQdvHBBf8lfjsR',
    					"plan" => $stripePlanId
    			)
    	);
    	
    
			foreach ($Subscriptions->data as $subscription) {  
			    // Do something with $subscription
			    //$subscription->id
				
				$customerObj = \Stripe\Customer::retrieve($subscription->customer);
			   $customer = $customerObj->__toArray(true);
			   //$customer = $customerArray['sources']['data'][0];  
			   $cmsuser = [];
			   $isRecordExist = $this->checkemail($customer['email']);
			    if(!$isRecordExist){
					
			    	$total_record_processed++;
					
					$cmsuser = $this->Cmsusers->newEntity();		
					$password = rand(100000,999999);
					$cmsuser = $this->createUser($cmsuser,["email" => $customer['email'],
					"password" => $password,
					"address_zip" => "",
					"stripe_customer_id" => $customer['id'],
					"phone" => "",
					"cardholder_name" => "",
					"permission_version" => "1",
					"ip" => "",
					"is_first_login" => "1",
					"package_id" => "2",
					"img_path" => "",
					"username" => $customer['email'],
					"language" => "en",
					"retype_password" => $password,
					]);
			    	
					$customerName = explode("@",$customer['email']);
					
					if ($this->Cmsusers->save($cmsuser)) {
						
						// add User To User Group
						$this->addUserToUserGroup($cmsuser->id, USER_GROUP_ID);
						// add User To Default Packages
						$this->addUserToPackages($cmsuser->id,PACKAGE_ID);
						$this->addUserToPackages($cmsuser->id,PACKAGE_WAVE_1_ID);
			 
						$template_content = array(
			                        'firstname' => $customerName[0],
			                        'user_email'=> $customer['email'],
			                        'password' => $password,
			                        'loginurl' => APP_SERVER_HOST_URL
			                    );
						//echo "Going to send email to :::".$customer['email']; 
						$this->sendEmail(MANDRILL_TEMPLATE_USER_CREATION, $template_content, $cmsuser->email);
			
					}else{
						// echo "::::::No data added----".$customer['email']."<br>\n";  
					}
				}else{
					 // do nothing
				}
			    }
			
      }
      
      //insert logs into process logs
      
      
      //$total_record_processed
      	$this->saveLogs("REG",$total_record_processed);
		echo "Customer process completed...";	
		exit;
    	 
    }
     */
    
    private function saveLogs($process_name,$number_of_record_processed){
    	$logTable = TableRegistry::get("ProcessLogs");
    	$entity = $logTable->newEntity();    	
    	
    	$entity->process_name = $process_name;
    	$entity->number_of_record_processed = $number_of_record_processed;    	 
    	$entity->created_on = date('Y-m-d h:i:s');
    	
     	$logTable->save($entity);
    	
    }
 
    
    private function objectToArray($d) {
    	if (is_object($d))
    		$d = get_object_vars($d);
    	return is_array($d) ? array_map(__METHOD__, $d) : $d;
    }
	
	

    /**
     * @param $cmsuser
     * @return \Cake\Datasource\EntityInterface
     */
    private function createUser($cmsuser,$data) {
        $cmsuser = $this->Cmsusers->patchEntity($cmsuser, $data);
        $cmsuser->reset_password_token = '';
        $cmsuser->created_on = date('Y-m-d H:i:s'); // date('Y-m-d H:i:s', strtotime("-61 day")); //
        $cmsuser->updated_on = date('Y-m-d H:i:s');
        $cmsuser->status = STATUS_ACTIVE;
        $cmsuser->company_id = 8;
        return $cmsuser;
    }

   /*  private function paymentInStrip($user)
    {
        require(ROOT.'/vendor/stripe/stripe-php/lib/Stripe.php');
        // payment code is here
        $stripe_customer_id = '';
        $customerObj = $this->stripeCreateCustomer($user->email,$user->token_no);
        if(!empty($customerObj)){
            $stripe_customer_id = $customerObj['id'];
        }
        $this->request->session()->write('Auth.stripe_customer_id', $stripe_customer_id);

        if(!empty($stripe_customer_id)){
            // $cardObj = $this->stripeCreateCard($stripe_customer_id);
                
            $defaultPlan = $this->getDefaultPlan();
            $plan_id = '';
            $plan_price = 0;
            if(!empty($defaultPlan)){
                $plan_id = $defaultPlan->stripe_plan_id;
                $plan_price = $defaultPlan->price;
            }
            $subscriptionObj = [];
            if(!empty($stripe_customer_id) && !empty($plan_id)){
                $subscriptionObj = $this->stripeCreateSubscription($stripe_customer_id, $plan_id);

                $this->request->session()->write('Auth.plan_id', $plan_id);

                $chargeObj = [];

                // if(!empty($user->token_no)){
                   // $chargeObj = $this->stripeCreateCharge($plan_price, $stripe_customer_id);
                // }
               // if(!empty($chargeObj)) {
                if(!empty($subscriptionObj)) {
                    // return true;
                    $code = 'successed';
                }
            } else {
                $code = 'failed';
            }
        } else {
            $code = 'failed';
        }
        // payment status is success
        
        return $code;
    } */
    
  /*   public function stripeCreateCustomer($email = null, $token_no = null)
    {
        //Create a new customer and card information
        Stripe\Stripe::setApiKey(APP_STRIPE_SECRET_KEY);
        
        $customerObj = \Stripe\Customer::create(array(
                "description" => "Customer for RTG",
                "source" => $token_no,
                "email" => $email,
                // obtained with Stripe.js
        ));
        //    pr($customerObj['id']);
        //    pr($customerObj);
        // exit;
        return $customerObj;
    } */
    
   /*  public function stripeCreateCard($customer_id = null)
    {
        //Create a new card information
        Stripe\Stripe::setApiKey(APP_STRIPE_SECRET_KEY);
        
        $customer = \Stripe\Customer::retrieve($customer_id);
        $cardObj = $customer->sources->create(array("source" => "tok_visa"));

        return $cardObj;
    } */
    
  /*   public function stripeCreateSubscription($customer_id = null, $plan_id = null)
    {
        //Create a new Subscription
        \Stripe\Stripe::setApiKey(APP_STRIPE_SECRET_KEY);

        $subscriptionObj = \Stripe\Subscription::create(array(
          "customer" => $customer_id,
          "items" => array(
            array(
              "plan" => $plan_id,
            ),
          )
        ));

        return $subscriptionObj;
    } */
    
   /*  public function stripeCreateCharge($price = 0, $stripe_customer_id = '',$package_id="")
    {
    	//Create a new charge
    	\Stripe\Stripe::setApiKey(APP_STRIPE_SECRET_KEY);

        // $chargeObj = \Stripe\Charge::create(array(
        //   "amount" => intval($price),
        //   "currency" => "usd",
        //   // "source" => $token_no, // obtained with Stripe.js
        //   "description" => "Charge for RTG Member"
        // ));


        $chargeObj = \Stripe\Charge::create(array(
          "amount" => ($price*100), // amount in cents, again
          "currency" => "usd",
          "customer" => $stripe_customer_id,
          "description" => "Charge for RTG package ID#".$package_id)
        );
    	return $chargeObj;
    } */

   /*  private function getDefaultPlan()
    {
        $defaultPlan = [];
        $table_plan = TableRegistry::get("Plans");
        $defaultPlan = $table_plan->find('all')
            ->select(['name','price','stripe_plan_id','is_default_plan'])
            ->where(['Plans.is_default_plan'=>1])
            ->first();
        return $defaultPlan;
    }
 */

    private function addUserToUserGroup($user_id, $usergroup_id)
    {
        $table_user_groups_user = TableRegistry::get("CmsuserUsergroups");
        $entity = $table_user_groups_user->newEntity();
        $entity->cms_user_id = $user_id;
        $entity->usergroup_id = $usergroup_id;
        if($table_user_groups_user->save($entity)){
            return true;
        } else {
            return false;
        }
    }

    public function addUserToPackages($user_id, $package_id)
    {
        $table_member_packages = TableRegistry::get("MemberPackages");
        $entity = $table_member_packages->newEntity();
        $entity->member_id = $user_id;
        $entity->package_id = $package_id;
        $entity->status = 1;
        $entity->created_on = date('Y-m-d h:i:s');
        if($table_member_packages->save($entity)){
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param $cmsuser
     * @return \Cake\Datasource\EntityInterface
     */
   /*  private function prepareCustomerObject($cmsuser) {
        $cmsuser = $this->Cmsusers->patchEntity($cmsuser, $this->request->data);
        $cmsuser->reset_password_token = '';
        $cmsuser->created_on = date('Y-m-d H:i:s');
        $cmsuser->updated_on = date('Y-m-d H:i:s');
        $cmsuser->status = STATUS_ACTIVE;
        $cmsuser->company_id = COMPANY_ID; //$this->Auth->user('company_id');
        // $cmsuser->current_plan_id = PACKAGE_ID;
        return $cmsuser;
    }
 */


    public function terms()
    {
        $session = $this->request->session();
        if ($this->request->is('post')) {
            if($this->request->data['terms'] == 1){
                
                //TODO - Change the logic of saving the user permissions
                // $previous_permission_version= $session->read('permission_version');
                // $user= $session->read('Auth.User');
                // $current_permission_version=TableRegistry::get('cmsusers')->get($user['id'])->permission_version;
                // if($current_permission_version!==$previous_permission_version){
                //     $this->addPermissionsAndVersionToSession($session, $user,$current_permission_version);
                // }
                
            	$user = $this->Auth->user();
                    
            	//change first time login
            	if(!empty($user)){
	            	$CmsusersTable = TableRegistry::get('Cmsusers');
	            	$CmsusersObj = $CmsusersTable->newEntity();
//	            	$CmsusersObj = $CmsusersTable->get();
//	            	 pr($CmsusersObj);exit;
                        if($_SESSION['userType']==4){
                            $user_id_or_cms_user_id = $user["user_id"];
                        }
                        
                        if($_SESSION['userType']==1){
                            $user_id_or_cms_user_id = $user["id"];
                        }
	            	$CmsusersObj->id = $user_id_or_cms_user_id;
	            	$CmsusersObj->is_first_login = 2;
	            	$user["is_first_login"] = $CmsusersObj->is_first_login;
                    if($user["is_trial_user"] == 1){
                        $this->loadModel('App');
                        $CmsusersObj->created_on = $this->App->getSystemCurrentTimeStamp();
                    }
	            	$CmsusersTable->save($CmsusersObj);
	            	
	            	$this->Auth->setUser($user);
                       
            	}
            	
            	
                $user_permissions= $session->read('prev_user_permissions');
                // $session->delete("prev_user_permissions");
                $session->write('user_permissions', $user_permissions);
                if($_SESSION['userType']==4){
                $redirectController = $_SESSION['access_controller'][0]['controller_name'];
                $this->redirect(['controller' =>$redirectController,'action' => 'index']);
            
                } else {
                    $this->redirect(['controller' =>'Dashboard','action' => 'index']);
                }
                }
        } else {
            $prev_user_permissions= $session->read('user_permissions');
            $session->write('prev_user_permissions', $prev_user_permissions);
            // $session->delete("user_permissions");
        }
        
        $this->viewBuilder()->layout("before_login");
    }

    public function checkemail($email)
    {
       // $defaultCmsusers = [];
       // $email = $this->request->data['email'];
       $result = false;

       $table_Cmsusers = TableRegistry::get("Cmsusers");
        $defaultCmsusers = $table_Cmsusers->find('all')
            ->select(['id','email'])
            ->where(['Cmsusers.email'=>$email])
            ->first();
        // return $defaultCmsusers;
        if(!empty($defaultCmsusers)){
           $result = true;
        } 
        
        return $result;
        
        /* else {
            $txt = 'Email is exist. Please change your email.';
        }
        $txtJson = json_encode($txt);
        $this->response->type('json');
        $this->response->body($txtJson);
        return $this->response; */
    }


}
