<?php
/**
 * @version		3.0.0
 * @package		JomLand TicketCenter
 * @copyright	Copyright (C) 2010 JomLand.com. All rights reserved.
 * @link 		www.jomland.com
 * @license		GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 */
defined('_JEXEC') or die('Restricted access');

jimport('joomla.html.pane');

require 'jlticketpayment.php';
class JLTicketCenterPaypal_api extends JLTicketPayment
{

	public $payment_params = array('paypal_debug'=>1,
								'paypal_email'=>'erezavny@gmail.com');

	private $payment_data = array();


	private $returnURL;
	private $cancelURL;

	function __construct(){
		//$this->returnURL = urlencode(JURI::base()."index.php?option=com_jlticketcenter&view=checkout&step=pay_comp");
		//$this->cancelURL = urlencode(JURI::base()."index.php?option=com_jlticketcenter&view=checkout&step=pay_cancel");
		$this->returnURL = JURI::base()."index.php?option=com_jlticketcenter&view=checkout&step=pay_comp";
		$this->cancelURL = JURI::base()."index.php?option=com_jlticketcenter&view=checkout&step=pay_cancel";

		if (session_id() == "")
		session_start();
	}

	function buildPanel($payment_class){

		$payment_config = $this->getConfig($payment_class);

        $output = JHtml::_('tabs.start', 'slider-', array('useCookie' => 1));
        $output .= JHtml::_('tabs.panel', JText::_('Parameters'), 'panel1');
        $output .='<div id="payment_params">'."\n";

		$output .='<tr>'."\n";
		$output .='<td width="100" class="key">'."\n";
		$output .='<label for="published">'.JText::_('Paypal Test Mode').'</label>'."\n";
		$output .='</td>'."\n";
		$output .='<td>'."\n";
		$output .= JHTML::_('select.booleanlist','params[paypal_debug]', '', $payment_config->paypal_debug);
		$output .='</td>'."\n";
		$output .='</tr>'."\n";

		$output .='<tr>'."\n";
		$output .='<td width="100" class="key">'."\n";
		$output .='<label for="published">'.JText::_('API Username').'</label>'."\n";
		$output .='</td>'."\n";
		$output .='<td>'."\n";
		$output .= '<input name="params[API_USERNAME]" value="'.$payment_config->API_USERNAME.'" />'."\n";;
		$output .='</td>'."\n";
		$output .='</tr>'."\n";

		$output .='<tr>'."\n";
		$output .='<td width="100" class="key">'."\n";
		$output .='<label for="published">'.JText::_('API Password').'</label>'."\n";
		$output .='</td>'."\n";
		$output .='<td>'."\n";
		$output .= '<input name="params[API_PASSWORD]" value="'.$payment_config->API_PASSWORD.'" />'."\n";;
		$output .='</td>'."\n";
		$output .='</tr>'."\n";

		$output .='<tr>'."\n";
		$output .='<td width="100" class="key">'."\n";
		$output .='<label for="published">'.JText::_('API Signature').'</label>'."\n";
		$output .='</td>'."\n";
		$output .='<td>'."\n";
		$output .= '<input name="params[API_SIGNATURE]" value="'.$payment_config->API_SIGNATURE.'" />'."\n";;
		$output .='</td>'."\n";
		$output .='</tr>'."\n";

        $output .='</div>';
        $output .= JHtml::_('tabs.end');

		return $output;
	}//EOF buildPanel


	function pross_payment($data){

		$mainframe = JFactory::getApplication();

		$pparams = new JLTicketCenterHelperSetup;
		$corrency_code = $pparams->get('currency_code','USD');

		//get Config
		$payment_config = $this->getConfig('paypal_api');

		//var_dump($payment_config );

		//$tax_total = $db->f("order_tax") + $db->f("order_shipping_tax");
		//$discount_total = $db->f("coupon_discount") + $db->f("order_discount");

		require_once JPATH_ADMINISTRATOR. '/components/com_jlticketcenter/models/payment/paypal_api/CallerService.php';


		if (!isset($data['zip'])){
			$zip='';
		}else{
			$zip=$data['zip'];
		}
                
		/**
		 * Get required parameters from the web form for the request
		 */
		$paymentType 	= urlencode('Sale');
		$firstName 		= urlencode($data['first_name']);
		$lastName 		= urlencode($data['last_name']);
		$creditCardType = urlencode($data['creditCardType']);
		$creditCardNumber= urlencode($data['creditCardNumber']);
		$expDateMonth 	= urlencode($data['expDateMonth']);

		// Month must be padded with leading zero
		$padDateMonth = str_pad($expDateMonth, 2, '0', STR_PAD_LEFT);

		$expDateYear 	= urlencode($data['expDateYear']);
		$cvv2Number 	= urlencode($data['cvv2Number']);
		$address1 		= urlencode($data['street']);
		$address2 		= '';//urlencode($data['street_2']);
		$city 			= urlencode($data['city']);
		$state 			= urlencode($data['state']);
		$zip 			= urlencode($zip);
		$amount 		= urlencode(round($data['order_total'],2));
		$currencyCode	= $corrency_code;
		//$paymentType	= urlencode('Sale');


		/* Construct the request string that will be sent to PayPal.
		 The variable $nvpstr contains all the variables and is a
		 name value pair string with & as a delimiter */
		$nvpstr="&PAYMENTACTION=$paymentType&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber&EXPDATE=".         $padDateMonth.$expDateYear."&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName&STREET=$address1&CITY=$city&STATE=$state".
		"&ZIP=$zip&COUNTRYCODE=US&CURRENCYCODE=$currencyCode";

		/* Make the API call to PayPal, using API signature.
		 The API response is stored in an associative array called $resArray */
		$resArray=hash_call("doDirectPayment",$nvpstr,$payment_config);
		/*
		 echo "---erez 1---";
		 var_dump($resArray);
		 echo "---erez 2---";
		 */
		/* Display the API response back to the browser.
		 If the response from PayPal was a success, display the response parameters'
		 If the response was an error, display the errors received using APIError.php.
		 */
		$ack = strtoupper($resArray["ACK"]);

		require_once (JPATH_COMPONENT_ADMINISTRATOR.DS.'models'.DS.'paymentlog.php');

		$timestr=strtotime($resArray['TIMESTAMP']);
		$tran_time =strftime("%Y-%m-%d %H:%M:%S",$timestr);

		$session = JFactory::getSession();

		if($ack!="SUCCESS")  {

			$log = array();
			$log['payment_time']=$tran_time;
			$log['order_id']=$session->get('jlticketcenter_order_id');
			$log['payment_method']='PayPal API';
			$log['amount']=$resArray['AMT'];
			$log['status']=0;
			$log['transactionid']='';

			$model = JModelLegacy::getInstance('PaymentLog', 'JLTicketCenterModel');
			$model->store($log);
			 
			$credit_info = array();
			$credit_info = $data;
				
			$credit_info['error_code']	= $resArray['L_ERRORCODE0'];
			$credit_info['error_short_msg']	= $resArray['L_SHORTMESSAGE0'];
			$credit_info['error_msg']	= $resArray['L_LONGMESSAGE0'];
			$credit_info['payment_class']	= 'paypal_api';
				
			$session->set('jlticketcenter_credit',$credit_info);
			 
			$link = JURI::base()."index.php?option=com_jlticketcenter&view=credit_error";
			$mainframe->redirect($link);
		}
		else{
			// Success write to log and proccess the order
			$data = array();
			$data['payment_time']=$tran_time ;
			$data['order_id']=$session->get('jlticketcenter_order_id');
			$data['payment_method']='PayPal API';
			$data['amount']=$resArray['AMT'];
			$data['status']=1;
			$data['transactionid']=$resArray['TRANSACTIONID'];
			 
			$model = JModelLegacy::getInstance('PaymentLog', 'JLTicketCenterModel');
			$model->store($data);
			 
			 
			require_once (JPATH_COMPONENT_ADMINISTRATOR.DS.'models'.DS.'order.php');
			require_once (JPATH_COMPONENT_ADMINISTRATOR.DS.'controllers'.DS.'order.php');
			 
			$order=array();
			$order['order_id'] 		=$data['order_id'];
			$order['order_status']	=0;
			$order['new_status']	='OrderPaid';
			$order['payment_pross']	=true;
			$order['no_redirect']	=true;
			$order[JUtility::getToken()]="1";
			 
			//var_dump($order);
			//die;
			JRequest::set($order,'POST');
			 
			JLTicketCenterControllerOrder::orderProcess();

			$session->set('jlticketcenter_order_paid',true);
			 
			$link = JURI::base()."index.php?option=com_jlticketcenter&view=order";
			$mainframe->redirect($link);
			die;
		}
	}// EOF pross
}//EOC