<?php
/**
 * @filename        Payleap.php
 * @description     This class is for making payment through Payleap
 * @version         1.0
 * @package         PaymentLibrary.classes
 * @author          Masuduzzaman
 *
 * @link
 * @created on      April 26, 2012
 * @Dependencies
 * @license
 ***/
  class BeanstreamMobile extends PaymentGateway
  {
      var $requesType = 'SALE';

      function BeanstreamMobile()
      {
          parent::PaymentGateway();
          $headers = array(
            "Content-type: application/xml;charset=\"utf-16\"",
            "Accept: application/xml",
            "Cache-Control: no-cache",
            "Pragma: no-cache"
         );
         $this->appendHeaderLength = FALSE;
         $this->setHeaders($headers);
         $this->supportedCurrencies = array('USD', 'EUR', 'GBP', 'CAD', 'JPY', 'AUD', 'ZAR');
      }

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

      function getSessionId()
      {
        $this->requestURL = 'https://www.beanstream.com/scripts/usersession/createsession.aspx';
        $this->testURL = 'https://www.beanstream.com/scripts/usersession/createsession.aspx';

        $xml = new DOMDocument("1.0","UTF-8");
        $xml->preserveWhiteSpace = false;
        $xml->formatOutput = true;
        $AuthorizeRequest = $xml->createElement('request');

        $companyName = $xml->createElement('companyName', $this->apiSignature);
        $AuthorizeRequest->appendChild($companyName);

        $password = $xml->createElement('password', $this->apiKey);
        $AuthorizeRequest->appendChild($password);

        $sessionSource = $xml->createElement('sessionSource', 'Mobile');
        $AuthorizeRequest->appendChild($sessionSource);

        $userName = $xml->createElement('userName', $this->apiUserName);
        $AuthorizeRequest->appendChild($userName);

        $xml->appendChild($AuthorizeRequest);
        $this->requestString = $xml->saveXML();
        $this->makeAPICall();
        return $this->response;
      }

      function sale()
      {
        $this->getSessionId();
        $sessionId = $this->response->authorizationId;
        $merchantId = $this->response->invoiceNumber;
        $this->requestURL = 'https://www.beanstream.com/scripts/process_transaction.aspx';
        $this->testURL = 'https://www.beanstream.com/scripts/process_transaction.aspx';
        $xml = new DOMDocument("1.0","UTF-8");
        $xml->preserveWhiteSpace = false;
        $xml->formatOutput = true;
        $AuthorizeRequest = $xml->createElement('request');
        $serviceVersion = $xml->createElement('serviceVersion', '1.3');
        $AuthorizeRequest->appendChild($serviceVersion);
        $merchantId = $xml->createElement('merchant_id', $merchantId);
        $AuthorizeRequest->appendChild($merchantId);
        $sessionId = $xml->createElement('sessionId', $sessionId);
        $AuthorizeRequest->appendChild($sessionId);
        $trnType = $xml->createElement('trnType', 'P');
        $AuthorizeRequest->appendChild($trnType);
        $trnTrackData = $xml->createElement('trnTrackData', $this->magData);
        $AuthorizeRequest->appendChild($trnTrackData);
        $trnTrackFormat = $xml->createElement('trnTrackFormat', '1');
        $AuthorizeRequest->appendChild($trnTrackFormat);
        $trnAmount = $xml->createElement('trnAmount', $this->amount);
        $AuthorizeRequest->appendChild($trnAmount);
        $xml->appendChild($AuthorizeRequest);
        $this->requestString = $xml->saveXML();
        $this->makeAPICall();
      }

      function refund()
      {
        $this->getSessionId();
        $sessionId = $this->response->authorizationId;
        $merchantId = $this->response->invoiceNumber;
        $this->requestURL = 'https://www.beanstream.com/scripts/process_transaction.aspx';
        $this->testURL = 'https://www.beanstream.com/scripts/process_transaction.aspx';
        $xml = new DOMDocument("1.0","UTF-8");
        $xml->preserveWhiteSpace = false;
        $xml->formatOutput = true;
        $AuthorizeRequest = $xml->createElement('request');
        $serviceVersion = $xml->createElement('serviceVersion', '1.3');
        $AuthorizeRequest->appendChild($serviceVersion);

        $merchantId = $xml->createElement('merchant_id', $merchantId);
        $AuthorizeRequest->appendChild($merchantId);

        $sessionId = $xml->createElement('sessionId', $sessionId);
        $AuthorizeRequest->appendChild($sessionId);

        $sessionSource = $xml->createElement('sessionSource', 'mobile');
        $AuthorizeRequest->appendChild($sessionSource);

        $trnType = $xml->createElement('trnType', 'R');
        $AuthorizeRequest->appendChild($trnType);

        $trnTrackData = $xml->createElement('adjId', $this->transactionId ); //transactionId
        $AuthorizeRequest->appendChild($trnTrackData);

        $trnAmount = $xml->createElement('trnAmount', $this->amount);
        $AuthorizeRequest->appendChild($trnAmount);

        $xml->appendChild($AuthorizeRequest);
        $this->requestString = $xml->saveXML();
        $this->makeAPICall();
      }

       function prepareResponse() {

        $rawResponse = $this->response->getRawResponse();
        $xml = new DOMDocument();
        if($xml->loadXML($this->response->getRawResponse())){
              $responseValues = array();
                   foreach($xml->childNodes as $node)
                    {
                       if($node->hasChildNodes())
                       {
                          foreach($node->childNodes as $childNode)
                          {
                              $responseValues[$childNode->nodeName] = trim($childNode->nodeValue);

                              if($childNode->hasChildNodes())
                              {
                                foreach($childNode->childNodes as $grandchildNode)
                                {
                                    $responseValues[$grandchildNode->nodeName] = trim($grandchildNode->nodeValue);
                                        if($grandchildNode->hasChildNodes())
                                        {
                                             foreach($grandchildNode->childNodes as $putichildNode)
                                             {
                                                 if ($putichildNode->nodeType != XML_TEXT_NODE)
                                                 $responseValues[$putichildNode->nodeName] = trim($putichildNode->nodeValue);
                                             }
                                        }
                                }
                              }
                          }
                      }

                  }
          }
          else{
              $this->response->ack = ACK_FAILURE;
          }

          //dumpvar($responseValues);

          if(isset($responseValues['trnApproved']) && $responseValues['trnApproved'] ==1){
                  $this->response->success = 1;
                  $this->response->ack = ACK_SUCCESS;
              }  else {
                  $this->response->success = 0;
                  $this->response->ack = ACK_FAILURE;

                  if(isset($responseValues['avsMessage']))
                  $this->response->setError($responseValues['avsMessage']);
              }

              $this->response->authorizationId = isset($responseValues['sessionId']) ? $responseValues['sessionId'] : '';
              $this->response->invoiceNumber = isset($responseValues['merchantId']) ? $responseValues['merchantId'] : '';  // Save merchantId Here.
              $this->response->transactionId =  isset($responseValues['trnId']) ? $responseValues['trnId'] : '';
      }



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

          $this->validateAmount();
      }
  }
?>