<?php

/**
* @version 2.8.1
* @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 korta extends Payment{

   var $last_error;                 // holds the last error encountered

   var $ipn_log;                    // bool: log IPN results to text file?

   var $ipn_log_file;               // filename of the IPN log

   var $ipn_response;               // holds the IPN response from korta

   var $ipn_data = array();         // array contains the POST values for IPN

   var $fields = array();           // array holds the fields to submit to korta

   var $bywebservice = false;

   function __construct() {

      // initialization constructor.  Called when class is created.
      global $korta_merchant,$korta_terminal,$korta_secretcode; 
      parent::__construct();
      
	  $this->url = ($this->paymentmode=='test')?'https://netgreidslur.korta.is/testing/':'https://netgreidslur.korta.is/';
     
      $this->secret_code = $korta_secretcode;
      $this->last_error = '';

      $this->ipn_log_file = 'ipn_log.txt';

      $this->ipn_log_file = dirname(__FILE__)."/ipnlog.txt";
	  //pr($this->ipn_log_file);

      $this->ipn_log = true;

      $this->ipn_response = '';  
      $this->merchant = $korta_merchant;
	  $this->terminal = $korta_terminal;
      $this->add_field('merchant',$korta_merchant);           // Return method = POST

	  // $this->add_field('reference',$this->confirmNum);

      $this->add_field('terminal',$korta_terminal);

   }

   function add_field($field, $value) {

      $this->fields["$field"] = $value;

   }

   function process(){

	   global $currency_code,$Itemid;

	   $mosConfig_live_site = JURI::root( false );

	   if($currency_code==""){$currency_code='USD';}

	   $checkvalue = $this->cart->getAmount().$currency_code . $this->merchant .$this->terminal . $this->description . $this->secret_code;
	    if($this->paymentmode=='test'){

		  $checkvalue .= 'TEST';

	    }
		$checkvaluemd5 = md5($checkvalue);
		$this->add_field('checkvaluemd5', $checkvaluemd5);
		
		$process = DT_Session::get('Setting.process');
		DT_Session::set($process.'.payment.checkvaluemd5',$checkvaluemd5);

	   $session_id = $this->saveSession();

	   $this->add_field('downloadurl', "{$mosConfig_live_site}components/com_dtregister/success.php?return=$session_id&Itemid=$Itemid&task=restore");

	   $this->add_field('continueurl', "{$mosConfig_live_site}components/com_dtregister/success.php?return=$session_id&Itemid=$Itemid&task=cancel");

	   $this->add_field('callbackurl', "{$mosConfig_live_site}components/com_dtregister/success.php?return=$session_id&Itemid=$Itemid&task=notification");
	   
	   $this->add_field('description',$this->description);
        $this->add_field('refermethod','POST');
		$this->add_field('refertarget','_top');
		
	  if(isset($this->firstname) && $this->firstname !="" ){
	  	 $this->add_field('name', trim($this->firstname." ".$this->lastname));
	  }
	  
	   if(isset($this->address) && $this->address !="" ){
	  	 $this->add_field('address1', $this->address);
	  }
	  
	   if(isset($this->city) && $this->city !="" ){
	  	 $this->add_field('city', $this->city);
	  }
	 
	   if(isset($this->zip) && $this->zip !="" ){
	  	 $this->add_field('zip', $this->zip);
	  }
	  
	  if(isset($this->state) && $this->state !="" ){
	  	 $this->add_field('state', $this->state);
	  }
	  
	   if(isset($this->email) && $this->email !="" ){
	  	 $this->add_field('email', $this->email);
	  }
	  
	  if(isset($this->phone) && $this->phone !="" ){
	  	 $this->add_field('phone', $this->phone);
	  }
	  
	   if(isset($this->country) && $this->country !="" ){
	  	 $this->add_field('country', $this->country);
	  }
		
	   $this->add_field('amount', $this->cart->getAmount());

	   $this->add_field('currency', "$currency_code");

	  // $this->add_field('custom', "test|session=$session_id");
	  
	   $this->submit_post();

   }

   function submit_post() {

      echo "<center><h3>".JText::_( 'DT_KORTA_REDIRECT_MSG')."</h3></center>\n";

      echo "<form method=\"post\" name=\"formRegister\" action=\"".$this->url."\">\n";

      foreach ($this->fields as $name => $value) {

         echo " <input type=\"hidden\" name=\"$name\" value=\"$value\">";

      }

?>

		<script language="javascript">

			function rg_direct(){

				document.formRegister.submit();

			}

			setTimeout("rg_direct()",5000);

		</script>

<?php

      echo "</form>\n";

   }

   function validate_ipn() {

      $this->log_ipn_results(false);
      //return true ;
	  $process = DT_Session::get('Setting.process');
	  $checkvaluemd5 = DT_Session::get($process.'.payment.checkvaluemd5');
	  $download=htmlspecialchars("2" .$checkvaluemd5 .$this->secret_code);
	  if($this->paymentmode=='test'){

		  $download .= 'TEST';

	    }
		$downloadmd5 = md5($download);
      return ($downloadmd5 == $_REQUEST['downloadmd5']);

   }

   function log_ipn_results($success) {
       //return;
      // if (!$this->ipn_log) return;  // is logging turned off?

      // Timestamp

      $text = '['.date('m/d/Y g:i A').'] - ';

      // Success or failure being logged?

      if ($success) $text .= "SUCCESS!\n";

      else $text .= 'FAIL: '.$this->last_error."\n";

      // Log the POST variables

      $text .= "IPN POST Vars from Korta:\n";

      foreach ($this->ipn_data as $key=>$value) {

         $text .= "$key=$value, ";

      }

      // Log the response from the korta server

      $text .= "\nIPN Response from Korta Server:\n ".$this->ipn_response;

      // Write to log

      $fp=fopen($this->ipn_log_file,'a');

      fwrite($fp, $text . "\n\n");

	  fwrite($fp, var_export($_SESSION,true). "\n\n");

      fclose($fp);  // close file

   }

   function dump_fields() {

      echo "<h3>korta_class->dump_fields() Output:</h3>";

      echo "<table width=\"95%\" border=\"1\" cellpadding=\"2\" cellspacing=\"0\">

            <tr>

               <td bgcolor=\"black\"><b><font color=\"white\">Field Name</font></b></td>

               <td bgcolor=\"black\"><b><font color=\"white\">Value</font></b></td>

            </tr>";

      ksort($this->fields);

      foreach ($this->fields as $key => $value) {

         echo "<tr><td>$key</td><td>".urldecode($value)."&nbsp;</td></tr>";

      }

      echo "</table><br>";

   }
    function success(){
          
		  $this->transactionId = $_POST['reference'];
		   $this->card4 =  $_POST['card4'];
		  if($this->transactionId === false){
		  	 return false ;
		  }
		    $process = DT_Session::get('Setting.process') ;
			DT_Session::set($process.'.payment.billing.x_card_num',$this->card4);
			DT_Session::set($process.'.payment.cardtype',$_POST['cardbrand']);
			  DT_Session::set($process.'.payment.transactionId',$this->transactionId);
			  
			 
		   return true;
		 

	 }
	 function after_user_save($user) {
		
		if(DT_Session::get('register.payment.billing.x_card_num')) {
			
			$billing = DT_Session::get('register.payment.billing');
			if(isset($billing['x_exp_date_year'])) {
				$billing['userId'] = $user->userId;
				$billing['status'] = 0;
				$year = substr($billing['x_exp_date_year'],2);
				$exp_date=$billing['x_exp_date_month']."/".$year;
				
				$billing['x_exp_date'] = $exp_date ;
				unset($billing['x_exp_date_year']);
				unset($billing['x_exp_date_month']);
			}
			if(!isset($data['userId']) || $data['userId'] == "") {
			   $billing['userId'] = $user->userId ;
			}
			$user->TableCard->save($billing);
			
		}
		
		return;
	}
   function notify(){
	   
	   if($this->validate_ipn()){
		   $this->transactionId = $_REQUEST['txn_id'];
		   $process = DT_Session::get('Setting.process');
		   DT_Session::set($process.'.payment.transactionId', $this->transactionId);
				   return true;
			   }else{
				   pr($this->validate_ipn());
				   return false;
	   }
	      
   }

}