\!/ KyuuKazami \!/

Path : /home/kohli/public_html/application/controllers/
Upload :
Current File : /home/kohli/public_html/application/controllers/cart.php

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

class Cart extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->load->library("common_lib");
        $this->load->model('commonm');
    }	
     
    public function index(){
        $data = array();        
        $data['inner_template'] = "cart/cart";
        $this->load->view('layout/layout_main.php',$data);		
    }
    
    public function user_exist($str){
        return $this->common_lib->check_user_exist($str);		
    }
    
    public function email_exist($str){
        return $this->common_lib->check_email_exist($str);                
    }
    
    public function createprofile(){        
        if($this->common_lib->run_register_validation(true)){            
            $user_data = array();
            
            $username = $this->common_lib->get_post('rg_username',true);
            $password = $this->common_lib->get_post('rg_password',true);
            $password = $this->common_lib->one_way_encrypt($password);
            
            if($this->common_lib->get_n_post("rg_shipping_detail") == 1){
                $personal_fields = $this->common_lib->user_form_personal_fields(true);
            }else{
                $personal_fields = $this->common_lib->user_form_personal_fields();
            }
                                                            
            $user_data['is_active'] = 1;
            $user_data['username'] = $username;
            $user_data['password'] = $password;
            
            $user_data = array_merge($user_data,$personal_fields);
            
            $this->load->model('userm');
            $user_id = $this->userm->_insert($user_data);
            
            $sdata = array(							  
                        'sess_username' => $this->common_lib->encode($username),                              
			            'sess_uid' => $this->common_lib->encode($user_id),
                        'sess_display_name' => $this->common_lib->encode($personal_fields['first_name']),
			            'sess_lastlogin' => $data['lastlogin'],
                        'sess_signature' => $this->common_lib->encode($user_id.$username)
			);
            $this->common_lib->set_session($sdata);
            $this->userm->_update($user_id, time());
            redirect("cart/checkout");
            
        }else{            
            $this->common_lib->set_session(array("danger-msg" => validation_errors()));                                     
        }
    }
    
    public function update_shipping(){
        if($this->common_lib->run_shipping_validation()){
            $user_data = array();			
            $user_data = $this->common_lib->user_form_shipping_fields();            
            $this->load->model('userm');			
            $this->userm->_up_profile($this->common_lib->get_login_id(),$user_data);
            //$this->common_lib->set_session(array("success-msg" => "Shipping Detail updated successfully"));
            redirect("cart/checkout");            
        }else{            
            $this->common_lib->set_session(array("danger-msg" => validation_errors()));            
        }
    }
    
        public function update_order(){
        
        $payment_mode = $this->common_lib->get_post("checkout_payment_method");
        $bValidateCardInfo = false;
        if($payment_mode == "CC"){
            $checkout_credit_card_type = $this->common_lib->get_n_post("checkout_credit_card_type");
            $checkout_credit_card_number = $this->common_lib->get_n_post("checkout_credit_card_number");
            $checkout_cvv_number = $this->common_lib->get_n_post("checkout_cvv_number");
            $checkout_expiry_month = $this->common_lib->get_n_post("checkout_expiry_month");
            $checkout_expiry_year = $this->common_lib->get_n_post("checkout_expiry_year");
            $bValidateCardInfo = true;
        }
        if($bValidateCardInfo){
            //echo "A";exit;
        }
        if($this->common_lib->run_payment_validation($bValidateCardInfo)){
                                                            
            if($this->common_lib->get_session("current_order_id") > 0){
                $this->commonm->_delete_rows("order_items",array("order_id" => $this->common_lib->get_session("current_order_id")));
            }
            
           
            
            $user_login_detail = $this->common_lib->get_login_detail();
             
            if($bValidateCardInfo){
                 $total_amount = $this->common_lib->insert_update_order(); 
                $pazeey = false;
                $authorized = false;
                
                if($pazeey && false){
                    $this->load->library('payeezy');
                    
                    $card_holder_name = $user_login_detail['first_name'];
                    $card_number = $checkout_credit_card_number;
                    $card_type = "Visa";
                    $card_cvv = $checkout_cvv_number;
                    $card_expiry = $checkout_expiry_month.substr($checkout_expiry_year,-2);
                    $amount = $total_amount;
                    $currency_code = "USD";
                    $merchant_ref = "Astonishing-Sale";
                
                    $primaryTxPayload = array(
                        "amount"=> $amount,
                        "card_number" => $card_number,
                        "card_type" => $card_type,
                        "card_holder_name" => $card_holder_name,
                        "card_cvv" => $card_cvv,
                        "card_expiry" => $card_expiry,
                        "merchant_ref" => $merchant_ref,
                        "currency_code" => $currency_code,
                    );
                    
                    $credential['api_key'] = PZ_API_KEY;
                    $credential['token'] = PZ_TOKEN;
                    $credential['api_secret'] = PZ_API_SECRET;
                    $this->payeezy->initialize($credential,"sandbox");
                    $pz_res = $this->payeezy->processPayment($primaryTxPayload);
                                                            
                    $pz_res_arr = json_decode($pz_res);
                    
                    
                    $bank_code = $pz_res_arr->bank_resp_code;
                    $response_code = 0;
                    if($bank_code=="100" || $bank_code=="101" || $bank_code=="102" || $bank_code=="103" || $bank_code=="104" || $bank_code=="105" || $bank_code=="106" || $bank_code=="107" || $bank_code=="108" || $bank_code=="109" || $bank_code=="110" || $bank_code=="111" || $bank_code=="164"){
                        $payment_status = "D";
                        $authorization_code = $pz_res_arr->bank_resp_code;
                        $response_description = $pz_res_arr->bank_message;                        
                        $transaction_id = $pz_res_arr->transaction_id;
                        $response_code = 1;
                    }else{
                        $payment_status = "P";                        
                        $response_description = $pz_res_arr->Error->messages[0]->description;                        
                        
                        $response = 'Some error occured during transaction, Please try again! ('.$response_description.')';
    				    $payment_status = "P";
                    }
                    
                }
                if($authorized && false){
                $this->load->library('authorize_net');
    			$param['card_num']		= $checkout_credit_card_number;
    			$param['exp_date']		= $checkout_expiry_month.'/'.$checkout_expiry_year;
    			$param['desc']			= '';
    			$param['amount']		= $total_amount;
    			$param['first_name']	= $user_login_detail['first_name'];
    			$param['last_name']		= $user_login_detail['last_name'];
    			$param['address']		= $user_login_detail['address'];
    			$param['city']			= $user_login_detail['city'];
    			$param['state']			= $user_login_detail['punjab'];
    			$param['country']		= $user_login_detail['country'];
    			$param['zipcode']		= $user_login_detail['zipcode'];
    			$param['ip']			= $this->input->server("REMOTE_ADDR");
    			$param['order_id']		= $this->common_lib->get_session("current_order_id");
    			$param['user_id']		= $user_login_detail['user_id'];
    			$param['birth_month']	= '';
    			$param['birth_day']		= '';
    			$param['birth_year']	= '';
    			$param['code']			= $checkout_cvv_number;
    
    			$result				= $this->authorize_net->authorize($param);
                
    			$result_arr			= explode("|", $result);
                
                $response_code = $result_arr[0];// 1 = Approved, 2 = Declined, 3 = Error, 4 = Held for Review
    			$response_description = $result_arr[3];// Description
    			$transaction_id = $result_arr[6];// Transaction ID
    			$authorization_code = $result_arr[4];// Authorization Code
                
                }
             }   
               if($payment_mode == "PP"){
                     $this->load->library("paypal_lib");
                        $firstName = urlencode($user_login_detail['first_name']);
                        $creditCardType = urlencode($checkout_credit_card_type); //Visa
                        $creditCardNumber = base64_encode(urlencode($checkout_credit_card_number)); //4269344632025581
                        $expDateMonth = $checkout_expiry_month; //02
                        $padDateMonth = urlencode(str_pad($expDateMonth, 2, '0', STR_PAD_LEFT));
                        $expDateYear = urlencode($checkout_expiry_year); //2014
                        $cvv2Number = urlencode($checkout_credit_card_number); //962
                        $address1 = urlencode($user_login_detail['address']); //address1
                        $address2 = urlencode("address2"); //address2
                        $city = urlencode($user_login_detail['city']); //phagwara
                        $state = urlencode($user_login_detail['punjab']); //punjab 
                        $country = urlencode($user_login_detail['country']); //US // US or other valid country code
                         //100
                        $total_amount = $this->common_lib->convert_grand_total();
                        $currencyID = urlencode('USD');	
                        $price = urlencode($total_amount); // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
                        $prod_price = "";
                       
                        $ItemTotalPrice = ($price); //(Item Price x Quantity = Total) Get total amount of product; 
	
                    	//Other important variables like tax, shipping cost
                    	$TotalTaxAmount 	= 0.00;  //Sum of tax for all items in this order. 
                    	$HandalingCost 		= 0.00;  //Handling cost for this order.
                    	$InsuranceCost 		= 0.00;     
                          
                        //shipping insurance cost for this order.
                    	//$ShippinDiscount 	= -3.00; //Shipping discount for this order. Specify this as negative number.
                    	//$ShippinCost 		= 3.00; //Although you may change the value later, try to pass in a shipping amount that is reasonably accurate.
                    	
                    	//Grand total including all tax, insurance, shipping cost and discount
                    	//$GrandTotal = ($ItemTotalPrice + $TotalTaxAmount + $HandalingCost + $InsuranceCost + $ShippinCost + $ShippinDiscount);
                        
           	$GrandTotal = ($price + $TotalTaxAmount + $HandalingCost + $InsuranceCost);        
        	
            $PayPalReturnmonthlyURL = site_url('cart/paymentsuccess');
            $PayPalCancelURL = site_url('cart/checkout');
        	//Parameters for SetExpressCheckout, which will be sent to PayPal
        	$padata = 	'&METHOD=SetExpressCheckout'.
        				'&RETURNURL='.urlencode($PayPalReturnmonthlyURL ).
        				'&CANCELURL='.urlencode($PayPalCancelURL).
        				'&PAYMENTREQUEST_0_PAYMENTACTION='.urlencode("SALE").
        				
        				'&L_PAYMENTREQUEST_0_NAME0='.urlencode($firstname).
        				'&L_PAYMENTREQUEST_0_NUMBER0='.urlencode($this->common_lib->get_session("current_order_id")).
        				'&L_PAYMENTREQUEST_0_DESC0='.urlencode($address1).
        				'&L_PAYMENTREQUEST_0_AMT0='.urlencode($price).
                        
        				//'&L_PAYMENTREQUEST_0_QTY0='. urlencode($ItemQty).
        				
        				/* 
        				//Additional products (L_PAYMENTREQUEST_0_NAME0 becomes L_PAYMENTREQUEST_0_NAME1 and so on)
        				'&L_PAYMENTREQUEST_0_NAME1='.urlencode($ItemName2).
        				'&L_PAYMENTREQUEST_0_NUMBER1='.urlencode($ItemNumber2).
        				'&L_PAYMENTREQUEST_0_DESC1='.urlencode($ItemDesc2).
        				'&L_PAYMENTREQUEST_0_AMT1='.urlencode($ItemPrice2).
        				'&L_PAYMENTREQUEST_0_QTY1='. urlencode($ItemQty2).
        				*/
        				
        				/* 
        				//Override the buyer's shipping address stored on PayPal, The buyer cannot edit the overridden address.
        				'&ADDROVERRIDE=1'.
        				'&PAYMENTREQUEST_0_SHIPTONAME=J Smith'.
        				'&PAYMENTREQUEST_0_SHIPTOSTREET=1 Main St'.
        				'&PAYMENTREQUEST_0_SHIPTOCITY=San Jose'.
        				'&PAYMENTREQUEST_0_SHIPTOSTATE=CA'.
        				'&PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE=US'.
        				'&PAYMENTREQUEST_0_SHIPTOZIP=95131'.
        				'&PAYMENTREQUEST_0_SHIPTOPHONENUM=408-967-4444'.
        				*/
        				
        				'&NOSHIPPING=0'. //set 1 to hide buyer's shipping address, in-case products that does not require shipping
        				
        				'&PAYMENTREQUEST_0_ITEMAMT='.urlencode($ItemTotalPrice).
        				'&PAYMENTREQUEST_0_TAXAMT='.urlencode($TotalTaxAmount).
        				//'&PAYMENTREQUEST_0_SHIPPINGAMT='.urlencode($ShippinCost).
        				'&PAYMENTREQUEST_0_HANDLINGAMT='.urlencode($HandalingCost).
        			//	'&PAYMENTREQUEST_0_SHIPDISCAMT='.urlencode($ShippinDiscount).
        				'&PAYMENTREQUEST_0_INSURANCEAMT='.urlencode($InsuranceCost).
        				'&PAYMENTREQUEST_0_AMT='.urlencode($GrandTotal).
        				'&PAYMENTREQUEST_0_CURRENCYCODE='.urlencode($currencyID).
        				'&LOCALECODE=GB'. //PayPal pages to match the language on your website.
        				'&LOGOIMG='.$this->common_lib->get_site_logo(). //site logo
        				'&CARTBORDERCOLOR=FFFFFF'. //border color of cart
        				'&ALLOWNOTE=1';
        				
                        $PayPalMode = "live";
                        
                        $_SESSION['ItemName'] 			=  $firstName; //Item Name
        				$_SESSION['ItemPrice'] 			=  $price; //Item Price
        				$_SESSION['ItemNumber'] 		=  $this->common_lib->get_session("current_order_id"); //Item Number
        				$_SESSION['ItemDesc'] 			=  $address1; //Item Number
        				//$_SESSION['ItemQty'] 			=  $ItemQty; // Item Quantity
        				$_SESSION['ItemTotalPrice'] 	=  $ItemTotalPrice; //(Item Price x Quantity = Total) Get total amount of product; 
        				$_SESSION['TotalTaxAmount'] 	=  $TotalTaxAmount;  //Sum of tax for all items in this order. 
        				$_SESSION['HandalingCost'] 		=  $HandalingCost;  //Handling cost for this order.
        				$_SESSION['InsuranceCost'] 		=  $InsuranceCost;  //shipping insurance cost for this order.
        			//	$_SESSION['ShippinDiscount'] 	=  $ShippinDiscount; //Shipping discount for this order. Specify this as negative number.
        			//	$_SESSION['ShippinCost'] 		=   $ShippinCost; //Although you may change the value later, try to pass in a shipping amount that is reasonably accurate.
	             $this->common_lib->set_session(array("Grand_Total" => $GrandTotal));
        
                    		//We need to execute the "SetExpressCheckOut" method to obtain paypal token
            		
            	$httpParsedResponseAr = $this->PPHttpPost('SetExpressCheckout', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
             //   print_r($httpParsedResponseAr);
               // exit;
               
              
              }
               if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]))
    		      {
		          $paypalurl ='https://www'.$paypalmode.'.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token='.$httpParsedResponseAr["TOKEN"].'';
                    header('Location: '.$paypalurl);
			          exit;
        		}else{
        			//Show error message
                    $response = 'Some error occured during transaction, Please try again !'.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]);
    				$payment_status = "P";   
        		}
              
                  
             

            if($payment_status == "D" || $payment_mode == "COD" ||  $payment_mode == "PP"){
                redirect("cart/orderconfirmed");
                exit;    
            }else{
                $this->common_lib->set_session(array("danger-msg" => $response));    
            }                                   
            
        }else{
            $this->common_lib->set_session(array("danger-msg" => validation_errors()));
        }
        
    }
        
    public function update_coupon(){        
        $coupon_code = $this->common_lib->get_post("checkout_coupon_code");
        if($coupon_code != ""){
            $coupon_detail = $this->commonm->get_all("coupons",array("is_active" => 1));
            if(count($coupon_detail) == 0){
                $this->common_lib->set_session(array("danger-msg" => "Please enter valid coupon code!"));    
            }else{
                $coupon_detail = $coupon_detail[0];
                $discount_amount = $coupon_detail->discount_value; 
                if($coupon_detail->discount_percent == 1){
                    $cart_total = $this->cart->total();
                    $discount_amount = $this->common_lib->currency_price( ($coupon_detail->discount_value/100) * $cart_total);   
                }
                $this->common_lib->set_session(array("coupon_code" => $coupon_code));
                $this->common_lib->set_session(array("success-msg" => "Coupon Applied Successfully"));
            }            
        }else{            
            $this->common_lib->set_session(array("danger-msg" => "Please enter valid coupon code!"));
        }
    }
    
    
    public function checkout(){
        
        if($this->cart->total_items() == 0){
            redirect("cart");
            exit;
        }
        
        $this->common_lib->set_session(array("validation-1" => ""));
        $this->common_lib->set_session(array("validation-2" => ""));
        $this->common_lib->set_session(array("validation-3" => ""));
        $this->common_lib->set_session(array("validation-4" => ""));
        $this->common_lib->set_session(array("validation-5" => ""));
        
        if($this->common_lib->get_session("panel-mode") == ""){
            $this->common_lib->set_session(array("validation-1" => 1));
        }else{
            $this->common_lib->set_session(array($this->common_lib->get_session("panel-mode") => 1));                
        }                        
        
        if($this->common_lib->get_post("checkout_mode") == "registration"){
            $this->common_lib->set_session(array("validation-2" => 1));
            $this->common_lib->set_session(array("panel-mode" => "validation-2"));
            $this->createprofile();
        }
        
        if($this->common_lib->get_post("checkout_mode") == "profile_update"){
            $this->common_lib->set_session(array("validation-2" => 1));
            $this->common_lib->set_session(array("panel-mode" => "validation-2"));
            if($this->common_lib->run_profile_validation()){
                $user_data = array();			
                if($this->common_lib->get_n_post("rg_shipping_detail") == 1){
                    $user_data = $this->common_lib->user_form_personal_fields(true);
                }else{
                    $user_data = $this->common_lib->user_form_personal_fields();
                }
                $this->load->model('userm');			
                $this->userm->_up_profile($this->common_lib->get_login_id(),$user_data);                
            }else{
                $this->common_lib->set_session(array("danger-msg" => validation_errors()));                                            
            }
        }
        
        if($this->common_lib->get_post("checkout_mode") == "update_shipping"){
            $this->common_lib->set_session(array("validation-3" => "1"));
            $this->common_lib->set_session(array("panel-mode" => "validation-3"));
            $this->update_shipping();
        }
        
        if($this->common_lib->get_post("checkout_mode") == "update_shipping_method"){
                      
            $ups_shipping_service = $this->common_lib->get_post("ups_shipping_service");
            $ups_shipping_service = $this->common_lib->decode($ups_shipping_service);
            $ups_shipping_service = explode("~~",$ups_shipping_service);
            $this->common_lib->set_session(array("ups_shipping_price" => $ups_shipping_service[0]));
            $this->common_lib->set_session(array("ups_shipping_service" => $ups_shipping_service[1]));
            $this->common_lib->set_session(array("validation-4" => "1"));  
            $this->common_lib->set_session(array("panel-mode" => "validation-4"));
            redirect("cart/checkout");            
        }
        
        if($this->common_lib->get_post("checkout_mode") == "apply_coupon"){
            $this->common_lib->set_session(array("validation-4" => "1"));
            $this->common_lib->set_session(array("panel-mode" => "validation-4"));
            $this->update_coupon();                            
        }
        
        if($this->common_lib->get_post("checkout_mode") == "payment_process"){
            $this->common_lib->set_session(array("validation-4" => "1"));
            $this->common_lib->set_session(array("panel-mode" => "validation-4"));
            $this->update_order();                            
        }
        
        if($this->common_lib->get_post("checkout_mode") == "login"){
            $login_status = $this->common_lib->do_login("cart/checkout");
            if($login_status){
                $this->common_lib->set_session(array("validation-1" => 1));
                $this->common_lib->set_session(array("panel-mode" => "validation-1"));
            }            
        }
        $checkout_steps = array("login","");
        
	    $data = array();
        $user_login_detail = $this->common_lib->get_login_detail();
        $data['user_login_detail'] = $user_login_detail; 
        $data['country_list'] = $this->commonm->get_all("countries",array(),array(),"country");
        $data['inner_template'] = "cart/checkout";
        $this->load->view('layout/layout_main.php',$data);		
    }
    
    public function orderconfirmed(){
        $data = array();
        $order_id = $this->common_lib->get_session("current_order_id");
        if($order_id > 0){
            $user_login_detail = $this->common_lib->get_login_detail();
            $user_order_detail = $this->common_lib->get_order_summary($order_id);
            $data['user_order_detail'] = $user_order_detail;
            $order_detail_template = $this->common_lib->get_order_detail_template($order_id);
            $this->common_lib->clear_cart_session();
            $this->common_lib->send_order_email($order_id,$user_login_detail['email'],$order_detail_template);            
            $data['inner_template'] = "cart/orderconfirmed";
            $this->load->view('layout/layout_main.php',$data);
        }else{
            redirect("cart");
            exit;
        }
    }
    
    
    public function paymentsuccess(){
       $this->load->model('commonm');
          if(isset($_GET["token"]) && isset($_GET["PayerID"]))
            {
            	$token = $_GET["token"];
            	$payer_id = $_GET["PayerID"];
            	
            	//get session variables
            	$ItemName 			= $_SESSION['ItemName']; //Item Name
            	$ItemPrice 			= $_SESSION['ItemPrice'] ; //Item Price
            	$ItemNumber 		= $_SESSION['ItemNumber']; //Item Number
            	$ItemDesc 			= $_SESSION['ItemDesc']; //Item Number
            	//$ItemQty 			= $_SESSION['ItemQty']; // Item Quantity
            	$ItemTotalPrice 	= $_SESSION['ItemTotalPrice']; //(Item Price x Quantity = Total) Get total amount of product; 
            	$TotalTaxAmount 	= $_SESSION['TotalTaxAmount'] ;  //Sum of tax for all items in this order. 
            	$HandalingCost 		= $_SESSION['HandalingCost'];  //Handling cost for this order.
            	$InsuranceCost 		= $_SESSION['InsuranceCost'];  //shipping insurance cost for this order.
            //	$ShippinDiscount 	= $_SESSION['ShippinDiscount']; //Shipping discount for this order. Specify this as negative number.
            //	$ShippinCost 		= $_SESSION['ShippinCost']; //Although you may change the value later, try to pass in a shipping amount that is reasonably accurate.
            	$GrandTotal 		= $_SESSION['GrandTotal'];
                $PayPalCurrencyCode = urlencode('USD');
            	$padata = 	'&TOKEN='.urlencode($token).
            				'&PAYERID='.urlencode($payer_id).
            				'&PAYMENTREQUEST_0_PAYMENTACTION='.urlencode("SALE").
            				
            				//set item info here, otherwise we won't see product details later	
            				'&L_PAYMENTREQUEST_0_NAME0='.urlencode($ItemName).
            				'&L_PAYMENTREQUEST_0_NUMBER0='.urlencode($ItemNumber).
            				'&L_PAYMENTREQUEST_0_DESC0='.urlencode($ItemDesc).
            				'&L_PAYMENTREQUEST_0_AMT0='.urlencode($ItemPrice).
            				'&L_PAYMENTREQUEST_0_QTY0='. urlencode($ItemQty).
            
            				/* 
            				//Additional products (L_PAYMENTREQUEST_0_NAME0 becomes L_PAYMENTREQUEST_0_NAME1 and so on)
            				'&L_PAYMENTREQUEST_0_NAME1='.urlencode($ItemName2).
            				'&L_PAYMENTREQUEST_0_NUMBER1='.urlencode($ItemNumber2).
            				'&L_PAYMENTREQUEST_0_DESC1=Description text'.
            				'&L_PAYMENTREQUEST_0_AMT1='.urlencode($ItemPrice2).
            				'&L_PAYMENTREQUEST_0_QTY1='. urlencode($ItemQty2).
            				*/
                            
            				'&PAYMENTREQUEST_0_ITEMAMT='.urlencode($ItemTotalPrice).
            				'&PAYMENTREQUEST_0_TAXAMT='.urlencode($TotalTaxAmount).
            			//	'&PAYMENTREQUEST_0_SHIPPINGAMT='.urlencode($ShippinCost).
            				'&PAYMENTREQUEST_0_HANDLINGAMT='.urlencode($HandalingCost).
            			//	'&PAYMENTREQUEST_0_SHIPDISCAMT='.urlencode($ShippinDiscount).
            				'&PAYMENTREQUEST_0_INSURANCEAMT='.urlencode($InsuranceCost).
            				'&PAYMENTREQUEST_0_AMT='.urlencode($this->common_lib->get_session("Grand_Total")).
            				'&PAYMENTREQUEST_0_CURRENCYCODE='.urlencode($PayPalCurrencyCode);
            	
            	//We need to execute the "DoExpressCheckoutPayment" at this point to Receive payment from user.
            
            	$httpParsedResponseAr = $this->PPHttpPost('DoExpressCheckoutPayment', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);
            	
               // print_r($httpParsedResponseAr);
                //  exit; 
                   
                if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) 
                {
                        $payment_status = "D";                    
                        $order_data = array();                    
                        $order_data['payment_status'] = $payment_status;
                        $order_data['payment_desc'] =  urlencode($httpParsedResponseAr["L_SHORTMESSAGE0"]);
                        $order_data['transaction_id'] = urldecode($httpParsedResponseAr["PAYMENTINFO_0_TRANSACTIONID"]);
                
                         $this->commonm->db_update($order_data,"orders","order_id",$this->common_lib->get_session("current_order_id"));    
                         redirect("cart/orderconfirmed");
                    
                }
                else{
                    $payment_status == "F";
                    $order_data = array();                    
                    $order_data['payment_status'] = $payment_status;
                    $order_data['payment_desc'] =  urlencode($httpParsedResponseAr["L_SHORTMESSAGE0"]);
                    $response = 'Some error occured during transaction, Please try again !'.urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]." ");
                    $this->commonm->db_update($order_data,"orders","order_id",$this->common_lib->get_session("current_order_id"));
                    echo $this->common_lib->get_session("current_order_id");
                    echo $this->db->last_query;
                     $this->common_lib->set_session(array("danger-msg" => $response));    
                    redirect("cart/checkout");
                    
            	}
      
    }
    
 }
    
    
    	function PPHttpPost($methodName_, $nvpStr_, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode) {
	   
			// Set up your API credentials, PayPal end point, and API version.
           $api_username = "kohlicards_api1.yahoo.com";
           $api_password = "QBLV4QNB99BN376N";	
           $api_signature = "ANKBS4Huglqyo.--Mu7vmux6JcWbAnn80KdQOC41d9Tvd5hQEj7Sh6N9";
            
            //$api_username = "amanpreet.ask-facilitator_api1.gmail.com";
        	//$api_password = "849SYDCFGL457YVA";	
        	//$api_signature = "AzhFp2-kuah915eGtAlYwL2b7M2wAM4cut.gAVA4wYnZg1CNUOW8a4GN";
        	$API_UserName = urlencode($api_username);
        	$API_Password = urlencode($api_password);
        	$API_Signature = urlencode($api_signature);
       	//	$API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
        	$API_Endpoint = "https://api-3t".$paypalmode.".paypal.com/nvp";
            
            
        	if("sandbox" === $PayPalMode || "beta-sandbox" === $PayPalMode ){
        		$API_Endpoint = "https://api-3t.$PayPalMode.paypal.com/nvp";
            //    $API_Endpoint = "https://api-3t.sandbox.paypal.com/nvp";
        	}
            
                
		
			$version = urlencode('109.0');
		
			// Set the curl parameters.
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
			curl_setopt($ch, CURLOPT_VERBOSE, 1);
		
			// Turn off the server and peer verification (TrustManager Concept).
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_POST, 1);
		
			// Set the API operation, version, and API signature in the request.
			$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
		
			// Set the request as a POST FIELD for curl.
			curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
		
			// Get response from the server.
			$httpResponse = curl_exec($ch);
		
			if(!$httpResponse) {
				exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
			}
		
			// Extract the response details.
			$httpResponseAr = explode("&", $httpResponse);
		
			$httpParsedResponseAr = array();
			foreach ($httpResponseAr as $i => $value) {
				$tmpAr = explode("=", $value);
				if(sizeof($tmpAr) > 1) {
					$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
				}
			}
		
			if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
				exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
			}
		
		return $httpParsedResponseAr;
	}
    
     /*   function PPHttpPost($methodName_, $nvpStr_) {
        
        $environment = "live";
        $api_username = "kohlicards_api1.yahoo.com";
    	$api_password = "QBLV4QNB99BN376N";	
    	$api_signature = "ANKBS4Huglqyo.--Mu7vmux6JcWbAnn80KdQOC41d9Tvd5hQEj7Sh6N9";
    	$API_UserName = urlencode($api_username);
    	$API_Password = urlencode($api_password);
    	$API_Signature = urlencode($api_signature);
    	$API_Endpoint = "https://api-3t.paypal.com/nvp";
    	if("sandbox" === $environment || "beta-sandbox" === $environment ){
    		$API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
    	}
    	$version = urlencode('51.0');
    
    	// Set the curl parameters.
    	$ch = curl_init();
    	curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
    	curl_setopt($ch, CURLOPT_VERBOSE, 1);
    
    	// Turn off the server and peer verification (TrustManager Concept).
    	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    	curl_setopt($ch, CURLOPT_POST, 1);
    
    	// Set the API operation, version, and API signature in the request.
        $nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
    
    	// Set the request as a POST FIELD for curl.
    	curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
    
    	// Get response from the server.
    	$httpResponse = curl_exec($ch);
    
    	if(!$httpResponse) {
    		exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
    	}
    
    	// Extract the response details.
    	$httpResponseAr = explode("&", $httpResponse);
    
    	$httpParsedResponseAr = array();
    	foreach ($httpResponseAr as $i => $value) {
    		$tmpAr = explode("=", $value);
    		if(sizeof($tmpAr) > 1) {
    			$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
    		}
    	}
    
    	if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
    		exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
    	}
    
    	return $httpParsedResponseAr;
    }*/
    
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */

@KyuuKazami