<?php
/**
* @version	$Id: paypal.php 13704 2010-06-09 14:52:56Z alex $
* @package	In-Commerce
* @copyright	Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license	Commercial License
* This software is protected by copyright law and international treaties.
* Unauthorized reproduction or unlicensed usage of the code of this program,
* or any portion of it may result in severe civil and criminal penalties,
* and will be prosecuted to the maximum extent possible under the law
* See http://www.in-portal.org/commercial-license for copyright notices and details.
*/

	require_once GW_CLASS_PATH.'/gw_base.php';

	class kGWPayPal extends kGWBase
	{
		/**
		 * Returns payment form submit url
		 *
		 * @param Array $gw_params gateway params from payment type config
		 * @return string
		 */
		function getFormAction($gw_params)
		{
			return $gw_params['submit_url'];
		}

		/**
		 * Processed input data and convets it to fields understandable by gateway
		 *
		 * @param Array $item_data
		 * @param Array $tag_params additional params for gateway passed through tag
		 * @param Array $gw_params gateway params from payment type config
		 * @return Array
		 */
		function getHiddenFields($item_data, $tag_params, $gw_params)
		{
			$ret = Array();
			$ret['item_name'] = 'Order #'.$item_data['OrderNumber'];
			$ret['item_number'] = 'order:'.$item_data['OrderNumber'];


			$selected_cur = $this->Application->RecallVar('curr_iso');
			$available = explode(',', $gw_params['currency_code']);
			$target = in_array($selected_cur, $available) ? $selected_cur : $available[0];

			if( !$this->IsTestMode() )
			{
				$currency_iso = $gw_params['currency_code'];
				$ret['amount'] = $this->ConvertCurrency($item_data['SubTotal'], $target);
				$ret['shipping'] =  $this->ConvertCurrency($item_data['ShippingCost'], $target);
				$ret['tax'] = $this->ConvertCurrency($item_data['VAT'], $target);
			}
			else
			{
				$ret['amount'] = 1;
				$ret['shipping'] = 0;
				$ret['tax'] = 0;
			}

			$ret['quantity'] = 1;
			$ret['cancel_return'] = $this->Application->HREF($tag_params['cancel_template'],'',Array('pass'=>'m'));
			$ret['return'] = $this->Application->HREF($tag_params['return_template'],'',Array('pass'=>'m'));
			$ret['no_note'] = 1;	// customer is not prompted for notes
			$ret['no_shipping'] = 1;	// customer is not prompted for shipping address
			$ret['rm'] = 2;	// return method - POST
			$ret['currency_code'] = $target;
			$ret['invoice'] = $item_data['OrderNumber'];
			$ret['business'] = $gw_params['business_account'];

			// prepopulated fields
			$ret['address_override'] = 1; // override user's stored address
			$ret['email'] = $item_data['BillingEmail'];
			list($first_name, $last_name) = explode(' ', $item_data['BillingTo']);
			$ret['first_name'] = $first_name;
			$ret['last_name'] = $last_name;
			$ret['address1'] = $item_data['BillingAddress1'];
			$ret['address2'] = $item_data['BillingAddress2'];
			$ret['city'] = $item_data['BillingCity'];
			$ret['state'] = $item_data['BillingState'];
			$ret['zip'] = $item_data['BillingZip'];

			$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
			/* @var $cs_helper kCountryStatesHelper */

			$ret['country'] = $cs_helper->getCountryIso( $item_data['BillingCountry'] );
			$ret['notify_url'] = $this->getNotificationUrl() . '?sid=' . $this->Application->GetSID() . '&admin=1&order_id=' . $item_data['OrderId'];

			$ret['cmd'] = '_xclick'; // act as "Buy Now" PayPal button
			return $ret;
		}

		function getSubscriptionFields($item_data, $tag_params, $gw_params)
		{

			$ret = Array();
			$ret['item_name'] = $item_data['item_name'];
			$ret['item_number'] = $item_data['item_number'];
			$ret['a1'] = $item_data['a1'];
			$ret['p1'] = $item_data['p1'];
			$ret['t1'] = $item_data['t1'];
			$ret['a2'] = $item_data['a2'];
			$ret['p2'] = $item_data['p2'];
			$ret['t2'] = $item_data['t2'];

			$ret['p3'] = $item_data['p3'];
			$ret['t3'] = $item_data['t3'];
			$ret['src'] = $item_data['src'];
			$ret['sra'] = $item_data['sra'];
			$ret['srt'] = $item_data['srt'];

			$ret['custom'] = $item_data['OrderId'];

			$currency_iso = $gw_params['currency_code'];
			$ret['a3'] = $this->ConvertCurrency($item_data['a3'], $currency_iso);;
			$ret['tax'] = $this->ConvertCurrency($item_data['VAT'], $currency_iso);
			if( $this->Application->isDebugMode() )
			{

			}
			else
			{

			}

//			$ret['quantity'] = 1;
			$ret['cancel_return'] = $this->Application->HREF($tag_params['cancel_template'],'',Array('pass'=>'m'));
			$ret['return'] = $this->Application->HREF($tag_params['return_template'],'',Array('pass'=>'m'));
			$ret['no_note'] = 1;	// customer is not prompted for notes
			$ret['no_shipping'] = 1;	// customer is not prompted for shipping address
			$ret['rm'] = 2;	// return method - POST
			$ret['currency_code'] = $gw_params['currency_code'];
			$ret['invoice'] = $item_data['OrderNumber'];
			$ret['business'] = $gw_params['business_account'];

			// prepopulated fields
			$ret['address_override'] = 1; // override user's stored address
			$ret['email'] = $item_data['BillingEmail'];
			list($first_name, $last_name) = explode(' ', $item_data['BillingTo']);
			$ret['first_name'] = $first_name;
			$ret['last_name'] = $last_name;
			$ret['address1'] = $item_data['BillingAddress1'];
			$ret['address2'] = $item_data['BillingAddress2'];
			$ret['city'] = $item_data['BillingCity'];
			$ret['state'] = $item_data['BillingState'];
			$ret['zip'] = $item_data['BillingZip'];

			$cs_helper =& $this->Application->recallObject('CountryStatesHelper');
			/* @var $cs_helper kCountryStatesHelper */

			$ret['country'] = $cs_helper->getCountryIso( $item_data['BillingCountry'] );
			$ret['notify_url'] = $this->getNotificationUrl() . '?sid='.$this->Application->GetSID().'&admin=1&order_id='.$item_data['OrderId'].'&payment_type_id='.$tag_params['payment_type_id'];
			$ret['cmd'] = '_xclick-subscriptions'; // act as "Buy Now" PayPal button

			$real_ret = array();
			foreach ($ret as $key => $val)
			{
				if ($val == '') continue;
				$real_ret[$key] = $val;
			}

			return $real_ret;
		}

		function processNotification($gw_params)
		{
			$payment_status = $_POST['payment_status']; // save payment_status for later proceeding

			$_POST['cmd'] = '_notify-validate';

			// status, of that PayPal server really has sent such notification to us
			$status_map = Array('INVALID' => 0, 'VERIFIED' => 1);

			$n_status = curl_post($gw_params['submit_url'], $_POST); // INVALID, VERIFIED
			$n_status = $status_map[$n_status];

			$success = ($n_status == 1) && ($payment_status == 'Completed') ? 1:0 ; // 1:0 is on purpose, false will result an SQL error !

			if (!$success) return;

			$type = $_POST['txn_type'];
			switch ($type)
			{
				case 'subscr_signup':
					break;
				case 'subscr_cancel':
					break;
				case 'subscr_failed':
					break;
				case 'subscr_payment':
					$field_values = $this->Conn->GetRow('SELECT * FROM '.TABLE_PREFIX.'OrderItems WHERE OrderItemId = '.$_POST['item_number']);
					$this->Application->HandleEvent($an_event, 'p:OnSubscriptionApprove', array('field_values' => $field_values));
					$success = 0; //this will eliminate OnCompleteOrder in gw_notify!

					$org_order = $this->Application->recallObject('ord.-original', 'ord', Array('skip_autoload' => true));
					$org_order->Load($field_values['OrderId']);

					$order = $this->Application->recallObject('ord.-paypal', 'ord');
					$order->SetDBFieldsFromHash($org_order->FieldValues);
					$order->SetDBField('SubTotal', $field_values['Price']);
					$order->SetDBField('OriginalAmout', $field_values['Price']);
					$order->SetDBField('OrderDate', adodb_mktime());
					$order->UpdateFormattersSubFields();

					$dup_item = false;
					if ($org_order->GetDBField('Status') >= ORDER_STATUS_PROCESSED) {
						$sql = 'SELECT MAX(SubNumber) FROM '.TABLE_PREFIX.'Orders WHERE Number = '.$org_order->GetDBField('Number');
						$num = $this->Conn->GetOne($sql) + 1;
						$order->SetDBField('SubNumber', $num);
						$dup_item = true;
					}
					else {
						$sql = 'SELECT MAX(Number) FROM '.TABLE_PREFIX.'Orders';
						$num = $this->Conn->GetOne($sql) + 1;
						$order->SetDBField('Number', $num);
						$order->SetDBField('SubNumber', 0);
					}
					$order->SetDBField('PaymentType', $this->Application->GetVar('payment_type_id'));
					$info = array(
						'BillingTo' => $_POST['first_name'].' '.$_POST['last_name'],
						'BillingCompany' => 'n/a (PayPal)',
						'BillingPhone' => 'n/a (PayPal)',
						'BillingFax' => '',
						'BillingEmail' => $_POST['payer_email'],
						'BillingAddress1' => 'n/a (PayPal)',
						'BillingCity' => 'n/a (PayPal)',
						'BillingState' => 'n/a (PayPal)',
						'BillingZip' => 'n/a (PayPal)',
						'BillingCountry' => '???',
					);

					$order->SetFieldsFromHash($info);

					$order->SetDBField('Status', ORDER_STATUS_PROCESSED);

					$order->Create();
					if ($dup_item) {
						$query = 'INSERT INTO '.TABLE_PREFIX.'OrderItems
											(OrderId, ProductId, ProductName, Quantity, QuantityReserved, FlatPrice, Price, BackOrderFlag, Weight, ShippingTypeId, ItemData, OptionsSalt)
											SELECT
												'.$order->GetId().' AS OrderId, ProductId, ProductName, Quantity, QuantityReserved, FlatPrice, Price, BackOrderFlag, Weight, ShippingTypeId, ItemData, OptionsSalt
											FROM '.TABLE_PREFIX.'OrderItems
											WHERE OrderItemId = '.$field_values['OrderItemId'];
					}
					else {
						$query = 'UPDATE '.TABLE_PREFIX.'OrderItems SET OrderId = %s WHERE OrderItemId = %s';
						$query = sprintf($query, $order->GetId(), $field_values['OrderItemId']);
					}
					$this->Conn->Query($query);

					break;
				case 'subscr_eot':
					break;
				case 'subscr_modify':
					break;
			}

			return $success;
		}
	}