<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Renew_payment extends CI_Controller {
	public function __construct(){
		parent::__construct();
		$this->load->model('common_model');
		$this->load->model('users_model');
		if(get_cookie('admin_id'))
		{
			$this->session->set_userdata('admin_id',get_cookie('admin_id'));
		}
		if(!$this->session->userdata('admin_id'))
		{
			redirect('admin/login');
		}
	}
	public function payment($enc_userID='')
	{
		if($enc_userID)
		{
			$order_id = base64_decode($enc_userID);
			$userdetails = $this->common_model->getAllRowMultipleJoin('usr_users',array('order_id'=>$order_id),array(array('shop_carts','shop_carts.user_id = usr_users.id'),array('shop_orders','shop_orders.cart_id = shop_carts.id')),'shop_orders.created DESC','*,usr_users.id as user_id');
            if(!$userdetails['card_alias']){
                $this->utility->setMsg('User does not have Saferpay card reference','ERROR');   
                redirect(base_url().'admin/order/view/'.$enc_userID);
            }
			//pr($userdetails);
			/*********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)$userdetails['total_sum'].'",
                  "CurrencyCode": "EUR"
                },
                "Description": "Renew Membership Order",
                "PayerNote": "Renew Membership Order"
              },
              "PaymentMeans": {
                "Alias": {
                  "Id": "'.$userdetails['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'];
                    }
                }
                $this->utility->setMsg($fail_reason,'ERROR');	
				redirect(base_url().'admin/order/view/'.$enc_userID);
            }
            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('order_id'=>$order_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'];
                    }
                }
                $this->utility->setMsg($fail_reason,'ERROR');	
				redirect(base_url().'admin/order/view/'.$enc_userID);
            }
            curl_close($curl);
            $response = json_decode($jsonResponse, true);
            if($response)
            {
                $this->common_model->UpdateData('shop_orders',array('trn_id'=>$response['CaptureId'],'is_renewed'=>1,'payment_method_id'=>13),array('order_id'=>$order_id));
            }
			  
			//echo "<pre>";
		    //print_r($response);
            //pr($userdetails);  
			/***********************Create Capture Direct********************/
			if($response)
			{
				
				$this->common_model->UpdateData('shop_orders',array('payed'=>1,'trn_id'=>$response['CaptureId'],'payment_method_id'=>13,'payment_date'=>date('Y-m-d'),'fail_reason'=>''),array('order_id'=>$order_id));

                $namedetails = $this->common_model->getAllRow('feu_userdetails',array('user_id'=>$userdetails['user_id']));  

                $renew_orders = $this->common_model->getAll('shop_orders',array('invoiceAddress'=>$userdetails['email'],'is_renewed'=>1, 'payed'=>0));
                if(count($renew_orders)==0){
                    $this->common_model->deleteData('feu_user_steps',array('user_id'=>$userdetails['user_id']));
                }
                
				
				
				$to = $userdetails['email'];
				$sub = getLang('Membership_Invoice_mail_from').' Castleevents';
				//$body= '<p>Dear '.$userData['username'].',</p>';
				$body= '<p>'.getLang('We_have_received_your_payment').'!</p>';
				$body.= '<p>'.getLang('Invoice_Number').': CE-'.$order_id.'</p><p>'.getLang('Generated_On').': '.date('Y-m-d',time()).'</p><p>'.getLang('Paid_Amount').': '.number_format(($userdetails['total_sum']/100),2, '.', '').' EUR</p>';
				$body.= '<p>'.getLang('Invoice_will_be_located').' www.castleevents.com.</p>';
				$body.= '<p>'.getLang('We_appreciate_very_much').'.</p>';
				$body.= '<p>'.getLang('Please_do_not_hesitate_to_contact').'.</p>';
				//$body.= '<p>Best regards,</p><p>Your Castleevents Team </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">'.$namedetails['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->sendOrderMail($to,$sub,$bodys);
			}
        }
		$this->utility->setMsg('Charged successfully','SUCCESS');	
		redirect(base_url().'admin/order/view/'.$enc_userID);

	}
}
