<?php

/**
* @version 2.8.14
* @package Joomla 2.5
* @subpackage DT Register
* @copyright Copyright (C) 2006 DTH Development
* @copyright contact dthdev@dthdevelopment.com
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/

defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' );

require_once( JPATH_SITE.'/components/com_dtregister/lib/class.payment.php');

class payflow_pro extends Payment 
{
	public $API_USERNAME;
	public $API_PASSWORD;
	public $API_VENDOR;
	public $API_PARTNER;
	public $API_ENDPOINT;
	public $USE_PROXY;
	public $PROXY_HOST;
	public $PROXY_PORT;
	public $PAYPAL_URL;
	
	public $NVP_HEADER;
	public $bywebservice = true;
	public $cardtype = "";

	// function __construct($API_USERNAME, $API_PASSWORD, $API_SIGNATURE, $PROXY_HOST, $PROXY_PORT, $IS_ONLINE = FALSE, $USE_PROXY = FALSE, $VERSION = '57.0')
	function __construct()
	{
		global $payflow_api_user,$payflow_api_password,$payflow_api_vendor,$paypal_pro_partner,$godaddy_hosting;
		
		parent::__construct();

		$this->API_USERNAME = $paypal_api_user; // $API_USERNAME;
		$this->API_PASSWORD = $paypal_api_password; // $API_PASSWORD;
		$this->API_VENDOR = $paypal_api_vendor; 
		$this->API_PARTNER = $paypal_api_partner;
		$this->API_ENDPOINT = ($this->paymentmode=='test')?'https://pilot-payflowpro.paypal.com':'https://payflowpro.paypal.com';
		$this->USE_PROXY = false;
		if($godaddy_hosting){
          
		  $this->USE_PROXY = true;
		  $PROXY_HOST = "http://proxy.shr.secureserver.net";
		  $PROXY_PORT = 3128;

	   }
		
		if($this->USE_PROXY == true)
		{
			$this->PROXY_HOST = $PROXY_HOST;
			$this->PROXY_PORT = $PROXY_PORT;
		}
		else
		{
			$this->PROXY_HOST = '127.0.0.1';
			$this->PROXY_PORT = '808';
		}
		if($this->paymentmode=='test')
		{
			$this->PAYPAL_URL = 'https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=';
		}
		else
		{
			$this->PAYPAL_URL = 'https://www.paypal.com/webscr&cmd=_express-checkout&token=';
		}
		
		$this->BUTTONSOURCE = 'DTHDev_SP';
		
	}

	function hash_call($url, $parameters, $headers = null)
	{
		 $header = array();

      $server = parse_url($url);

      if (!isset($server['port'])) {
        $server['port'] = ($server['scheme'] == 'https') ? 443 : 80;
      }

      if (!isset($server['path'])) {
        $server['path'] = '/';
      }

      if (isset($server['user']) && isset($server['pass'])) {
        $header[] = 'Authorization: Basic ' . base64_encode($server['user'] . ':' . $server['pass']);
      }

      if (!empty($headers) && is_array($headers)) {
        $header = array_merge($header, $headers);
      }

      
        $curl = curl_init($server['scheme'] . '://' . $server['host'] . $server['path'] . (isset($server['query']) ? '?' . $server['query'] : ''));
        curl_setopt($curl, CURLOPT_PORT, $server['port']);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_FORBID_REUSE, 1);
        curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $parameters);

        if (!empty($header)) {
          curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        }

        $result = curl_exec($curl);

        curl_close($curl);
     

      return $result;

	}

	function deformatNVP($nvpstr)
	{

		$intial=0;
		$nvpArray = array();
		while(strlen($nvpstr))
		{
			$keypos= strpos($nvpstr,'='); 
			$valuepos = strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr); 
			$keyval=substr($nvpstr,$intial,$keypos);
			$valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
			$nvpArray[urldecode($keyval)] =urldecode( $valval);
			$nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
		 }
		return $nvpArray;
	}
	
	function billingform(){

	   global $cardtype;
       
	   $form = parent::billingform();
       ob_start();
	   $size = count($cardtype);
	   if($size ==1){

		  ?>

       <div id="dtcard_details" style="clear:both; margin:10px 0 0 0">

           <div>

           <input type="radio" style="display:none" name="billing[cardtype]" value="<?php echo $cardtype[0];?>" <?php echo "checked"; ?> /></div>

       </div>

          <?php

	   }else{

	   ?>

	    <dl>

          <dt class="dtlabel"><?php echo JText::_( 'CARD_TYPE' );?>:<span class='dtrequired'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></dt>

          <dd class="dtfield">

            <?php

			$mCardtype = DtrModel::getInstance('cardtype','DtregisterModel');
			$types = $mCardtype->gettypes();
			$options = array();
			foreach($cardtype as $key=>$type) {
				$options[$key] = $types[$type]; 
			}
			$options=DtHtml::options($options);
			echo JHTML::_('select.genericlist', $options,'billing[cardtype]','','value','text',isset($this->cardtype)?$this->cardtype:'');

			?>

          </dd>

        </dl>

	   <?php

	   }

	   ?>

          <dl>

		         <dt class="dtlabel"><?php echo JText::_( 'CARD_NUMBER' );?>:<span class='dtrequired'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></dt>

		         <dd class="dtfield"><input type="text" name="billing[x_card_num]" class="inputbox" value="<?php echo isset($this->cb_creditcardnumber)?$this->cb_creditcardnumber:''?>" />

		              <br />

		            <?php echo JText::_( 'CARD_NUMBER_EXPLANATION' );?></dd>

		   </dl>

           <?php
        echo   $this->expiry_fields(isset($this->cb_expdate)?$this->cb_expdate:'');
		?>
        
         <?php
        echo   $this->start_fields();
		?>
         <!--dl>

		    <dt class="dtlabel"><?php echo JText::_( 'CARD_EXPIRY_DATE' );?>:<span class='dtrequired'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></dt>

		    <dd class="dtfield"><input type="text" name="billing[x_exp_date]" value="<?php //echo isset($this->cb_expdate)?$this->cb_expdate:''?>" class="inputbox" />

		            &nbsp;&nbsp;(mm/yyyy)</dd>

		 </dl-->

          <dl>

		         <dt class="dtlabel"><?php echo JText::_( 'CVV_CODE' );?>:<span class='dtrequired'>&nbsp;&nbsp;*&nbsp;&nbsp;</span></dt>

		         <dd class="dtfield"><input autocomplete="off" type="text" name="billing[x_card_code]" size="10" class="inputbox" value="" />

		            <?php echo JText::_( 'CVV_CODE_EXPLANATION' );?></dd>

		 </dl>

       <?php
		
	   $html = ob_get_clean();

	   return $form.$html;

   }

	function setFields(){

   }

	function process(){
        global $currency_code,$cardtype;
		if($currency_code==""){$currency_code='USD';}
		
		switch($cardtype[$this->cardtype]){			
			case 'AmericanExpress':
				$this->cardtype = 'Amex';
			break;
			default:
				 $this->cardtype = $cardtype[$this->cardtype];
			break;
		}
		$year = $this->x_exp_date_year;
	   $exp_date=$this->x_exp_date_month."/".$year;
	   
       $this->x_exp_date = $exp_date ;
		$card_expiry_array = explode("/", $this->x_exp_date);
		
		$params = array('USER' => $this->API_USERNAME,
		                'VENDOR' => $this->API_PASSWORD,
						'PARTNER' => $this->API_PARTNER,
						'VENDOR'=> $this->API_VENDOR,
						'TENDER' => 'C',
						'TRXTYPE' => 'S');
						
		$params['FIRSTNAME']			= urlencode($this->firstname);
		$params['LASTNAME']			= urlencode($this->lastname);
		$params['ACCTTYPE'] 	= urlencode($this->cardtype);
		$params['ACCT'] 	= urlencode($this->x_card_num);
		$params['CARDSTART'] 		= urlencode($this->x_start_date_month.$this->x_start_date_year); // mention in form first
		$params['EXPDATE'] 		= urlencode($card_expiry_array[0].$card_expiry_array[1]);
		$params['FIRSTNAME'] 		= urlencode($this->x_card_code);
		$params['STREET'] 			= urlencode($this->address);
		//$params['FIRSTNAME'] 			= '';
		$params['CITY'] 				= urlencode($this->city);
		$params['STATE'] 				= urlencode($this->state);
		$params['ZIP'] 				= isset($this->zipcode)?urlencode($this->zipcode):'';
		$params['AMT'] 			= urlencode($this->cart->getAmount());
		$params['CURRENCY']		= urlencode($currency_code);
		$params['EMAIL']              = urlencode($this->email);
		$params['COUNTRY'] = $this->country ;
		$params['CLIENTIP'] =  urlencode($_SERVER['REMOTE_ADDR']) ;
		$params['ACCT'] = $$creditCardNumber ;
		$params['BUTTONSOURCE'] = $this->BUTTONSOURCE;
		$params['COMMENT1'] = $this->description ;
		
		
		 $post_string = '';

        foreach ($params as $key => $value) {
          $post_string .= $key . '[' . strlen(urlencode(utf8_encode(trim($value)))) . ']=' . urlencode(utf8_encode(trim($value))) . '&';
        }

        $post_string = substr($post_string, 0, -1);

        $response = $this->hash_call($this->API_ENDPOINT, $post_string, array('X-VPS-REQUEST-ID: ' . md5(session_id() . rand())));
		 $response_array = array();
        parse_str($response, $response_array);
        
		/*$fp = fopen('/tmp/payflowdb.log', 'a+');
		fwrite($fp, $post_string ."\n");
		fwrite($fp, serialize($response_array) . "\n");
		fwrite($fp, $post_string ."\n");
		fclose($fp);		*/
		//$ack = strtoupper($resArray["ACK"]);
		// pr($resArray);
		if ($response_array['RESULT'] != '0') {  
	      
		  switch ($response_array['RESULT']) {
            case '1':
            case '26':
              $error_message = JText::_('DT_CFG_ERROR');
              break;

            case '7':
              $error_message = JText::_('DT_ERROR_ADDRESS');
              break;

            case '12':
              $error_message = JText::_('DT_ERROR_DECLINED');
              break;

            case '23':
            case '24':
              $error_message = JText::_('DT_ERROR_INVALID_CREDIT_CARD');
              break;

            default:
              $error_message = JText::_( 'DT_PAYFLOW_PRO_FAILURE' );
              break;
          }

		   echo $error_message." <br /> ".$response_array['RESPMSG']."<br /><br />" ;
		  return false ;
		} else {
		   	$this->transactionId = $response_array['PNREF'];

             $process = DT_Session::get('Setting.process');
			 DT_Session::set($process.'.payment.transactionId',$this->transactionId);
			 return true;
		}
		

   }

   

	function __destruct() 
	{

	}
}