<?php
class Paypal_model extends CI_Model
{

	var $paymentTypeSale = 'Sale';

	var $paymentTypeAuthorization = 'Authorization';

	public function __construct()
	{
		parent::__construct();
		$this->load->config('paypal_config');
        log_ipn_message('PAYPAL EXPRESS CHECKOUT STARTED.');  
	}

	/**
	 * hash_call: Function to perform the API call to PayPal using API signature
	 *
	 * @param string $methodName is name of API  method
	 * @param string $nvpStr is nvp string
	 * @param int $merchant_row_id to get api information
	 * @return an associtive array containing the response from the server
	 */
	function hash_call ($methodName, $nvpStr, $APIInfo)
	{
		//setting the curl parameters.
		$ch = curl_init();
        
        if(!in_array($APIInfo->merchant_row_id, $this->config->item('test_accounts')))
           curl_setopt($ch, CURLOPT_URL, $this->config->item('API_ENDPOINT'));
        else
           curl_setopt($ch, CURLOPT_URL, 'https://api-3t.sandbox.paypal.com/nvp');
        
		curl_setopt($ch, CURLOPT_VERBOSE, 1);
		//turning 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);
		//if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
		//Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php
		if ($this->config->item('USE_PROXY'))
		{
			curl_setopt($ch, CURLOPT_PROXY, $this->config->item('PROXY_HOST') . ':' . $this->config->item('PROXY_PORT'));
		}
		//NVPRequest for submitting to server
		$nvpreq = 'METHOD=' . urlencode($methodName) . '&VERSION=' . urlencode($this->config->item('VERSION')) . '&PWD=' . urlencode($APIInfo->paypal_api_password) . '&USER=' . urlencode($APIInfo->paypal_api_user_name) . '&SIGNATURE=' . urlencode($APIInfo->paypal_api_signature) . $nvpStr;
		//$nvpreq = 'METHOD=' . urlencode ( $methodName ) . '&VERSION=' . urlencode ( $this->config->item ( 'VERSION' ) ) . '&PWD=' . urlencode ( $this->config->item('API_PASSWORD') ) . '&USER=' . urlencode ( $this->config->item('API_USERNAME') ) . '&SIGNATURE=' . urlencode ( $this->config->item('API_SIGNATURE') ) . $nvpStr;
		//setting the nvpreq as POST FIELD to curl
		curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
		//getting response from server
		$response = curl_exec($ch);
		//convrting NVPResponse to an Associative Array
		$nvpResArray = $this->deformatNVP($response);
		$nvpReqArray = $this->deformatNVP($nvpreq);
		$curlError['curl_error_no'] = '';
		$curlError['curl_error_msg'] = '';
		if (curl_errno($ch))
		{
			// moving to display page to display curl errors
			$curlError['curl_error_no'] = curl_errno($ch);
			$curlError['curl_error_msg'] = curl_error($ch);
		} else
		{
			//closing the curl
			curl_close($ch);
		}
		$result['request'] = $nvpReqArray;
		$result['nvpResArray'] = $nvpResArray;
		$result['curlError'] = $curlError;
		return $result;
	}

	/** This function will take NVPString and convert it to an Associative Array and it will decode the response.
	 * It is usefull to search for a particular key and displaying arrays.
	 * @nvpstr is NVPString.
	 * @nvpArray is Associative Array.
	 */
	function deformatNVP ($nvpstr)
	{
		$intial = 0;
		$nvpArray = array();
		while (strlen($nvpstr))
		{
			//postion of Key
			$keypos = strpos($nvpstr, '=');
			//position of value
			$valuepos = strpos($nvpstr, '&') ? strpos($nvpstr, '&') : strlen($nvpstr);
			//getting the Key and Value values and storing in a Associative Array
			$keyval = substr($nvpstr, $intial, $keypos);
			$valval = substr($nvpstr, $keypos + 1, $valuepos - $keypos - 1);
			//decoding the respose
			$nvpArray[urldecode($keyval)] = urldecode($valval);
			$nvpstr = substr($nvpstr, $valuepos + 1, strlen($nvpstr));
		}
		return $nvpArray;
	}

	/**
	 * do direct payment sale
	 *
	 * @param array $paymentInfo
	 * @return to doDirect payment method
	 */
	function doDirectPaymentSale ($paymentInfo)
	{
		return $this->doDirectPayment($paymentInfo, $this->paymentTypeSale);
	}

	function doDirectPaymentAuthorise ($paymentInfo)
	{
		return $this->doDirectPayment($paymentInfo, $this->paymentTypeAuthorization);
	}

	/**
	 * Do the transaction get two arguments
	 *
	 * @param array $paymentInfo
	 * @param string $paymentType
	 * @return array
	 */
	function doDirectPayment ($paymentInfo, $paymentType)
	{
		$getInstance = &get_instance();
		$getInstance->load->model('carts/Cart_Setup_model', 'Cart_Setup_model', TRUE);
		$APIInfo = $getInstance->Cart_Setup_model->getGatewaySetup($paymentInfo['merchant_row_id']);
		$paymentType = urlencode($paymentType);
		$currencyCode = $paymentInfo['currencyCodeType'];
		$firstName = urlencode($paymentInfo['first_name']);
		$lastName = urlencode($paymentInfo['last_name']);
		$creditCardType = urlencode($paymentInfo['card_type']);
		$creditCardNumber = urlencode($paymentInfo['card_number']);
		// Month must be padded with leading zero
		$expDateMonth = urlencode(str_pad($paymentInfo['expiration_month'], 2, '0', STR_PAD_LEFT));
		$expDateYear = urlencode($paymentInfo['expiration_year']);
		$address1 = urlencode($paymentInfo['address_1']);
		$address2 = urlencode($paymentInfo['address_2']);
		$city = urlencode($paymentInfo['city']);
		$state = urlencode($paymentInfo['state']);
		$zip = urlencode($paymentInfo['zip_code']);
		$amount = urlencode($paymentInfo['amount']);
		// Construct the request string that will be sent to PayPal.
		// The variable $nvpstr contains all the variables and is a
		// name value pair string with & as a delimiter
		$nvpstr = '&PAYMENTACTION=' . $paymentType . '&AMT=' . $amount . '&CREDITCARDTYPE=' . $creditCardType . '&ACCT=' . $creditCardNumber . '&EXPDATE=' . $expDateMonth . $expDateYear . '&FIRSTNAME=' . $firstName . '&LASTNAME=' . $lastName . '&STREET=' . $address1 . ' ' . $address2 . '&CITY=' . $city . '&STATE=' . $state . '&ZIP=' . $zip . '&COUNTRYCODE=US' . '&CURRENCYCODE=' . $currencyCode;
		// Make the API call to PayPal, using API signature.
		// The API response is stored in an associative array called $resArray
		$res = $this->hash_call('doDirectPayment', $nvpstr, $APIInfo);
		$resArray = $this->prepareDoDirectPaymentResponse($res['nvpResArray'], $res['curlError']);
		$result['request'] = $res['request'];
		$result['response'] = $resArray;

		$ack = strtoupper($resArray['ack']);

		// Display the API response back to the browser.
		// If the response from PayPal was a success, display the response parameters'
		// If the response was an error, display the errors received using APIError.php.

		if ($ack == 'SUCCESS')
		{
			$result['response']['success'] = 1;
		} else
		{
			$result['response']['success'] = 0;
		}
		return $result;
	}

	function prepareDoDirectPaymentResponse ($data, $curlError)
	{
		$response['curl_error_number'] = $curlError['curl_error_no'];
		$response['curl_error_message'] = $curlError['curl_error_msg'];
		$response['ack'] = $data['ACK'];
		$response['correlation_id'] = isset($data['CORRELATIONID']) ? $data['CORRELATIONID'] : '';
		$response['version'] = isset($data['VERSION']) ? $data['VERSION'] : '';
		$response['transaction_id'] = isset($data['TRANSACTIONID']) ? $data['TRANSACTIONID'] : '';
		$response['amount'] = isset($data['AMT']) ? $data['AMT'] : '';
		$response['avs_code'] = isset($data['AVSCODE']) ? $data['AVSCODE'] : '';
		#$response['cvv2_match'] = isset($data['CVV2MATCH']) ? $data['CVV2MATCH'] : '';
		$response['error_text'] = '';
		if ($response['curl_error_number'] && $response['curl_error_message'])
		{
			$response['error_text'] .= $response['curl_error_number'] . ': ' . $response['curl_error_message'] . '<br/>';
		}
		$count = 0;
		while (isset($data['L_SHORTMESSAGE' . $count]))
		{
			$error['error_code'] = $data['L_ERRORCODE' . $count];
			$error['short_message'] = $data['L_SHORTMESSAGE' . $count];
			$error['long_message'] = $data['L_LONGMESSAGE' . $count];
			$response['error_text'] .= $error['error_code'] . ': ' . $error['short_message'] . '(' . $error['long_message'] . ')<br/>';
			$count ++;
		}
		return $response;
	}

	function doCapture ($info)
	{
		$authorizationId = urlencode($info['authorization_id']);
		$completeCodeType = urlencode($info['complete_code_type']);
		$amount = urlencode($info['amount']);
		#$invoiceID = urlencode($info['invoice_id']);
		$currency = urlencode($info['currency']);
		$note = urlencode($info['note']);
		// Construct the request string that will be sent to PayPal.
		// The variable $nvpstr contains all the variables and is a
		// name value pair string with & as a delimiter
		$nvpStr = '&AUTHORIZATIONID=' . $authorizationId . '&AMT=' . $amount . '&COMPLETETYPE=' . $completeCodeType . '&CURRENCYCODE=' . $currency . '&NOTE=' . $note;
		// Make the API call to PayPal, using API signature.
		// The API response is stored in an associative array called $resArray
		$res = $this->hash_call('DOCapture', $nvpStr);
		// Next, collect the API request in the associative array $reqArray
		// as well to display back to the browser.
		// Normally you wouldnt not need to do this, but its shown for testing
		$resArray = $res['nvpResArray'];
		$result['request'] = $res['request'];
		$result['response'] = $this->prepareDoCaptureResponse($resArray, $result['curlError']);
		// Display the API response back to the browser.
		// If the response from PayPal was a success, display the response parameters'
		// If the response was an error, display the errors received using APIError.php.
		$ack = strtoupper($resArray['ack']);
		if ($ack == 'SUCCESS')
		{
			$result['response']['success'] = 1;
		} else
		{
			$result['response']['success'] = 0;
		}
		return $result;
	}

	function prepareDoCaptureResponse ($data, $curlError)
	{
		$response['curl_error_number'] = $curlError['curl_error_no'];
		$response['curl_error_message'] = $curlError['curl_error_msg'];
		$response['ack'] = $data['ACK'];
		$response['correlation_id'] = isset($data['CORRELATIONID']) ? $data['CORRELATIONID'] : '';
		$response['version'] = isset($data['VERSION']) ? $data['VERSION'] : '';
		$response['transaction_id'] = isset($data['TRANSACTIONID']) ? $data['TRANSACTIONID'] : '';
		$response['amount'] = isset($data['AMT']) ? $data['AMT'] : '';
		$response['error_text'] = '';
		if ($response['curl_error_number'] && $response['curl_error_message'])
		{
			$response['error_text'] .= $response['curl_error_number'] . ': ' . $response['curl_error_message'] . '<br/>';
		}
		$count = 0;
		while (isset($data['L_SHORTMESSAGE' . $count]))
		{
			$error['error_code'] = $data['L_ERRORCODE' . $count];
			$error['short_message'] = $data['L_SHORTMESSAGE' . $count];
			$error['long_message'] = $data['L_LONGMESSAGE' . $count];
			$response['error_text'] .= $error['error_code'] . ': ' . $error['short_message'] . '(' . $error['long_message'] . ')<br/>';
			$count ++;
		}
		return $response;
	}

	function setExpressCheckout ($tempOrderRowId, $totalAmount, $currencyCode, $merchantRowId)
	{
		$returnURL = urlencode(BASEURL.'paymentMethods/payment_utility/setExpressCheckoutSaleWithToken/' . $tempOrderRowId . '/' . $merchantRowId);
        $cancelURL = urlencode(BASEURL.'cancel_express_payment.php?oid='.$tempOrderRowId . '&cancel=1');

		$getInstance = &get_instance();
        $apiInfo = $this->Cart_Setup_model->getGatewaySetup($merchantRowId);  
		$nvpstr .= "&Amt=" . $totalAmount . "&PAYMENTACTION=" . $this->paymentTypeSale . "&RETURNURL=" . $returnURL . "&CANCELURL=" . $cancelURL . "&CURRENCYCODE=" . $currencyCode;

        $orderTempList = $this->Shopping_Cart_model->getTempOrderDetails($tempOrderRowId); 
        foreach($orderTempList as $key => $item)
        {
            if($item->recurring_profile_row_id)
            {
                 $nvpstr .= "&L_BILLINGTYPE{$key}=RecurringPayments&L_BILLINGAGREEMENTDESCRIPTION{$key}=" . urlencode($item->product_desc);
            }
        }
		$resArray = $this->hash_call("SetExpressCheckout", $nvpstr, $apiInfo);
        
        

		$_SESSION['reshash'] = $resArray;
		$ack = strtoupper($resArray["nvpResArray"]["ACK"]);
		if ($ack == "SUCCESS")
		{
			// Redirect to paypal.com here
			$token = urldecode($resArray["nvpResArray"]["TOKEN"]);
            if(!in_array($merchantRowId, $this->config->item('test_accounts')))
               $payPalURL = $this->config->item('PAYPAL_URL') . $token;
            else 
               $payPalURL = 'https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=' . $token;
			header('Location: ' . $payPalURL);
		} 
        else
		{
           exception($resArray['nvpResArray']['L_SHORTMESSAGE0'] . '<br />' . $resArray['nvpResArray']['L_LONGMESSAGE0']); 
           redirect('carts/shopping_cart/showCart/' . $tempOrderRowId); 
		}
	}

    function getExpressCheckoutDetails($tempOrderRowId, $merchantRowId, $token)
    {
        $apiInfo = $this->Cart_Setup_model->getGatewaySetup($merchantRowId);   
        $token = urlencode($token); 
        $nvpstr = "&TOKEN=" . $token;
        $resArray = $this->hash_call("GetExpressCheckoutDetails", $nvpstr, $apiInfo);
        $_SESSION['reshash'] = $resArray;
        $ack = strtoupper($resArray["nvpResArray"]["ACK"]);
        log_general(print_r($resArray ,1));
        if ($ack == "SUCCESS")
        {
           $orderRowId = $this->saveExpressCheckoutOrder($tempOrderRowId);
           $_SESSION['express_order_token_' . $orderRowId] = urldecode($token);
           redirect('paymentMethods/payment_utility/showExpressCheckout/' . $orderRowId);
        }   
        else                                                   
        {
           exception($resArray['nvpResArray']['L_SHORTMESSAGE0'] . '<br />' . $resArray['nvpResArray']['L_LONGMESSAGE0']); 
           redirect('carts/shopping_cart/showCart/' . $tempOrderRowId); 
        }
    }
    
    function saveExpressCheckoutOrder($tempOrderRowId)
    {
        $getInstance = &get_instance();
        $getInstance->load->model('portal/User_model', 'User_model', TRUE);
        $getInstance->load->model('orders/Order_model', 'Order_model', TRUE);
        $getInstance->load->model('carts/Shopping_cart_model', 'Shopping_Cart_model', true);
        $getInstance->load->model('customers/Customer_Setup_model', 'Customer_Setup_model', TRUE);
        $getInstance->load->model('Gift_Certificate_model', '', true);

        $tempOrder = $getInstance ->Shopping_Cart_model->getTempOrder($tempOrderRowId);

        $customer['merchant_row_id'] = $tempOrder->merchant_row_id;
        $customer['shipping_info']   = 1;
        $customer['first_name'] = $_SESSION['reshash']['nvpResArray']['FIRSTNAME'];
        $customer['last_name']  = $_SESSION['reshash']['nvpResArray']['LASTNAME'];
        $customer['customer_email'] = $_SESSION['reshash']['nvpResArray']['EMAIL'];
        $customer['country'] = $_SESSION['reshash']['nvpResArray']['COUNTRYCODE'];
        $customer['address_line1'] = $_SESSION['reshash']['nvpResArray']['SHIPTOSTREET'];
        $customer['customer_city'] = $_SESSION['reshash']['nvpResArray']['SHIPTOCITY'];
        $customer['customer_state'] = $_SESSION['reshash']['nvpResArray']['SHIPTOSTATE'];
        $customer['customer_zip'] = $_SESSION['reshash']['nvpResArray']['SHIPTOZIP'];

        $customer['shipping_name'] = $customer['first_name'] . ' ' . $customer['last_name'];
        $customer['shipping_address_line1'] = $_SESSION['reshash']['nvpResArray']['SHIPTOSTREET'];
        $customer['shipping_customer_city'] = $_SESSION['reshash']['nvpResArray']['SHIPTOCITY'];
        $customer['shipping_customer_state'] = $_SESSION['reshash']['nvpResArray']['SHIPTOSTATE'];
        $customer['shipping_customer_zip'] = $_SESSION['reshash']['nvpResArray']['SHIPTOZIP'];
        $customer['shipping_country'] = $_SESSION['reshash']['nvpResArray']['SHIPTOCOUNTRYCODE'];

        $userData = $getInstance->User_model->checkValidUser ( $customer['customer_email'], $tempOrder->merchant_row_id );

        if(!$userData)
        {
           $customerId = $getInstance->Customer_Setup_model->saveCustomer($customer);
           //$this->saveCustomerIdInCookie($customerId);
        }
        else
        {
           $customerId = $userData->customer_id;
           /*
           if($userData->visibility == 0 && $data['visibility'])
               $this->Customer_Setup_model->updateVisibility($customer_id);
           
           $this->saveCustomerIdInCookie($customerId);
           */
        }
        $totalAmount = $tempOrder->total_price
                    - $tempOrder->order_discount
                    + $tempOrder->country_tax
                    + $tempOrder->state_tax
                    + $tempOrder->shpping_amount
                    - $tempOrder->coupon_discount
                    - $tempOrder->quantity_discount - $tempOrder->quantity_discount_no_tax
                    - $tempOrder->gift_certificate_payment;
        $totalAmount = round($totalAmount, 2);

        $order_data = $customer;
        $order_data['appliedCoupons'] = $getInstance->Shopping_Cart_model->getAppliedCouponsOfCart($tempOrderRowId);
        $order_data['appliedGiftCertificates'] = $getInstance->Gift_Certificate_model->getAppliedGiftCertificatesTemp($tempOrderRowId);
        $order_data['orderTempList'] = $getInstance->Shopping_Cart_model->getTempOrderDetails($tempOrderRowId);
        $order_data['shpping_amount'] = $tempOrder->shpping_amount;
        $order_data['shipping_id'] = $tempOrder->shipping_id;
        $order_data['method_name'] = $tempOrder->method_name;
        $order_data['shipping_service'] = $tempOrder->shipping_service;
        $order_data['shipping_info'] = $getInstance->Customer_Setup_model->getCurrentShippingAddress($customerId);
        $order_data['shipping_info']->country = $order_data['country'];
        $order_data['shipping_info_check'] = 1;
        $order_data['shipping_info']->shipping_address_line1 = $order_data['shipping_address_line1'];
        $order_data['shipping_info']->shipping_customer_city = $order_data['shipping_customer_city'];
        $order_data['shipping_info']->shipping_customer_state = $order_data['shipping_customer_state'];
        $order_data['shipping_info']->shipping_customer_zip = $order_data['shipping_customer_zip'];
        $order_data['shipping_info']->shipping_country = $order_data['shipping_country'];

        $order_data['customer_id'] = $customerId;
        $order_data['order_temp_id'] = $tempOrderRowId;
        $order_data['merchant_row_id'] = $tempOrder->merchant_row_id;
        $order_data['from_ip_address'] = $this->input->ip_address();
        $order_data['browser_details'] = $this->input->user_agent();
        $order_data['order_status']  = $this->config->item('cos_pending_num');
        $order_data['charge_status'] = $this->config->item('ccs_charge_pending_num');
        //Anjuman | D:06152012
        //$order_data['quantity_discount'] = $quantity_discount;
        //End of : Anjuman
        $order_data['card_type'] = 'paypal_express';
        $order_data['product_total'] = $tempOrder->total_price;
        $order_data['total_price']   = $totalAmount;
        $order_data['order_discount'] = $tempOrder->order_discount;
        $order_data['country_tax'] = $tempOrder->country_tax;
        $order_data['state_tax'] = $tempOrder->state_tax;
        $order_data['plexum_user_id'] = $tempOrder->plexum_user_id;
        $order_data['coupon_discount'] = $tempOrder->coupon_discount;
        $order_data['gift_certificate_payment'] = $tempOrder->gift_certificate_payment;
        $order_data['post_order_row_id'] = $tempOrder->post_order_row_id;
        $order_data['app_id'] = $tempOrder->app_id;
        $order_data['order_discount_type'] = $this->input->post('order_discount_type');
        $order_data['order_process_model'] = $this->config->item('order_process_paypal_express');
        $getInstance->Shopping_Cart_model->removeOrderTemp($tempOrderRowId);
        $orderRowId = $_SESSION['process_payment_ord_id'] = $getInstance->Order_model->saveOrder($order_data);
        return $orderRowId;
        
    }

	function doExpressCheckout ($orderRowId, $total_amount, $currencyCodeType)
	{
		$apiInfo = $this->getMerchantAPIInformation($orderRowId);
		$getInstance = &get_instance();
        $getInstance->load->model('scheduleJob/Recurring_Payment_model', 'Recurring_Payment_model', TRUE);
        $getInstance->load->model('orders/Order_model', 'Order_model', TRUE);
        $order = $getInstance->Order_model->getOrderByRowId($orderRowId);
        /**
         * set shipping information with transaction
         */
		/* Gather the information to make the final call to
		   finalize the PayPal payment.  The variable nvpstr
		   holds the name value pairs
	   */
		$token = urlencode($_SESSION['reshash']['nvpResArray']['TOKEN']);
		$payerID = urlencode($_SESSION['reshash']['nvpResArray']['PAYERID']);
		$paymentAmount = urlencode($total_amount);
		$paymentType = urlencode($this->paymentTypeSale);
		$currCodeType = urlencode($currencyCodeType);
		$serverName = urlencode($_SERVER['SERVER_NAME']);
		$nvpstr .= '&TOKEN=' . $token . '&PAYERID=' . $payerID . '&PAYMENTACTION=' . $paymentType . '&AMT=' . $paymentAmount . '&CURRENCYCODE=' . $currCodeType . '&IPADDRESS=' . $serverName . '&BUTTONSOURCE=PremiumWebCartInc_Cart_EC&NOTIFYURL=' . BASEURL . 'paymentMethods/payment_utility/getNotification/' . $order->merchant_row_id . '/' . $order->order_row_id . '/' . $order->customer_id . '.html&CUSTOM=' . $order->merchant_row_id . '|' . $order->order_row_id . '|' . $order->customer_id;
        log_ipn_message('PAYPAL EXPRESS DoExpressCheckoutPayment: ' . $nvpstr);
		/* Make the call to PayPal to finalize payment
		If an error occured, show the resulting errors
		*/
		$resArray = $this->hash_call("DoExpressCheckoutPayment", $nvpstr, $apiInfo);
		/* Display the API response back to the browser.
	    If the response from PayPal was a success, display the response parameters'
	    If the response was an error, display the errors received using APIError.php.
	    */
		$ack = strtoupper($resArray["nvpResArray"]["ACK"]);
        $paymentDetails['order_row_id'] = $orderRowId;
        $paymentDetails['customer_id']  = $order->customer_id;
        $paymentDetails['merchant_row_id'] = $order->merchant_row_id;
		$paymentDetails['reason_code']  = $resArray['nvpResArray']['REASONCODE'];
		$paymentDetails['payment_status'] = $resArray['nvpResArray']['PAYMENTSTATUS'];
		$paymentDetails['pending_reason'] = $resArray['nvpResArray']['PENDINGREASON'];
		$paymentDetails['amount'] = $resArray['nvpResArray']['AMT'];
		$paymentDetails['curl_error_number'] = $resArray['curlError']['curl_error_no'];
		$paymentDetails['curl_error_message'] = addslashes($resArray['curlError']['curl_error_msg']);
		$paymentDetails['ack'] = $resArray['nvpResArray']['ACK'];
		$paymentDetails['correlation_id'] = $resArray['nvpResArray']['CORRELATIONID'];
		$paymentDetails['version'] = $resArray['nvpResArray']['VERSION'];
		$paymentDetails['transaction_id'] = $resArray['nvpResArray']['TRANSACTIONID'];
		$paymentDetails['transaction_type'] = $resArray['nvpResArray']['TRANSACTIONTYPE'];
		$paymentDetails['success'] = ($ack=='SUCCESS')?1:0;
		$paymentDetails['error_text'] = addslashes($resArray['curlError']['curl_error_msg']);
		//$paymentDetails['payment_gateway'] = $this->config->item('payment_gateway_paypal');
        $paymentDetails['payment_gateway'] = $this->config->item('payment_gateway_paypal_website_payment_pro');
        $getInstance->Recurring_Payment_model->savePaymentDetails($paymentDetails);
		$_SESSION['reshash'] = $resArray;
		$_SESSION['paymentDetails'] = $paymentDetails;

		if ($ack == "SUCCESS")
			redirect('paymentMethods/payment_utility/paymentSuccess/' . $orderRowId);
        else
			redirect('paymentMethods/payment_utility/paymentAPIError/' . $orderRowId);
	}

    /**
    * @desc refund transaction to the client paypal account or credit card
    */

    function refundTransaction($paymentInfo,$orderRowId){

        $transaction_id=urlencode($paymentInfo['transactionID']);
        $refundType=urlencode($paymentInfo['refundType']);
        $amount=urlencode($paymentInfo['amount']);
        $currency=urlencode($paymentInfo['currency']);
        $memo=urlencode($paymentInfo['memo']);

        /* Construct the request string that will be sent to PayPal.
        The variable $nvpstr contains all the variables and is a
        name value pair string with & as a delimiter */

        $nvpStr='&TRANSACTIONID='.$transaction_id.'&REFUNDTYPE='.$refundType.'&CURRENCYCODE='.$currency.'&NOTE='.$memo;
        if(strtoupper($refundType)=="PARTIAL")
        {
            $nvpStr = $nvpStr.'&AMT='.$amount;
        }

        $apiInfo = $this->getMerchantAPIInformation($orderRowId);

        /* Make the API call to PayPal, using API signature.
        The API response is stored in an associative array called $resArray */
        $resArray=$this->hash_call("RefundTransaction",$nvpStr,$apiInfo);

        /* Next, collect the API request in the associative array $reqArray
        as well to display back to the browser.
        Normally you wouldnt not need to do this, but its shown for testing */

        #$reqArray=$_SESSION['nvpReqArray'];


        /* Display the API response back to the browser.
        If the response from PayPal was a success, display the response parameters'
        If the response was an error, display the errors received using APIError.php.
        */
        #strtoupper($resArray["ACK"]);
		return $resArray;
		//if()
        /*if($ack!="SUCCESS"){
            $_SESSION['reshash']=$resArray;
            $location = "APIError.php";
            header("Location: $location");
        }*/
    }

    function merchantRefundTransaction($paymentInfo,$admin_gateway_row_id)
    {
    	$transaction_id=urlencode($paymentInfo['transactionID']);
        $refundType=urlencode($paymentInfo['refundType']);
        $amount=urlencode($paymentInfo['amount']);
        $currency=urlencode($paymentInfo['currency']);
        $memo=urlencode($paymentInfo['memo']);

        /* Construct the request string that will be sent to PayPal.
        The variable $nvpstr contains all the variables and is a
        name value pair string with & as a delimiter */

        $nvpStr='&TRANSACTIONID='.$transaction_id.'&REFUNDTYPE='.$refundType.'&CURRENCYCODE='.$currency.'&NOTE='.$memo;
        if(strtoupper($refundType)=="PARTIAL")
        {
            $nvpStr = $nvpStr.'&AMT='.$amount;
        }

        $apiInfo = $this->getMerchantAPIInformationUsingAdminGatewayRowId($admin_gateway_row_id);

        /* Make the API call to PayPal, using API signature.
        The API response is stored in an associative array called $resArray */
        $resArray=$this->hash_call("RefundTransaction",$nvpStr,$apiInfo);

        /* Next, collect the API request in the associative array $reqArray
        as well to display back to the browser.
        Normally you wouldnt not need to do this, but its shown for testing */

        #$reqArray=$_SESSION['nvpReqArray'];


        /* Display the API response back to the browser.
        If the response from PayPal was a success, display the response parameters'
        If the response was an error, display the errors received using APIError.php.
        */
        #strtoupper($resArray["ACK"]);
		return $resArray;
		//if()
        /*if($ack!="SUCCESS"){
            $_SESSION['reshash']=$resArray;
            $location = "APIError.php";
            header("Location: $location");
        }*/
    }

    /**
     *
     *
     * $paymentInfo array should be contains the following values
     * 		emailSubject 			--	email subject for paypal (required)
     * 		receiverType 			--	value should be static "EmailAddress" (required)
     * 		receiverEmail[](array) 	--	email addresses array (required)
     * 		receiverAmount[](array)	-- 	should be contains receiver amount respective to email address
     * 		uniqueID[](optional)	--	Transaction-specific identification number for tracking in an
     * 									accounting system.Character length and limitations: 30 single-byte
     * 									characters. No whitespace allowed. (required)
     *		note[](optional)		-- 	Custom note for each recipient. Character length and limitations:
     * 									4,000 single-byte alphanumeric characters
     * @param array $paymentInfo
     * @param string $currencyCodeType
     */

    function masspayTransaction($paymentInfo, $currencyCodeType)
    {
	    /**
	 	* Get required parameters from the web form for the request
	 	*/
		$emailSubject =urlencode($paymentInfo['emailSubject']);
		$receiverType = urlencode($paymentInfo['receiverType']);
		$currency=urlencode($currencyCodeType);

		$nvpstr = '';

		$count= count($paymentInfo['receiverEmail']);

		for($i=0,$j=0;$i<$count;$i++) {
			if (isset($paymentInfo['receiverEmail'][$i]) && $paymentInfo['receiverEmail'][$i]!='' ) {
					$receiverEmail = urlencode($paymentInfo['receiverEmail'][$i]);
					$amount = urlencode($paymentInfo['receiverAmount'][$i]);
					$uniqueID = urlencode($paymentInfo['uniqueID'][$i]);
					$note = urlencode($paymentInfo['note'][$i]);
					$nvpstr.='&L_EMAIL'.$j.'='.$receiverEmail.'&L_Amt'.$j.'='.$amount.'&L_UNIQUEID'.$j.'='.$uniqueID.'&L_NOTE'.$j.'='.$note;
					$j++;
			}
		}

		/* Construct the request string that will be sent to PayPal.
   		The variable $nvpstr contains all the variables and is a
   		name value pair string with & as a delimiter */

		$nvpstr.='&EMAILSUBJECT='.$emailSubject.'&RECEIVERTYPE='.$receiverType.'&CURRENCYCODE='.$currency ;

		$getInstance = &get_instance();
		$getInstance->load->model('carts/Cart_Setup_model', 'Cart_Setup_model', TRUE);
		$APIInfo = $getInstance->Cart_Setup_model->getGatewaySetup(getCurrentMerchantId());

		/* Make the API call to PayPal, using API signature.
   		The API response is stored in an associative array called $resArray */

		$resArray=$this->hash_call('MassPay',$nvpstr,$APIInfo);

		/* Display the API response back to the browser.
		   If the response from PayPal was a success, display the response parameters'
		   If the response was an error, display the errors received using APIError.php.
		   */

		/*$ack = strtoupper($resArray["ACK"]);

		if($ack!="SUCCESS")
		{
				$_SESSION['reshash']=$resArray;
				$location = "APIError.php";
				header("Location: $location");
		} */
		return  $resArray;
    }

	/**
	 * return merchant api information by order_row_id
	 *
	 * @param $orderRowId
	 * @return merchant_row_id
	 */
	function getMerchantAPIInformation ($orderRowId)
	{
		$getInstance = &get_instance();
		$getInstance->load->model('orders/Order_model', 'Order_model', TRUE);
		$getInstance->load->model('carts/Cart_Setup_model', 'Cart_Setup_model', TRUE);
		$orderInfo = $getInstance->Order_model->getOrderByRowId($orderRowId);
		$APIInfo = $getInstance->Cart_Setup_model->getGatewaySetup($orderInfo->merchant_row_id);   
		return $APIInfo;
	}

	function getMerchantAPIInformationUsingAdminGatewayRowId($admin_gateway_row_id)
	{
		$getInstance = &get_instance();
		$getInstance->load->model('administration/Admin_user_model', 'Admin_user_model', TRUE);
		$APIInfo = $getInstance->Admin_user_model->getAdminGatewaySetup($admin_gateway_row_id);
		return $APIInfo;
	}
}
?>