<?php 
class Cr_renew_membership extends CI_Controller
{
	public function renewUserMembership()
    {
        $this->load->model('common_model');
        //$currentDate = '2020-06-11';
        //$currentDate = date('Y-m-d');
        mail('testdevloper007@gmail.com','Renew Cron runs','Renew Cron runs');

        $memberships = $this->common_model->getAll('shop_articles',array('id >'=>3,'id <'=>6),'','id Desc') ;
        $memberships_half = $this->common_model->getAll('shop_new_articles','','','id Asc') ;

        $currentDate = date('Y-m-d',strtotime('+1 day',time()));
        $time = strtotime($currentDate);
        $qry = $this->db->query('select * from (select *, case when time = 365 then DATE(FROM_UNIXTIME(created + (365 * 86400))) when time = 182 then DATE(FROM_UNIXTIME(created + (182 * 86400))) end as required_date  from (SELECT shop_orders.payment_method_id,shop_orders.time,shop_articles_carts.article_id,shop_orders.created,shop_orders.cart_id,`usr_users`.`id` as `user_id`,`usr_users`.`email` as `email`, `usr_users`.`cc_ref_id`, `shop_articles`.`userstatus`,usr_users.stop_renewal,usr_users.card_alias FROM `shop_articles` INNER JOIN `shop_articles_carts` ON `shop_articles_carts`.`article_id` = `shop_articles`.`id` INNER JOIN `shop_carts` ON `shop_carts`.`id` = `shop_articles_carts`.`cart_id` INNER JOIN `usr_users` ON `usr_users`.`id` = `shop_carts`.`user_id` INNER JOIN `shop_orders` ON `shop_orders`.`cart_id` = `shop_carts`.`id` WHERE ( `shop_articles_carts`.`cancelled` != 1 OR `shop_articles_carts`.`cancelled` IS NULL ) ORDER BY `usr_users`.`id` DESC, `shop_carts`.`created` DESC) as a GROUP BY a.user_id ORDER BY a.user_id DESC) as b where case when time = 365 then b.created <('.$time.' - (364 * 86400)) when time = 182 then b.created <('.$time.' - (181 * 86400)) end AND article_id in (5,4) AND required_date = "'.$currentDate.'" order by b.created DESC limit 0,10');
   
        $getUserListData1 = $qry->result();
        $getUserListData = (array) $getUserListData1;
		
        $i = 0;
        //echo $this->db->last_query();die;
        //echo '<pre>';print_r($getUserListData); die();
        foreach ($getUserListData as $data) {
            if($data->stop_renewal == 1){
                $this->common_model->insertData('feu_user_steps',array('user_id'=>$data->user_id,'step'=>6,'created'=>time()));
            } else {

                $first_paid_membership = $this->common_model->getAllRow('shop_orders',array('is_booking'=>0, 'payed'=>1, 'cancelled'=>0, 'invoiceAddress'=>$data->email ),'','created ASC');
                
               print"<pre>";
                var_dump($data->user_id);
    			$text = $data->cc_ref_id.'|'.date('d-m-Y',$data->created);
    			//mail('testdevloper007@gmail.com','new cron test1',$text);
                $user = $this->db->where('id', $data->user_id)
                        ->join('feu_userdetails','feu_userdetails.user_id = usr_users.id')
                        ->get('usr_users')
                        ->result()[0];
                // TO DO Send Email for Renewal CC Details
                if(!$data->cc_ref_id && $data->payment_method_id == 13 && !$data->card_alias){

                    print"<pre>";
                    var_dump('No CC Ref Id Email Send');
                    $this->common_model->insertData('feu_user_steps',array('user_id'=>$data->user_id,'step'=>6,'created'=>time()));
                    //$to = 'sayan@digitalaptech.com';
                    
                    mail('testdevloper007@gmail.com','cc ref fail',$data->user_id.'= cc ref not found');
                    /***************Renew fail*******************/
                    $orderQry = $this->db->query('select * from shop_orders where cart_id = '.$data->cart_id);
                    $data->order_data = $orderQry->result()[0];
                    $cartDataset = array(
                        'created'   => time(),
                        'user_id'   => $data->user_id,
                        'ordered'   => 0
                    );
                    if(!$cartId = $this->common_model->insertData('shop_carts',$cartDataset)) {
                        print"<pre>";
                        var_dump('There was an error trying to create the Cart Dataset');
                    }
                    //End Create New Order cart dataset
                    //Insert shop articles cart dataset
                    $cartArticleDataset = array(
                        'created'       => time(),
                        'article_id'    => $data->userstatus == 'premium' ? 4 : 5,
                        'cart_id'       => $cartId,
                        'quantity'      => 1,
                    );

                    $this->db->insert('shop_articles_carts', $cartArticleDataset);
                    //End Insert shop articles cart dataset
                    $orderDetails = $this->common_model->getAllRow('shop_orders','','','','max(order_id) as order_id');
                    //Create Order Dataset
                    $time = 365;
                    if($data->order_data->time > 0)
                    {
                        $time = $data->order_data->time;
                    }
    				
    				
    				$ord_totalbase = $data->order_data->total_base;
    				$ord_totalsum = 0;
    				$ord_paymentfee = 0;
    				$ord_vat = 0;
    				if($data->userstatus == 'premium'){
                        if($time==365){
                            $ord_totalbase = $memberships[1]['base_price'];
                            
                        }else{
                            $ord_totalbase =  $memberships_half[1]['base_price'];
                        }
                        
                    }else{
                        
                        if($time==365){
                            $ord_totalbase =  $memberships[0]['base_price'];
                        }else{
                            $ord_totalbase =  $memberships_half[0]['base_price'];
                        }                   
                        
                    }
    				$ord_paymentfee=(int)($ord_totalbase*2.5)/100;
    				/*if($data->order_data->vat > 0){
    					$ord_vat=(int)((($ord_totalbase+$ord_paymentfee)*7.7)/100) ;
    				}*/				
    				$ord_totalsum = (int)($ord_totalbase+$ord_paymentfee+$ord_vat);
    				//print_r($ord_totalsum);die();
                    $orderDataset = array(
                        'order_id'=> $orderDetails['order_id']+1,
                        'cart_id' => $cartId,
                        'created' => time(),
                        'updated' => NULL,
                        'shipping_address_id' => $data->order_data->shipping_address_id ? $data->order_data->shipping_address_id : null,
                        'invoice_address_id'  => $data->order_data->invoice_address_id ? $data->order_data->invoice_address_id : null,
                        'ip_address'    => $data->order_data->ip_address,
                        'total_base' => $data->order_data->total_base ? $data->order_data->total_base : 0,
                        'total_sum' => $data->order_data->total_sum ? $data->order_data->total_sum : 0,
                        'shipping_fee' => $data->order_data->shipping_fee ? $data->order_data->shipping_fee : 0,
                        'payment_fee'  => $data->order_data->payment_fee ? $data->order_data->payment_fee : 0,
                        'vat'  => $data->order_data->vat ? $data->order_data->vat : 0,
                        //'total_sum' => $data->order_data->total_sum,
                        'payment_method_id' => ($data->order_data->payment_method_id==15) ? 13 : $data->order_data->payment_method_id,
                        'payed' => 0,
                        'invoiceAddress' =>$data->email ? $data->email: null,
                        'time' =>$time,
                        'is_renewed' =>1,
                        'fail_reason'=>'Invalid CC Ref Id',
                        'discount'  => $data->order_data->discount ? $data->order_data->discount : null
                    );

                    $this->db->insert('shop_orders', $orderDataset);

                    $orderData = $this->db->where('cart_id', $cartId)
                        ->get('shop_orders')
                        ->result()[0];

                    $orderId = $orderDetails['order_id']+1;
                    $this->common_model->UpdateData('shop_orders',array('order_id_masked'=>'CE-'.$orderId),array('order_id'=>$orderId));
                    
                    $unpaidDataSet = array(
                        'user_id'     => $data->user_id,
                        'order_id'    => $orderId
                    );
                    $this->db->insert('usr_temp_unpaid_orders', $unpaidDataSet);

                    $outstandingDetails = $this->common_model->getAllRow('shop_orders',array('cart_id'=>$cartId));
                    $to = $user->email;
                    $sub = getLang('Membership_Renew_failure');
                    $body= '<p>'.getLang('We_tried_to_change_you_your_outstanding_membership').'</p>';
                    $body.= '<h3 class="text_gold">'.getLang('INVOICE_DETAILS').'</h3> 
                        <div style="clear:both;">
                          <p>'.getLang('Invoice_Number').' : CE-'.$orderId.'</p>
                          <p>'.getLang('Invoice_Date').' : '.date('d-m-Y').'</p>
                          <p>'.getLang('Due_Date').' : '.date('d-m-Y').'</p>
                          <div style="background-color: #b3975b; border-radius: 5px; clear: both; height: auto;padding: 0 20px;line-height: 50px;text-align: center; "><p>'.getLang('Outstanding_Balance').': '.number_format($outstandingDetails['total_sum']/100, 2,',', '.').' &euro;</p></div>
                        </div> ';
                
                    $body.= '<p style="background-color: #333333; border-radius: 5px; clear: both; height: auto;padding: 0 20px;line-height: 50px;text-align: center;"><a  style="color:#fff; text-decoration: none;" href="'.base_url().'add_card/index/'.base64_encode($orderId).'">'.getLang('Please_login_and_pay_by_credit_card').'</a></p>';
                    $body.= '<br><p>'.getLang('Thank_you_very_much_for').'</p>';
                    $body.= '<p>'.getLang('Please_do_not_hasitate_to_contact').'.</p>';
                    $bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
                        <tr>
                           <td>
                              <table cellspacing="0" cellpadding="0" border="0" width="100%">
                                 <tr>
                                    <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
                                       <h2>'.getLang('Dear').' <span style="text-transform:capitalize">'.$user->username.'</span> </h2>
                                    </td>
                                 </tr>
                                 <tr>
                                    <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
                                       '.$body.'
                                    </td>
                                 </tr>
                                 <tr>
                                    <td align="center" style="font-family: sans-serif; color: rgb(179, 151, 91); padding: 20px 40px; border-top: 1px solid rgb(79, 79, 79); background: rgb(19, 18, 24) none repeat scroll 0px 0px;">
                                        '.getLang('Best_regards').' <br>
                                        <p style="margin:5px 0 0">'.getLang('Your_Castleevents_Team').'</p> 
                                    </td>
                                 </tr>
                              </table>
                           </td>
                        </tr>
                    </table>';
                    $this->utility->sendCIRenewMail($to,$sub,$bodys);
    				$this->utility->sendCIRenewMail('testdevloper007@gmail.com',$sub,$bodys);
                    /***************Renew fail*******************/    
                } else {
                    $orderQry = $this->db->query('select * from shop_orders where cart_id = '.$data->cart_id);
                    $data->order_data = $orderQry->result()[0];
                    $cartDataset = array(
                        'created' 	=> time(),
                        'user_id' 	=> $data->user_id,
                        'ordered' 	=> 0
                    );
                    if(!$cartId = $this->common_model->insertData('shop_carts',$cartDataset)) {
                        print"<pre>";
                        var_dump('There was an error trying to create the Cart Dataset');
                    }
                    //End Create New Order cart dataset
                    //Insert shop articles cart dataset
                    $cartArticleDataset = array(
                        'created'       => time(),
                        'article_id' 	=> $data->userstatus == 'premium' ? 4 : 5,
                        'cart_id' 		=> $cartId,
                        'quantity' 		=> 1,
                    );

                    $this->db->insert('shop_articles_carts', $cartArticleDataset);
                    //End Insert shop articles cart dataset
                    $orderDetails = $this->common_model->getAllRow('shop_orders','','','','max(order_id) as order_id');
                    //Create Order Dataset
                    $time = 365;
                    if($data->order_data->time > 0)
                    {
                        $time = $data->order_data->time;
                    }
    				$ord_totalbase = $data->order_data->total_base;
    				$ord_totalsum = 0;
    				$ord_paymentfee = 0;
    				$ord_vat = 0;
    				if($data->userstatus == 'premium'){
                        if($time==365){
                            $ord_totalbase = $memberships[1]['base_price'];
                            
                        }else{
                            $ord_totalbase =  $memberships_half[1]['base_price'];
                        }
                        
                    }else{
                        
                        if($time==365){
                            $ord_totalbase =  $memberships[0]['base_price'];
                        }else{
                            $ord_totalbase =  $memberships_half[0]['base_price'];
                        }                   
                        
                    }
    				$ord_paymentfee=(int)($ord_totalbase*2.5)/100;
    				/*if($data->order_data->vat > 0){
    					$ord_vat=(int)(($ord_totalbase+$ord_paymentfee)*7.7)/100 ;
    				}*/				
    				$ord_totalsum = (int)($ord_totalbase+$ord_paymentfee+$ord_vat);
    				
    				
    				
                    $orderDataset = array(
                        'order_id'=> $orderDetails['order_id']+1,
                        'cart_id' => $cartId,
                        'created' => time(),
                        'updated' => NULL,
                        'shipping_address_id' => $data->order_data->shipping_address_id ? $data->order_data->shipping_address_id : null,
                        'invoice_address_id'  => $data->order_data->invoice_address_id ? $data->order_data->invoice_address_id : null,
                        'ip_address'    => $data->order_data->ip_address,
                        'total_base' => $data->order_data->total_base ? $data->order_data->total_base : 0,
                        'total_sum' => $data->order_data->total_sum ? $data->order_data->total_sum : 0,
                        'shipping_fee' => $data->order_data->shipping_fee ? $data->order_data->shipping_fee : 0,
                        'payment_fee'  => $data->order_data->payment_fee ? $data->order_data->payment_fee : 0,
                        'vat'  => $data->order_data->vat ? $data->order_data->vat : 0,
                        //'total_sum' => $data->order_data->total_sum,
                        'payment_method_id' => ($data->order_data->payment_method_id==15) ? 13 : $data->order_data->payment_method_id,
                        'payed' => 0,
                        'invoiceAddress' =>$data->email ? $data->email: null,
                        'time' =>$time,
                        'is_renewed' =>1,
                        'discount'  => $data->order_data->discount ? $data->order_data->discount : null
                    );

                    $this->db->insert('shop_orders', $orderDataset);

                    $orderData = $this->db->where('cart_id', $cartId)
                        ->get('shop_orders')
                        ->result()[0];

                    $orderId = $orderDetails['order_id']+1;
    				$this->common_model->UpdateData('shop_orders',array('order_id_masked'=>'CE-'.$orderId),array('order_id'=>$orderId));
    				$paymentMethod = $this->db->where('id', 13)
                        ->get('shop_payment_methods')
                        ->result()[0];
                    $paymentResult = array();
                    if($data->card_alias) {
                        $paymentResult = $this->_chargeSaferpayJson($user, $orderData);
                    }  
                    
                    //mail('testdevloper007@gmail.com','new cron charge',$data->user_id);

    				/******************10-11-2017*******************/
    				$userDet= $this->common_model->getAllRow('usr_users',array('id'=>$data->user_id));
    				$status = '';
                    $error = '';
                    if(isset($paymentResult['success']))
    				{
    					$this->common_model->deleteData('feu_user_steps',array('user_id'=>$data->user_id));
                        $status = 'Paid';
    					$error = '';
                        
                        //$to = 'sayan@digitalaptech.com';
                        $to = $user->email;
                        $sub = getLang('Membership_successfully_renewed');
                        $body= '<p>'.getLang('Thank_you_very_much_for_renewing').'</p>';
                        $body.= '<p>'.getLang('On_our_website_you_will_find').'.</p>';
                        if(isset($first_paid_membership)){
                            $body.= '<p></p>';
                            $body.= '<p>This payment is related our <a href="'.base_url('terms').'">terms and conditions</a> confirmed from you on '.date('d-m-Y H:i:s', $first_paid_membership['created']).' </p>';
                        }
                        $bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
                            <tr>
                               <td>
                                  <table cellspacing="0" cellpadding="0" border="0" width="100%">
                                     <tr>
                                        <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
                                           <h2>'.getLang('Dear').' <span style="text-transform:capitalize">'.$user->username.'</span> </h2>
                                        </td>
                                     </tr>
                                     <tr>
                                        <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
                                           '.$body.'
                                        </td>
                                     </tr>
                                     <tr>
                                        <td align="center" style="font-family: sans-serif; color: rgb(179, 151, 91); padding: 20px 40px; border-top: 1px solid rgb(79, 79, 79); background: rgb(19, 18, 24) none repeat scroll 0px 0px;">
                                            '.getLang('Best_regards').' <br>
                                            <p style="margin:5px 0 0">'.getLang('Your_Castleevents_Team').'</p> 
                                        </td>
                                     </tr>
                                  </table>
                               </td>
                            </tr>
                        </table>';
                        $this->utility->sendCIRenewMail($to,$sub,$bodys);

                        /****extra mail****/
                            $to = 'alorenc@me.com';
                            $sub = 'Payment recieved';
                            $body= 'CE-'.$orderId.', EUR '.number_format(($orderData->total_sum/100), 2,',', '.');
                            $body.= '<p>Paid Renewal Membership Fees</p>';
                            $body.= '<p>'.$user->username.'</p>';
                            $bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
                                        <tr>
                                           <td>
                                              <table cellspacing="0" cellpadding="0" border="0" width="100%">
                                                 <tr>
                                                    <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
                                                       '.$body.'
                                                    </td>
                                                 </tr>
                                              </table>
                                           </td>
                                        </tr>
                                    </table>';
                            $this->utility->sendOrderMail($to,$sub,$bodys);
                        /****extra mail****/
                        //$this->utility->sendCIMail('testdevloper007@gmail.com',$sub,$bodys);
                    }
    				else
    				{
    					$unpaidDataSet = array(
                            'user_id'     => $data->user_id,
                            'order_id'    => $orderId
                        );
                        $this->db->insert('usr_temp_unpaid_orders', $unpaidDataSet);
                        
                        $this->common_model->insertData('feu_user_steps',array('user_id'=>$data->user_id,'step'=>6,'created'=>time()));
                        $outstandingDetails = $this->common_model->getAllRow('shop_orders',array('cart_id'=>$data->cart_id));
                        $status = 'Unpaid';
    					$error = '';
                        if(isset($paymentResult['error'])){
                            $error = $paymentResult['error'];
                        }
                        //$to = 'sayan@digitalaptech.com';
                        $to = $user->email;
                        $sub = getLang('Membership_Renew_failure');
                        $body= '<p>'.getLang('We_tried_to_change_you_your_outstanding_membership').'</p>';
                        $body.= '<h3 class="text_gold">'.getLang('INVOICE_DETAILS').'</h3> 
                            <div style="clear:both;">
                              <p>'.getLang('Invoice_Number').' : CE-'.$orderId.'</p>
                              <p>'.getLang('Invoice_Date').' : '.date('d-m-Y').'</p>
                              <p>'.getLang('Due_Date').' : '.date('d-m-Y').'</p>
                              <div style="background-color: #b3975b; border-radius: 5px; clear: both; height: auto;padding: 0 20px;line-height: 50px;text-align: center; "><p>'.getLang('Outstanding_Balance').': '.number_format($outstandingDetails['total_sum']/100, 2,',', '.').' &euro;</p></div>
                            </div> ';
                    
                        $body.= '<p style="background-color: #333333; border-radius: 5px; clear: both; height: auto;padding: 0 20px;line-height: 50px;text-align: center;"><a  style="color:#fff; text-decoration: none;" href="'.base_url().'add_card/index/'.base64_encode($orderId).'">'.getLang('Please_login_and_pay_by_credit_card').'</a></p>';
                        $body.= '<br><p>'.getLang('Thank_you_very_much_for').'</p>';
                        $body.= '<p>'.getLang('Please_do_not_hasitate_to_contact').'.</p>';
                        
                        

                        $bodys=' <table cellspacing="0" cellpadding="0" border="0" align="center" bgcolor="#22222c" width="100%" style="max-width: 600px;">
                            <tr>
                               <td>
                                  <table cellspacing="0" cellpadding="0" border="0" width="100%">
                                     <tr>
                                        <td align="center" style="padding: 40px; font-family: sans-serif; font-size: 15px; mso-height-rule: exactly; line-height: 20px; color: #b3975b;">
                                           <h2>'.getLang('Dear').' <span style="text-transform:capitalize">'.$user->username.'</span> </h2>
                                        </td>
                                     </tr>
                                     <tr>
                                        <td style="font-family: sans-serif; color: #fff; padding: 0px 40px 40px; font-size: 16px; line-height: 30px;">
                                           '.$body.'
                                        </td>
                                     </tr>
                                     <tr>
                                        <td align="center" style="font-family: sans-serif; color: rgb(179, 151, 91); padding: 20px 40px; border-top: 1px solid rgb(79, 79, 79); background: rgb(19, 18, 24) none repeat scroll 0px 0px;">
                                            '.getLang('Best_regards').' <br>
                                            <p style="margin:5px 0 0">'.getLang('Your_Castleevents_Team').'</p> 
                                        </td>
                                     </tr>
                                  </table>
                               </td>
                            </tr>
                        </table>';
                        $this->utility->sendCIRenewMail($to,$sub,$bodys);
                        $this->utility->sendCIRenewMail('testdevloper007@gmail.com',$sub,$bodys);
                        $this->common_model->UpdateData('shop_orders',array('fail_reason'=>$error),array('order_id'=>$orderId));
    				}
                    

    				$detdata = $this->common_model->getAllRow('charge_card',array('cc_ref_id'=>$userDet['cc_ref_id']));
    				$con = array(
    							'amount'=>$data->order_data->total_sum ? $data->order_data->total_sum : 0,
    							'card'=>'',
    							'date'=>date('Y-m-d H:i:s',time()),
    							'cc_ref_id'=>0,
    							'payment_status'=>$status,
    							'error'=>$error,
    							'user_id'=>$data->user_id,
    					);
    				$this->common_model->insertData('charge_card',$con);
    				/********************10-11-2017*****************/

                    //print_r($paymentResult); die;
                    if($paymentResult['success']) {
                            $cart 	= $this->db->where('id', $cartId)
                                    ->get('shop_carts')
                                    ->result()[0];
                        $mailResult = $this->confirmOrder($cart, $orderData);
                        
                    } else {
                        print"<pre>";
                        var_dump('CC Details not valid Email Send');
                    }
                }

                $i++;

                if($i == 200)
                    break;
            }


        }

        print"<pre>";
        var_dump('DONE');
        exit;
    }



    public function _chargeSaferpayJson($user, $order) {

        /*********TEST*************/
        /*$CustomerId = 246934; 
        $TerminalId = 17951970; 
        $username = 'API_246934_23183450';
        $password = 'JsonApiPwd1_a8EpfvCy';*/
        /*********TEST*************/

        /*********LIVE*************/
        $CustomerId = 403547;
        $TerminalId = 17799239; 
        $username = 'API_403547_78643204';
        $password = 'JsonApiPwdAnexus1_a8EpfvCy';   
        /*********LIVE*************/

        /***********************Create Transaction Direct********************/
            $JSONObj  = '{
              "RequestHeader": {
                "SpecVersion": "1.10",
                "CustomerId": "'.$CustomerId.'",
                "RequestId": "aScdFewDSRFrfas2wsad3",
                "RetryIndicator": 0
              },
              "TerminalId": "'.$TerminalId.'",
              "Payment": {
                "Amount": {
                  "Value": "'.(int)$order->total_sum.'",
                  "CurrencyCode": "EUR"
                },
                "Description": "Renew Membership Order",
                "PayerNote": "Renew Membership Order"
              },
              "PaymentMeans": {
                "Alias": {
                  "Id": "'.$user->card_alias.'"
                }
              }
            }';

            //$url = 'https://test.saferpay.com/api/Payment/v1/Transaction/AuthorizeDirect';
            $url = 'https://www.saferpay.com/api/Payment/v1/Transaction/AuthorizeDirect';
            
            $JSONObj = json_decode($JSONObj);
            $curl = curl_init($url);
            curl_setopt($curl, CURLOPT_HEADER, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-type: application/json"));
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($JSONObj));
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
            $jsonResponse = curl_exec($curl);
            $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            if ( $status != 200 ) {
                if($status == 400) {
                    $fail_reason = 'Validation error';
                } elseif($status == 401) {
                    $fail_reason = 'Authentication of the request failed';
                } elseif($status == 402) {
                    $fail_reason = 'Requested action failed';
                } elseif($status == 403) {
                    $fail_reason = 'Access denied';
                } elseif($status == 406) {
                    $fail_reason = 'Not acceptable (wrong accept header)';
                } elseif($status == 415) {
                    $fail_reason = 'Unsupported media type (wrong content-type header)';
                } elseif($status == 500) {
                    $fail_reason = 'Internal error';
                }
                $errorresponse = json_decode($jsonResponse, true);
                if($errorresponse)
                {
                    if($errorresponse['ProcessorMessage'])
                    {
                        $fail_reason = $errorresponse['ProcessorMessage'];
                    }
                }
                mail('testdevloper007@gmail.com','new cron fail','today saferpay json api');
                $this->common_model->UpdateData('shop_orders',array('fail_reason'=>$fail_reason,'payment_method_id'=>13),array('cart_id'=>$order->cart_id));
                return array('error' => $fail_reason);
            }
            curl_close($curl);
            $transactionresponse = json_decode($jsonResponse, true);
            $this->common_model->UpdateData('shop_orders',array('real_name'=>$transactionresponse['PaymentMeans']['Card']['HolderName'], 'card_origin'=>$transactionresponse['PaymentMeans']['Card']['CountryCode']),array('cart_id'=>$order->cart_id));
            //echo "<pre>";
            //print_r($transactionresponse);die;
        /***********************Create Transaction Direct********************/


        /***********************Create Capture Direct********************/
            $JSONObj  = '{
              "RequestHeader": {
                "SpecVersion": "1.10",
                "CustomerId": "'.$CustomerId.'",
                "RequestId": "aScdFewDSRFrfas2wsad3",
                "RetryIndicator": 0
              },
              "TransactionReference": {
                "TransactionId": "'.$transactionresponse['Transaction']['Id'].'"
              }
            }';
            //echo $JSONObj;die;
            //$url = 'https://test.saferpay.com/api/Payment/v1/Transaction/Capture';
            $url = 'https://www.saferpay.com/api/Payment/v1/Transaction/Capture';
            
            $JSONObj = json_decode($JSONObj);
            $curl = curl_init($url);
            curl_setopt($curl, CURLOPT_HEADER, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_HTTPHEADER,array("Content-type: application/json"));
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($JSONObj));
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
            $jsonResponse = curl_exec($curl);
            $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            if ( $status != 200 ) {
                if($status == 400) {
                    $fail_reason = 'Validation error';
                } elseif($status == 401) {
                    $fail_reason = 'Authentication of the request failed';
                } elseif($status == 402) {
                    $fail_reason = 'Requested action failed';
                } elseif($status == 403) {
                    $fail_reason = 'Access denied';
                } elseif($status == 406) {
                    $fail_reason = 'Not acceptable (wrong accept header)';
                } elseif($status == 415) {
                    $fail_reason = 'Unsupported media type (wrong content-type header)';
                } elseif($status == 500) {
                    $fail_reason = 'Internal error';
                }
                $errorresponse = json_decode($jsonResponse, true);
                if($errorresponse)
                {
                    if($errorresponse['ProcessorMessage'])
                    {
                        $fail_reason = $errorresponse['ProcessorMessage'];
                    }
                }
                mail('testdevloper007@gmail.com','new cron fail','today saferpay json api');
                $this->common_model->UpdateData('shop_orders',array('fail_reason'=>$fail_reason,'payment_method_id'=>13),array('cart_id'=>$order->cart_id));
                return array('error' => $fail_reason);
            }
            curl_close($curl);
            $response = json_decode($jsonResponse, true);
            if($response)
            {
                $this->common_model->UpdateData('shop_orders',array('trn_id'=>$transactionresponse['Transaction']['Id'],'trn_capture_id'=>$response['CaptureId'],'is_renewed'=>1,'payment_method_id'=>13),array('cart_id'=>$order->cart_id));
                mail('testdevloper007@gmail.com','new saferpay json api success',$response['CaptureId']);
                return array('success' => 'transaction_complete');
            }
    }
    // END _chargeCreditCard()


    /**
     * Generiert aus einer Bestellung eine Rechnungs-PDF
     *
     * @param int $cartId ist die ID des Warenkorbs, der in eine Rechnung konvertiert werden soll
     * @param boolean $open wenn true, dann wird die Datei direkt geöffnet und nicht nur gespeichert
     */
    public function confirmOrder($cart, $order)
    {
        $cartDataset = array(
            'id' 		=> $cart->id,
            'ordered' 	=> 1
        );
        $this->common_model->UpdateData('shop_carts',array('ordered'=>1),array('id'=>$cart->id));
        // Bestellung als "bezahlt" markieren
        $orderDataset = array(
            'cart_id' 	=> $order->cart_id,
            'payed' 	=> 1
        );
        $this->common_model->UpdateData('shop_orders',array('payed'=>1),array('cart_id'=>$order->cart_id));
        //mail('testdevloper007@gmail.com','new cron confirm',$order->order_id_masked);
    
        return true;
    }
}