<?php
/**
 * @filename        Quantum.php
 * @description     This class is for making payment through Quantum Gateway (Non-interactive method)
 * @version         1.0
 * @package         PaymentLibrary.classes
 * @author          Masuduzzaman
 *
 * @link
 * @created on      November 21, 2011
 * @Dependencies
 * @license
 ***/ 
  class WorldPayRealTime extends PaymentGateway
  {
  
      var $requesType = 'SALES';
 

      function WorldPayRealTime()
      {
	      parent::PaymentGateway();		  
          //$this->testURL = 'https://select-test.wp3.rbsworldpay.com/wcc/purchase';
		  $this->testURL = "https://secure-test.worldpay.com/wcc/purchase";
          $this->requestURL = 'https://secure.wp3.rbsworldpay.com/wcc/purchase';
          $this->supportedCurrencies = array('USD', 'EUR', 'GBP', 'CAD', 'JPY', 'AUD', 'ZAR');
		  
      }

      function initialize()
      {   
          $this->logMessage('Initializing basic parameters...');
          $this->setParam('gwlogin', $this->apiUserName);
          $this->setParam('RestrictKey', $this->apiKey);
          $this->setParam('amount', $this->amount);
      }

      function setCardParameters()
      {
          $this->logMessage('Initializing card parameters...');
          $this->setParam('ccnum', $this->cardNumber);
          $this->setParam('ccmo',str_pad($this->expiryMonth, 2, '0', STR_PAD_LEFT));
          $this->setParam('ccyr',$this->expiryYear);
      }

      function setBillingInformation()
      {
          $this->logMessage('Initializing billing parameters...');
          $this->setParam('FNAME', $this->firstName);
          $this->setParam('LNAME', $this->lastName);
          $this->setParam('BADDR1', trim($this->address1 . ' ' . $this->address2));
          $this->setParam('BCITY', $this->city);
          $this->setParam('BSTATE', $this->state);
          $this->setParam('BZIP1', $this->zip);
          $this->setParam('BCUST_EMAIL', $this->email);
      }

      function authorize()
      {   
		  $this->setParam('BCITY', $this->city);	
          $this->requesType = 'AUTH_ONLY';
          $this->logMessage('Setting parameters for authorize request...');
          $this->initialize();
          $this->setParam('trans_type','AUTH_ONLY');
          $this->setCardParameters();
          $this->setBillingInformation();
          $this->makeAPICall();
          return $this->response;
      }

      function capture()
      { 
          $this->logMessage('Preparing capture request...');
          $this->validateBasicInput();
          $this->validateTransactionID();

          if($this->response->hasError())
          {
              $this->logMessage('Error found...<br />' . $this->response->getErrorString('ul'));
              return $this->response;
          }

          $this->requesType = 'PREVIOUS_SALE';

          $this->logMessage('Setting parameters for capture request...');
          $this->initialize();
          $this->setParam('trans_type','PREVIOUS_SALE');
          $this->setParam('transID', $this->transactionId);

          $this->makeAPICall();
          return $this->response;
      }

      function sale()
      {
	   
	   $this->makeAPICall();
	   exit;
	      
          $this->logMessage('Preparing sale request...xxxx');
          $this->validateBasicInput();
          $this->validateCreditCardNumber();
          $this->validateExpiryDate();

          if($this->response->hasError())
          {
              $this->logMessage('Error found...<br />' . $this->response->getErrorString('ul'));
              return $this->response;
          }

          $this->requesType = 'SALES';
          $this->logMessage('Setting parameters for sale request...');
          $this->initialize();
          $this->setParam('trans_type','SALES');

          $this->setCardParameters();
          $this->setBillingInformation();
          $this->makeAPICall();
          return $this->response;
      }

      function refund()
      { //die('123');
          $this->logMessage('Preparing refund request...');
          $this->validateBasicInput();
          $this->validateCreditCardNumber();

          $this->validateTransactionID();

          if($this->response->hasError())
          {
              $this->logMessage('Error found...<br />' . $this->response->getErrorString('ul'));
              return $this->response;
          }

          $this->logMessage('Setting parameters for refund request...');
          $this->requesType = 'RETURN';
          $this->initialize();
          $this->setParam('trans_type','RETURN');
          $this->setCardParameters();
          $this->setParam('transID',$this->transactionId);
          $this->makeAPICall();
          return $this->response;
      }

      function prepareResponse()
      { //die('ppp123pp');
          if($this->response->rawResponse)
          {
              $responseArray = explode('|', $this->response->rawResponse);

              $status = trim($responseArray[0],'"');

              if($status=='APPROVED')
              {
                  $this->response->success = 1;
                  $this->response->ack = ACK_SUCCESS;
                  $this->response->authorizationId = trim($responseArray[1],'"');
                  $this->response->transactionId = trim($responseArray[2],'"');
              }
              else
              {
                  $this->response->ack = ACK_FAILURE;
                  $this->response->success = 0;
                  $error = !empty($responseArray[6]) ? trim($responseArray[6],'"') : (count($responseArray) == 1 ? trim($responseArray[0], '*') : 'The transaction has been declined');
                  $this->response->setError($error);
                  $this->response->responseCode = !empty($responseArray[7]) ? trim($responseArray[7],'"') : 0;
              }
          }
          else
          {
              $this->response->ack = ACK_FAILURE;
              $this->response->success = 0;
          }

          $this->response->invoiceNumber = $this->invoiceNumber;
          $this->response->transactionType = $this->requesType;
          $this->response->currency = $this->currencyCode;
      }

      /**
      *@desc Basic input validation
      */
      function validateBasicInput()
      { //die('basic');
          if(empty($this->apiUserName) || empty($this->apiKey) )
          {
              $this->response->setError('Quantum gateway login credentials have not been configured.');
          }

          $this->validateAmount();
      }
	  
	   function makeAPICall_bak()
      {
          $url = $this->getRequestURL();

          if(empty($url))
          {
              $this->logMessage('Request URL is missing.');
              $this->response->setError('Request URL has not been set');
          }

          if($this->response->hasError())
          {
              $this->logMessage('Request could not be made because of errors.');
              return;
          }

          $this->logMessage('Preparing request...');
          $this->prepareRequest();
		  $this->requestString ="region=Cambridgeshire&authAmountString=10&_SP.charEnc=UTF-8&
								desc=&tel=0870+366+1233&address1=WorldPay+Ltd&countryMatch=S&cartId=test&
								address2=270-289+The+Science+Park&address3=Milton+Road&lang=en&callbackPW=your_password&
								rawAuthCode=A&transStatus=Y&amountString=10&authCost=10.99&
								currency=GBP&installation=211616&amount=10&countryString=United+Kingdom&
								displayAddress=WorldPay+LtdA270-289+The+Science+ParkAMilton+RoadACambridge0ACambridgeshire&
								transTime=1331631533596&name=CARD+HOLDER&testMode=100&routeKey=VISA-SSL&
								ipAddress=62.249.232.76&fax=&rawAuthMessage=cardbe.msg.authorised&instId=211616&AVS=0001&
								compName=Admin+Company+Name&authAmount=10.99&postcode=CB4+0WE&cardType=Visa&
								cost=10.99&authCurrency=GBP&country=GB&charenc=UTF-8&email=support@worldpay.com&
								address=WorldPay+LtdA270-289+The+Science+ParkAMilton+RoadACambridgeACambridgeshire&
								transId=129170095&msgType=authResult&town=Cambridge&authMode=A";

          $this->logMessage($this->requestString);

          $this->logMessage('Initializing cURL...');
          $ch = curl_init();

          if($this->requestMethod == 'POST')
          {
              $this->logMessage('Sending Request to : ' . $url);
              curl_setopt($ch, CURLOPT_URL, $url);
              curl_setopt($ch, CURLOPT_POST, 1);
              curl_setopt($ch, CURLOPT_POSTFIELDS, $this->requestString);
          }
          else
          {
              $url .= $this->requestString; //the URL should contain '?' if it is needed
              $this->logMessage('Sending Request to : ' . $url);
              curl_setopt($ch, CURLOPT_URL, $url);
              curl_setopt($ch, CURLOPT_POST, 0);
          }

          if ($this->proxyHost && $this->proxyPort)
          {
              curl_setopt($ch, CURLOPT_PROXY, $this->proxyHost . ':' . $this->proxyPort);
          }

          if(!empty($this->sslCertificatate))
          {
              $this->logMessage('Using SSL Certificate...' . $this->sslCertificatate);
              curl_setopt ($ch, CURLOPT_SSLCERT, $this->sslCertificatate);
          }

          if(empty($this->headers))
          {
              $this->headers = array();
          }

          $this->headers[] = "Content-Length: " . strlen($this->requestString);
          curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);

          if($this->testMode)
          {
              curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
              curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
              $this->response->isTestMode = 1;
          }
          else if(!$this->verifiy_ssl)
          {
              $this->logMessage('SSL in not verified as using internet secure gateway');
              curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
              curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
          }
          else
          {
              curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
              curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
          }

          curl_setopt($ch,CURLOPT_USERAGENT, $this->userAgent);
          curl_setopt($ch, CURLOPT_TIMEOUT, 60);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
          curl_setopt($ch, CURLOPT_VERBOSE, ($this->debug ? 1 : 0));

          $this->logMessage('Getting response...');
          $this->response->setRawResponse(curl_exec($ch));

          $this->logMessage(urldecode($this->response->getRawResponse()));

          if (curl_errno($ch))
          {
              $this->response->curlErrorNo = curl_errno($ch);
              $this->response->curlErrorMessage = curl_error($ch);
              $error = 'cURL Error # ' . $this->response->curlErrorNo . ' : ' . $this->response->curlErrorMessage;

              $this->logMessage($error);

              if($this->showCurlError)
              {
                  $this->response->setError($error);
              }
          }
          else
          {
              curl_close($ch);
          }
          $this->logMessage('Preparing response...');
          $this->prepareResponse();

          $this->logMessage('Done...');
      }
	  
	function makeAPICall()
      {
	  
		  //$url = $this->getRequestURL();
		  $url = "https://UNSTOPPABLETM1:UTe8n7LJ@secure-test.bibit.com/jsp/merchant/xml/paymentService.jsp";		  
		  
          if(empty($url))
          {
              $this->logMessage('Request URL is missing.');
              $this->response->setError('Request URL has not been set');
          }

          if($this->response->hasError())
          {
              $this->logMessage('Request could not be made because of errors.');
              return;
          }

          $this->logMessage('Preparing request...');
          $this->prepareRequest();
		  /*$this->requestString = "<?xml version='1.0' encoding='UTF-8'?>
					<!DOCTYPE paymentService PUBLIC '-//Bibit//DTD Bibit PaymentService v1//EN' 'http://dtd.bibit.com/paymentService_v1.dtd'>
					<paymentService version='1.4' merchantCode='UNSTOPPABLETM1'>
					  <submit>
						<order orderCode = '13472793552'>
						  <description>ACME Webshops Int. Inc.</description>
						  <amount value='1982' currencyCode = 'USD' exponent = '2'/>
						  <orderContent>
							<![CDATA[<center><table>
					<tr><td bgcolor='#CCCCCC'>Your Internet Order:</td><td colspan='2' bgcolor='#ffff00' align='right'>845</td></tr>
					<tr><td bgcolor='#ffff00'>Description:</td><td>14 Tulip bulbs</td><td align='right'>1,00</td></tr>
					<tr><td colspan='2'>Subtotal:</td><td align='right'>14,00</td></tr>
					<tr><td colspan='2'>VAT: 13%</td><td align='right'>1,82</td></tr>
					<tr><td colspan='2'>Shipping and Handling:</td><td align='right'>4,00</td></tr>
					<tr><td colspan='2' bgcolor='#c0c0c0'>Total cost:</td><td bgcolor='#c0c0c0' align='right'>USD 19,82</td></tr>
					<tr><td colspan='3'>&nbsp;</td></tr>
					<tr><td bgcolor='#ffff00' colspan='3'>Your billing address:</td></tr>
					<tr><td colspan='3'>Mr. zaman,<br>11 Hereortherestreet,<br>1234 KL yourcity,<br>Thisplace.</td></tr>
					<tr><td colspan='3'>&nbsp;</td></tr>
					<tr><td bgcolor='#ffff00' colspan='3'>Your shipping address:</td></tr>
					<tr><td colspan='3'>Mr. zaman,<br>11 Hereortherestreet,<br>1234 KL yourcity,<br>Thisplace.</td></tr>
					<tr><td colspan='3'>&nbsp;</td></tr>
					<tr><td bgcolor='#ffff00' colspan='3'>Our contact information:</td></tr>
					<tr><td colspan='3'>ACME Webshops Int. Inc.,<br>11 Strangewood Blv.,<br>1255 KZ Thisisit,<br>Nowhereatall.<br><br>acmeweb@acme.inc<br>(555) 1235 456</td></tr>
					<tr><td colspan='3'>&nbsp;</td></tr>
					<tr><td bgcolor='#c0c0c0' colspan='3'>Billing notice:</td></tr>
					<tr><td colspan='3'>Your payment will be handled by Bibit Global Payments Services<br>This name may appear on your bank statement<br>http://www.bibit.com</td></tr>
					</table></center>]]>
						  </orderContent>
						  <paymentMethodMask>
							<include code='ALL'/>
						  </paymentMethodMask>      <shopper>
							<shopperEmailAddress>enggmasud1983@gmail.com</shopperEmailAddress>
						  </shopper>
						  <shippingAddress>
							<address>
							  <firstName>masud</firstName>
							  <lastName>zaman</lastName>
							  <street>11 Hereortherestreet</street>
							  <postalCode>1234 KL</postalCode>
							  <city>Camborne</city>
							  <countryCode>US</countryCode>
							  <telephoneNumber>123</telephoneNumber>
							</address>
						  </shippingAddress>
						</order>
					  </submit>
					</paymentService>";
					*/
					
	$this->requestString = "<?xml version='1.0' encoding='UTF-8'?>
							<!DOCTYPE paymentService PUBLIC '-//Bibit//DTD Bibit PaymentService v1//EN' 'http://dtd.bibit.com/paymentService_v1.dtd'>
							<paymentService version='1.4' merchantCode='UNSTOPPABLETM1'>
							  <submit>
								<order orderCode = '1347953033'>
								  <description>ACME Webshops Int. Inc.</description>
								  <amount value='1982' currencyCode = 'USD' exponent = '2'/>
								  <orderContent>
									<![CDATA[<center><table>
							<tr><td bgcolor='#CCCCCC'>Your Internet Order:</td><td colspan='2' bgcolor='#ffff00' align='right'>AY 845</td></tr>
							<tr><td bgcolor='#ffff00'>Description:</td><td>14 Tulip bulbs</td><td align='right'>1,00</td></tr>
							<tr><td colspan='2'>Subtotal:</td><td align='right'>14,00</td></tr>
							<tr><td colspan='2'>VAT: 13%</td><td align='right'>1,82</td></tr>
							<tr><td colspan='2'>Shipping and Handling:</td><td align='right'>4,00</td></tr>
							<tr><td colspan='2' bgcolor='#c0c0c0'>Total cost:</td><td bgcolor='#c0c0c0' align='right'>USD 19,82</td></tr>
							<tr><td colspan='3'>&nbsp;</td></tr>
							<tr><td bgcolor='#ffff00' colspan='3'>Your billing address:</td></tr>
							<tr><td colspan='3'>Mr. zaman,<br>32 Edward Street,<br>TR148PA Camborne,<br>Thisplace.</td></tr>
							<tr><td colspan='3'>&nbsp;</td></tr>
							<tr><td bgcolor='#ffff00' colspan='3'>Your shipping address:</td></tr>
							<tr><td colspan='3'>Mr. yourlastname,<br>32 Edward Street,<br>TR148PA Camborne,<br>Thisplace.</td></tr>
							<tr><td colspan='3'>&nbsp;</td></tr>
							<tr><td bgcolor='#ffff00' colspan='3'>Our contact information:</td></tr>
							<tr><td colspan='3'>ACME Webshops Int. Inc.,<br>11 Strangewood Blv.,<br>1255 KZ Thisisit,<br>Nowhereatall.<br><br>acmeweb@acme.inc<br>(555) 1235 456</td></tr>
							<tr><td colspan='3'>&nbsp;</td></tr>
							<tr><td bgcolor='#c0c0c0' colspan='3'>Billing notice:</td></tr>
							<tr><td colspan='3'>Your payment will be handled by Bibit Global Payments Services<br>This name may appear on your bank statement<br>http://www.bibit.com</td></tr>
							</table></center>]]>
								  </orderContent>
								  <paymentMethodMask>
									<include code='ALL'/>
								  </paymentMethodMask>      <shopper>
									<shopperEmailAddress>enggmasud1983@gmail.com</shopperEmailAddress>
								  </shopper>
								  <shippingAddress>
									<address>
									  <firstName>masud</firstName>
									  <lastName>zaman</lastName>
									  <street>32 Edward Street</street>
									  <postalCode>TR148PA</postalCode>
									  <city>Camborne</city>
									  <countryCode>US</countryCode>
									  <telephoneNumber>13123</telephoneNumber>
									</address>
								  </shippingAddress>
								</order>
							  </submit>
							</paymentService>";



		  echo $this->requestString; exit;					
          $this->logMessage($this->requestString);
          $this->logMessage('Initializing cURL...');
          $ch = curl_init();

          if($this->requestMethod == 'POST')
          {
              $this->logMessage('Sending Request to : ' . $url);
              curl_setopt($ch, CURLOPT_URL, $url);
              curl_setopt($ch, CURLOPT_POST, 1);
              curl_setopt($ch, CURLOPT_POSTFIELDS, $this->requestString);
          }
          else
          {
              $url .= $this->requestString; //the URL should contain '?' if it is needed
              $this->logMessage('Sending Request to : ' . $url);
              curl_setopt($ch, CURLOPT_URL, $url);
              curl_setopt($ch, CURLOPT_POST, 0);
          }

          if ($this->proxyHost && $this->proxyPort)
          {
              curl_setopt($ch, CURLOPT_PROXY, $this->proxyHost . ':' . $this->proxyPort);
          }

          if(!empty($this->sslCertificatate))
          {
              $this->logMessage('Using SSL Certificate...' . $this->sslCertificatate);
              curl_setopt ($ch, CURLOPT_SSLCERT, $this->sslCertificatate);
          }

          if(empty($this->headers))
          {
              $this->headers = array();
          }

          $this->headers[] = "Content-Length: " . strlen($this->requestString);
          curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);

          if($this->testMode)
          {
              curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
              curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
              $this->response->isTestMode = 1;
          }
          else if(!$this->verifiy_ssl)
          {
              $this->logMessage('SSL in not verified as using internet secure gateway');
              curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
              curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
          }
          else
          {
              curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
              curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
          }

          curl_setopt($ch,CURLOPT_USERAGENT, $this->userAgent);
          curl_setopt($ch, CURLOPT_TIMEOUT, 60);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
          curl_setopt($ch, CURLOPT_VERBOSE, ($this->debug ? 1 : 0));
			
			
          $this->logMessage('Getting response...');
          $this->response->setRawResponse(curl_exec($ch));

          $this->logMessage(urldecode($this->response->getRawResponse()));

          if (curl_errno($ch))
          {
              $this->response->curlErrorNo = curl_errno($ch);
              $this->response->curlErrorMessage = curl_error($ch);
              $error = 'cURL Error # ' . $this->response->curlErrorNo . ' : ' . $this->response->curlErrorMessage;

              $this->logMessage($error);

              if($this->showCurlError)
              {
                  $this->response->setError($error);
              }
          }
          else
          {
              curl_close($ch);
          }
          $this->logMessage('Preparing response...');
          $this->prepareResponse();

          $this->logMessage('Done...');
      }
  }
?>