<?php
class PaypalexprescheckoutModel extends PaymentModel
{
    public function process($order = '',$orderItems = '')
    {
		//echo '<pre>';print_r($order);exit;
		$ObjCurrency		= new CurrencyModel();
        parent::listPaymentSettingsValues($order['paymentSettingsGroupID']);
        $payAmount       	= $order['orderTotalAmount'];
        $paymentCurrency = $this->settingsVars["payment_currency"];
        $currencyArr     = '';
		$paymentCurrency			=	$this->settingsVars["payment_currency"];
		if ($paymentCurrency != '')
		{
			$paymentCurrency = str_replace(", ", ",", $paymentCurrency);
			$currencyArr     = explode(",", $paymentCurrency);
		}
		if(count($currencyArr)<1)
		{
			$this->isError 		= true;
			$this->errorMessage	= "Currency not configured , Please contact the site admin";
			return false;
		}
		else
		{
			$currencyFlag = false;
			$purchasedCurrencyDetails 	= $ObjCurrency->getCurrencyByCurrencyID($order["purchasedCurrency"]);
			$currencyCode				= $purchasedCurrencyDetails['currencyCode'];
			$systemCurrencies 			=	$ObjCurrency->listCurrencyCodes();
			if(!in_array($purchasedCurrencyDetails['currencyCode'],$currencyArr))
			{
				foreach ($systemCurrencies as $key => $currency)
				{
					if(in_array($currency['currencyCode'],$currencyArr))
					{
						$currencyFlag = true;
						$supportedCurrencyCode 	= $currency['currencyCode'];	
						$supportedCurrencyID 	= $currency['currencyID'];
						break;
					}
				}
				if($currencyFlag==true)
				{
                                    
					$payAmount              =       $ObjCurrency->convertValueCustom($payAmount,$order["purchasedCurrency"],$supportedCurrencyID);
					$currencyCode		=	$supportedCurrencyCode;
				}
				else
				{
					$this->isError 		= true;
					$this->errorMessage	= "Currency not configured , Please contact the site admin";
					return false;
				}
				
			}
		}
		
		if($payAmount<.01)
		{
			$this->isError 		= true;
			$this->errorMessage	= "Invalid amount , please use another method";
			return false;
		}
		
		if (!empty($orderItems))
        {
			$desc	= '';
            foreach ($orderItems as $key => $ordItem)
            {
                $orderGiveAsGift = '';
                if (isset($ordItem['orderGiveAsGift']) && $ordItem['orderGiveAsGift'] == 'Yes')
                {
                    $orderGiveAsGift = ' (As Gift)';
                }
                $fldName = ($order['orderType'] == 'product') ? 'productOptionName' : 'itemName';
                $desc .= "".urlencode(substr($ordItem[$fldName], 0, 110)) . $orderGiveAsGift . " Qty - ".
				number_format($ordItem['orderItemQuantity'], 2, ".", "") ."";
            }
        }
		$shipValue		= '';
        $paymentAmount 	= urlencode($payAmount);
        $currencyID    	= urlencode($currencyCode);
        $paymentType   	= urlencode($order['authValue']);
        $itemsArray   	= '';
        $itemAmount    	= 0;
        $returnURL     	= urlencode($order['returnURL']);
        $cancelURL     	= urlencode($order['cancelURL']);
        $siteDesc      	= urlencode($order['siteDesc']);
        $nvpStr        	= "&AMT=" . number_format($paymentAmount, 2, ".", "") . "&RETURNURL=$returnURL&LOCALECODE=US&CANCELURL=$cancelURL&PAYMENTACTION=$paymentType&DESC=" . $desc . "" . $shipValue . "&CURRENCYCODE=$currencyID&NOSHIPPING=1";	
							 	
        $API_UserName  = urlencode($this->settingsVars["payment_login"]);
        $API_Password  = urlencode($this->settingsVars["payment_login_password"]);
        $API_Signature = urlencode($this->settingsVars["payment_signature"]);
        $methodName_   = 'SetExpressCheckout';
        $nvpStr_       = $nvpStr;        
        if ($this->settingsVars["payment_test"] == 'On')
        {
            $environment = 'sandbox';
        }
        $API_Endpoint = $this->settingsVars["payment_gateway_url"];
        $version      = urlencode('51.0');
        $ch           = curl_init();
        curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        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);
        $nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
        curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
        $httpResponse = curl_exec($ch);
		
        if (!$httpResponse)
        {
            $this->errorMessage = curl_error($ch) . '(' . curl_errno($ch) . ')';
        }
        $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))
        {
            $this->isError      = true;
            $this->errorMessage = "Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.";
            return !$this->isError;
        }
        if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]))
        {
            $token     = urldecode($httpParsedResponseAr["TOKEN"]);
            $payPalURL = "https://www.paypal.com/webscr&cmd=_express-checkout&token=$token";
            if ("sandbox" === $environment || "beta-sandbox" === $environment)
            {
                $payPalURL = "https://www.$environment.paypal.com/webscr&cmd=_express-checkout&token=$token";
            }
            $this->isError      = false;
            $this->errorMessage = "";
            header("Location: $payPalURL");
            exit;
        }
        else
        {
            $this->isError = true;
            if (stripslashes($httpParsedResponseAr["L_SHORTMESSAGE0"]) == stripslashes($httpParsedResponseAr["L_LONGMESSAGE0"]))
                $this->errorMessage = stripslashes($httpParsedResponseAr["L_LONGMESSAGE0"]);
            else
                $this->errorMessage = stripslashes($httpParsedResponseAr["L_SHORTMESSAGE0"]) . ". " . stripslashes($httpParsedResponseAr["L_LONGMESSAGE0"]);
            return !$this->isError;
        }
    }
    public function processCustom($order = '')
    {
		$ObjCurrency			= new CurrencyModel();
        parent::listPaymentSettingsValues($order['paymentSettingsGroupID']);
		$getPaymentTransactionDetails = parent::getPaymentTransactionDetails(0,
		$order["masterOrderID"]);
		$purchasedCurrencyDetails = $ObjCurrency->getCurrencyByCurrencyID(
		$getPaymentTransactionDetails["paymentCurrencyID"]);
		$currencyCode			= $purchasedCurrencyDetails['currencyCode'];
		
        $this->isError                = false;
        //check is transaction completed
        if ($order["paymentType"] != "AUTH_ONLY" || $order["paymentStatus"] == 'Received')
        {
            $this->isError      = true;
            $this->errorMessage = "Transaction already completed";
            return false;
        }
        //get captured total amount & x_trans_id
		$capturedTotalAmount = $getPaymentTransactionDetails['convertedPaymentAmount'];
        $payAmount           = $capturedTotalAmount;
        $transactionID       = $getPaymentTransactionDetails["transactionID"];
        $version             = urlencode('51.0');
        $method        = 	"DoCapture";
        $nvpReq        = 	"METHOD=" . $method . "&AUTHORIZATIONID=" . urlencode($transactionID) . "&AMT=" . urlencode(number_format($payAmount, 2, ".", "")) . "&CURRENCYCODE=" . urlencode($currencyCode) . "&COMPLETETYPE=Complete";
							
							
        $API_UserName  = urlencode($this->settingsVars["payment_login"]);
        $API_Password  = urlencode($this->settingsVars["payment_login_password"]);
        $API_Signature = urlencode($this->settingsVars["payment_signature"]);
        $nvpReq .= "&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature";
        //post data to paypal
        $postUrl = trim($this->settingsVars["payment_gateway_url"]) == "" ? "https://api-3t.paypal.com/nvp" : trim($this->settingsVars["payment_gateway_url"]);
        $ch      = curl_init();
        curl_setopt($ch, CURLOPT_URL, $postUrl);
        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);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpReq);
        // getting response from server
        $httpResponse = curl_exec($ch);
        // Extract the RefundTransaction response details
        if (!empty($httpResponse))
        {
            $httpResponseAr = explode("&", $httpResponse);
        }
        $httpParsedResponseAr = array();
        foreach ($httpResponseAr as $i => $value)
        {
            $tmpAr = explode("=", $value);
            if (sizeof($tmpAr) > 1)
            {
                $httpParsedResponseAr[$tmpAr[0]] = urldecode($tmpAr[1]);
            }
        }
        if ($transactionID == $httpParsedResponseAr["AUTHORIZATIONID"])
        {
            $transactionID		= ($httpParsedResponseAr["TRANSACTIONID"] >0) ? $httpParsedResponseAr["TRANSACTIONID"] : $httpParsedResponseAr["AUTHORIZATIONID"];
            $paymentMethodName  = $this->settingsVars["payment_method_name"];
			
            parent::createTransaction($order, $transactionID, 
			"ORDER TYPE: PRIOR_AUTH_CAPTURE\n\n" . str_replace("~", "\n", $httpResponse),
			 "", "AUTH_CAPTURE", 0, $paymentMethodName,
			 $getPaymentTransactionDetails["paymentCurrencyID"],$payAmount);
            $this->isError      = false;
            $this->errorMessage = "";
            return "Success";
        }
        elseif ("Failure" == $httpParsedResponseAr["ACK"])
        {
            $this->isError = true;
            if (stripslashes($httpParsedResponseAr["L_SHORTMESSAGE0"]) == stripslashes($httpParsedResponseAr["L_LONGMESSAGE0"]))
                $this->errorMessage = stripslashes($httpParsedResponseAr["L_LONGMESSAGE0"]);
            else
                $this->errorMessage = stripslashes($httpParsedResponseAr["L_SHORTMESSAGE0"]) . ". " . stripslashes($httpParsedResponseAr["L_LONGMESSAGE0"]);
        }
        else
        {
            $this->isError      = true;
            $this->errorMessage = "Incorrect form params. Please contact site administartor.";
            //return false;
        }
        if ($this->isError)
        {
            $this->logStart();
            $this->log($httpResponse, $this->settingsVars["payment_processor_id"]);
            $this->logFinish();
            $this->isError = true;
        }
        return !$this->isError;
    }
    public function doExpressCheckout($token, $PayerID, $order = '', $postForm = '', $orderItems = '')
    {
		$ObjCurrency	= new CurrencyModel();
		$ObjCountry     = new CountryModel();
        parent::listPaymentSettingsValues($order['paymentSettingsGroupID']);
        $payediD         = $PayerID;
        $token           = $token;
        $payerID         = urlencode($payediD);
        $token           = urlencode($token);
        $paymentType     = urlencode($order['authValue']); // or 'Sale' or 'Order'
        $payAmount       = $order['orderTotalAmount'];
        $shippingAmount  = $order["shippingAmount"];
        $taxAmount       = $order["orderTaxAmount"];
        $serviceCharge   = $order["orderOtherServiceCharge"];
		$orderPromoDiscountAmount 	= $order["orderPromoDiscountAmount"];
		$orderUserCreditAmount 		= $order["orderUserCreditAmount"];
		$masterOrderSubtotal 		= $order["orderSubtotal"];
		$supportedCurrencyID		= $order["purchasedCurrency"];
		
        $paymentCurrency = $this->settingsVars["payment_currency"];
        $currencyArr     = '';
		if ($paymentCurrency != '')
		{
			$paymentCurrency = str_replace(", ", ",", $paymentCurrency);
			$currencyArr     = explode(",", $paymentCurrency);
		}
		if(count($currencyArr)<1)
		{
			$this->isError 		= true;
			$this->errorMessage	= "Currency not configured , Please contact the site admin";
			return false;
		}
		else
		{
			$currencyFlag = false;
			$purchasedCurrencyDetails 	= $ObjCurrency->getCurrencyByCurrencyID($order["purchasedCurrency"]);
			$currencyCode				= $purchasedCurrencyDetails['currencyCode'];
			$systemCurrencies 			=	$ObjCurrency->listCurrencyCodes();
			if(!in_array($purchasedCurrencyDetails['currencyCode'],$currencyArr))
			{
				foreach ($systemCurrencies as $key => $currency)
				{
					if(in_array($currency['currencyCode'],$currencyArr))
					{
						$currencyFlag = true;
						$supportedCurrencyCode 	= $currency['currencyCode'];	
						$supportedCurrencyID 	= $currency['currencyID'];
						break;
					}
				}
				if($currencyFlag==true)
				{
					$payAmount = $ObjCurrency->convertValueCustom($payAmount,$order["purchasedCurrency"],$supportedCurrencyID);
					$taxAmount = $ObjCurrency->convertValueCustom($taxAmount,$order["purchasedCurrency"],$supportedCurrencyID);
					$shippingAmount = $ObjCurrency->convertValueCustom($shippingAmount,$order["purchasedCurrency"],
					$supportedCurrencyID);
					$serviceCharge = $ObjCurrency->convertValueCustom($serviceCharge,$order["purchasedCurrency"],
					$supportedCurrencyID);
					$orderPromoDiscountAmount = $ObjCurrency->convertValueCustom($orderPromoDiscountAmount
					,$order["purchasedCurrency"],$supportedCurrencyID);
					$orderUserCreditAmount = $ObjCurrency->convertValueCustom($orderUserCreditAmount,$order["purchasedCurrency"],
					$supportedCurrencyID);
					$masterOrderSubtotal = $ObjCurrency->convertValueCustom($masterOrderSubtotal,$order["purchasedCurrency"],
					$supportedCurrencyID);
					
					$currencyCode		=	$supportedCurrencyCode;
				}
				else
				{
					$this->isError 		= true;
					$this->errorMessage	= "Currency not configured , Please contact the site admin";
					return false;
				}
				
			}
		}
        $currencyID    = urlencode($currencyCode);
        $paymentAmount = urlencode($payAmount);
        $itemsArray  = '';
        $itemAmount  = 0;
        $itemsAmount = 0;
        $key         = 0;
        $siteDesc   = urlencode($order['siteDesc']);
        // Add request-specific fields to the request string.		
		
		$countryCode             = $ObjCountry->getCountryCode($order['billingAddress']['billingCountry']);
		
        $nvpStr = 		"&TOKEN=$token&PAYERID=$payerID&PAYMENTACTION=$paymentType&AMT=" . number_format($paymentAmount, 2, ".", "") . "&CURRENCYCODE=$currencyID&DESC=" . $siteDesc . "&LOCALECODE=US&EMAIL=" . urlencode($order['billingAddress']['billingEmail']);
			
		//$nvpStr .= "&NOTIFYURL=".urlencode($postForm['notifyURL']);
        $methodName    = 'DoExpressCheckoutPayment';
        $API_UserName  = urlencode($this->settingsVars["payment_login"]);
        $API_Password  = urlencode($this->settingsVars["payment_login_password"]);
        $API_Signature = urlencode($this->settingsVars["payment_signature"]);
        if ($this->settingsVars["payment_test"] == 'On')
        {
            $environment = 'sandbox';
        }
        $API_Endpoint = $this->settingsVars["payment_gateway_url"];
        $version      = urlencode('51.0');
        // setting the curl parameters.
        $ch           = curl_init();
        curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        // Set the curl parameters.
        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.
		//echo $nvpreq;
        $httpResponse = curl_exec($ch);
		$this->writeToLogAction($httpResponse);
        if (!$httpResponse)
        {
            $this->errorMessage = 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))
        {
            $this->isError      = true;
            $this->errorMessage = "Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.";
        }
        if ($order['authValue'] == 'Authorization')
        {
            $authOnly = 'AUTH_ONLY';
        }
        else
        {
            $authOnly = 'AUTH_CAPTURE';
        }
        if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == 
		strtoupper($httpParsedResponseAr["ACK"]))
        {
            $transactionID 			= $httpParsedResponseAr["TRANSACTIONID"];
            $paymentMethodName    	= $this->settingsVars["payment_method_name"];
            parent::createTransaction($order, $transactionID, str_replace("~", "\n", 
			$httpResponse), "", $authOnly, 0, $paymentMethodName,
			$supportedCurrencyID,$payAmount);
            $this->isError      = false;
            $this->errorMessage = "";
            return "Pending";
        }
        else
        {
            $this->isError = true;
            if (stripslashes($httpParsedResponseAr["L_SHORTMESSAGE0"]) == stripslashes($httpParsedResponseAr["L_LONGMESSAGE0"]))
                $this->errorMessage = stripslashes($httpParsedResponseAr["L_LONGMESSAGE0"]);
            else
                $this->errorMessage = stripslashes($httpParsedResponseAr["L_SHORTMESSAGE0"]) . ". " . stripslashes($httpParsedResponseAr["L_LONGMESSAGE0"]);
        }
        if ($this->isError && $this->errorMessage != '')
        {
            parent::createTransactionError($order, $transactionID, "ORDER TYPE: PRIOR_AUTH_CAPTURE\n\n" . str_replace("~", "\n", $httpResponse), "", "AUTH_CAPTURE", $paymentGatewayCharge, $paymentMethodName);
        }
        return !$this->isError;
    }
    public function processRefund($order = '', $postValues = '')
    {
        $ObjRefund           	= new RefundModel();
        $masterOrderID       	= $postValues['masterOrderID'];
        $refundTransactionID 	= $postValues['keyRefundTransactionID'];
        $this->paySetGroupID 	= $postValues['paymentSettingsGroupID'];
        //Set request-specific fields.
        $transactionID       	= urlencode($postValues['apiPaymentTransactionID']);
        $refundType          	= urlencode('Partial'); // or 'Full'
        $amount					= number_format($order['orderTotalAmount'], 2, ".", ""); // required if Partial.
        $memo					= 'Order Refund - MASORDID-'.$order['orderNumber']; // required if Partial.
        $currencyID 		 	= urlencode('USD'); // or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
        //Add request-specific fields to the request string.
        $nvpStr     		 = "&TRANSACTIONID=$transactionID&REFUNDTYPE=$refundType"; // &CURRENCYCODE=$currencyID
        if (isset($memo))
        {
            $nvpStr .= "&NOTE=$memo";
        }
        if (strcasecmp($refundType, 'Partial') == 0)
        {
            if (!isset($amount))
            {
                $this->errorMessage = "Partial Refund Amount is not specified.";
            }
            else
            {
                $nvpStr = $nvpStr . "&AMT=$amount";
            }
            if (!isset($memo))
            {
                $this->errorMessage = "Partial Refund Memo is not specified.";
            }
        }
        // Execute the API operation; see the PPHttpPost function.
        $httpParsedResponseAr = $this->PPHttpPost('RefundTransaction', $nvpStr);
        if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"]))
        {
            foreach ($httpParsedResponseAr as $key => $val)
            {
                $arrXnResponse['refundResponse'] .= $key . '=' . $val . '&';
            }
            $arrXnResponse['transactionID']  = $httpParsedResponseAr["REFUNDTRANSACTIONID"];
            $arrXnResponse['refundResponse'] = urldecode(substr($arrXnResponse['refundResponse'], 0, -1));
			$arrXnResponse['refundResponse'] = str_replace('~','<br/>',$arrXnResponse['refundResponse']);
            $arrXnResponse['refundAmount']   = $httpParsedResponseAr["GROSSREFUNDAMT"];
            $resUpdateRefund                 = $ObjRefund->updateRefundTransaction('', $refundTransactionID, $arrXnResponse, $masterOrderID);
            $this->isError                   = false;
            $this->errorMessage              = "";
        }
        else
        {
            foreach ($httpParsedResponseAr as $key => $val)
            {
                $arrXnResponse['refundResponse'] .= $key . '=' . $val . '&';
            }
            $arrXnResponse['transactionID']  = '';
            $arrXnResponse['refundResponse'] = urldecode(substr($arrXnResponse['refundResponse'], 0, -1));
			$arrXnResponse['refundResponse'] = str_replace('~','<br/>',$arrXnResponse['refundResponse']);
            $arrXnResponse['refundAmount']   = '';
            $resUpdateRefund                 = $ObjRefund->updateRefundTransaction('',$refundTransactionID, $arrXnResponse,$masterOrderID);
            $this->isError                   = true;
            if (stripslashes($httpParsedResponseAr["L_SHORTMESSAGE0"]) == stripslashes($httpParsedResponseAr["L_LONGMESSAGE0"]))
                $this->errorMessage = stripslashes($httpParsedResponseAr["L_LONGMESSAGE0"]);
            else
                $this->errorMessage = stripslashes($httpParsedResponseAr["L_SHORTMESSAGE0"]) . ". " . stripslashes($httpParsedResponseAr["L_LONGMESSAGE0"]);
        }
        return !$this->isError;
    }
	
    public function PPHttpPost($methodName_, $nvpStr_)
    {
        parent::listPaymentSettingsValues($this->paySetGroupID);
        if ($this->settingsVars["payment_test"] == 'On')
        {
            $environment = 'sandbox'; // or 'beta-sandbox' or 'live'
        }
        //global $environment;
        // Set up your API credentials, PayPal end point, and API version.
        $API_UserName  = urlencode($this->settingsVars["payment_login"]);
        $API_Password  = urlencode($this->settingsVars["payment_login_password"]);
        $API_Signature = urlencode($this->settingsVars["payment_signature"]);
        $API_Endpoint  = trim($this->settingsVars["payment_gateway_url"]);
        $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)
        {
            $this->errorMessage = "$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))
        {
            $this->isError      = true;
            $this->errorMessage = "Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.";
        }
        return $httpParsedResponseAr;
    }
	
	public function writeToLogAction($httpResponse)
	{		
		$writeLog      = "###############################  " . date("d-M-Y H:i:s") . " From Model  ###############################\n";
		$writeLog .= "\n##########################################################################################\n";
		if (file_exists("testLogFile.txt"))
		{
			$writeLog.=print_r($httpResponse, TRUE);
			$Handle = fopen("testLogFile.txt", "a");
			fwrite($Handle, "\n" . $writeLog . "\n");
			fclose($Handle);
		}	
	}
}
