<?php
//-----------------------------------------
// Author: Qphoria@gmail.com
// Web: http://www.OpenCartGuru.com/
//-----------------------------------------
class ControllerPaymentPpHosted extends Controller {

	protected $errors = array();

	public function index() {

		# Generic Init
		$extension_type 			= 'payment';
		$classname 					= str_replace('vq2-' . basename(DIR_APPLICATION) . '_' . strtolower(get_parent_class($this)) . '_' . $extension_type . '_', '', basename(__FILE__, '.php'));
		$data['classname'] 			= $classname;
		$data 						= array_merge($data, $this->load->language($extension_type . '/' . $classname));
		$data['testmode'] 			= $this->config->get($classname . '_test');

		# Form Fields
		$data['fields'] = array();

		# Order Info
		$this->load->model('checkout/order');
		$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);

		# Error Check
		$data['error'] = (isset($this->session->data['error'])) ? $this->session->data['error'] : NULL;
		unset($this->session->data['error']);

		$data['use_iframe'] = $this->config->get($classname . '_iframe');

		# Check for supported currency, otherwise convert to ISK.
		$supported_currencies = explode(",", $this->config->get($classname . '_supported_currencies'));
		if (in_array($order_info['currency_code'], $supported_currencies)) {
			$currency = $order_info['currency_code'];
		} else {
			$currency = $this->config->get($classname . '_default_currency');
		}

		$amount = str_replace(array(''), '', $this->currency->format($order_info['total'], $currency, FALSE, FALSE));

		if (!$this->config->get($classname . '_test')) {
			$data['action'] = 'https://securepayments.paypal.com/webapps/HostedSoleSolutionApp/webflow/sparta/hostedSoleSolutionProcess';
  		} else {
			$data['action'] = 'https://securepayments.sandbox.paypal.com/webapps/HostedSoleSolutionApp/webflow/sparta/hostedSoleSolutionProcess';
		}

		$storename = ($this->config->get('config_name')) ? $this->config->get('config_name') : $this->config->get('config_store');
		$store_url = ($this->config->get('config_ssl') ? (is_numeric($this->config->get('config_ssl'))) ? str_replace('http', 'https', $this->config->get('config_url')) : $this->config->get('config_ssl') : $this->config->get('config_url'));
		
		# Get all totals and discount total
		$total = 0;
        $total_data = array();
		$taxes = $this->cart->getTaxes();

		if (file_exists(DIR_APPLICATION . 'model/extension/extension.php')) { //1.5.x
			$this->load->model('extension/extension');
			$results = $this->model_extension_extension->getExtensions('total');
		} else {
			$this->load->model('setting/extension');
			$results = $this->model_setting_extension->getExtensions('total');
		}

		$sort_order = array();

		foreach ($results as $key => $value) {
			if (!$this->config->get($value['code'] . '_status')) { unset($results[$key]); continue; }
			// v15x compatibility
			if (!isset($value['key']) && isset($value['code'])) { $value['key'] = $value['code']; }
			$sort_order[$key] = $this->config->get($value['key'] . '_sort_order');
		}

		array_multisort($sort_order, SORT_ASC, $results);

		$discount_total = 0;
		foreach ($results as $result) {

			// v15x compatibility
			if (!isset($result['key']) && isset($result['code'])) { $result['key'] = $result['code']; }

			$this->load->model('total/' . $result['key']);
			$old_total = $total;
			if (version_compare(VERSION, '2.2.0.0', '<')) {
				$this->{'model_total_' . $result['key']}->getTotal($total_data, $total, $taxes);
			} else {
				$xtotals = array(
					'totals' => &$total_data,
					'total'  => &$total,
					'taxes'  => &$taxes
				);
				$this->{'model_total_' . $result['key']}->getTotal($xtotals);
			}

			if ($total < $old_total) {
				$discount_total += $old_total - $total;
			}
		}


		# Get Shipping Total
		$shipping_total = 0;
		if ($this->cart->hasShipping()) {
			if (isset($this->session->data['shipping_method'])) {
				$shipping_total = $this->session->data['shipping_method']['cost'];
			} else {
				$shipping_total = 0;
				//file_put_contents(DIR_LOGS . 'pp_hosted_no_shipping_session.txt', "\r\n" . print_r($this->session->data,1), FILE_APPEND);
			}
		}


		# Get Tax Total
		$tax_total = 0;
		foreach ($taxes as $key => $value) {
			$tax_total += $value;
		}

		$data['fields']['cmd'] = '_hosted-payment';
		$data['fields']['upload'] = '1';

		$product_total = 0;
		$i = 1;
		//$product_total = $this->currency->format($this->cart->getSubtotal(), $currency, FALSE, FALSE);
		$product_total = $this->cart->getSubtotal();

		if ($discount_total) {
			//$product_total -= $this->currency->format($discount_total, $currency, FALSE, FALSE);
			$product_total -= $discount_total;
		}


		$data['fields']['shipping'] = $this->currency->format($shipping_total, $currency, FALSE, FALSE);
		$data['fields']['tax'] = $this->currency->format($tax_total, $currency, FALSE, FALSE);


		# Get any remaining balance as a handling fee
		//$remaining_total = $total - $product_total - $tax_total - $shipping_total + $discount_total;
		$remaining_total = $total - $product_total - $tax_total - $shipping_total;
		if ($remaining_total > 0) {
			//$product_total += number_format(abs($this->currency->format($remaining_total, $currency, FALSE, FALSE)), 2, '.', '');
			$product_total += number_format(abs($remaining_total), 2, '.', '');
		}
		//$data['fields']['subtotal'] = $product_total;
		$data['fields']['subtotal'] = $this->currency->format($product_total, $currency, FALSE, FALSE);

		// Experimental
		// If voucher/discount is greater than product + shipping + tax, then set them all to zero
		// Set subtotal equal to resulting opencart total
		//if ((float)$product_total <= 0.01) { // if product total is less than 1 cent
		if ($discount_total > ($product_total + $tax_total + $shipping_total)) {
			$data['fields']['shipping'] = '0.00';
			$data['fields']['tax'] = '0.00';
			$data['fields']['subtotal'] = $this->currency->format($total, FALSE, FALSE, FALSE);
		}

		// Experimental Paypal Calculation Rounding Fix
		// Sometimes there is an extra cent shown on the paypal total due to their post-conversion math:
		// http://forum.opencart.com/viewtopic.php?f=113&t=51687#p244304
		// This will try to adjust the price before sending to paypal to avoid issue
		$opencart_total = round($this->currency->format($total, $currency, FALSE, FALSE), 2);
		$paypal_total = round(($data['fields']['subtotal'] + $data['fields']['shipping'] + $data['fields']['tax']), 2);
		$correction = 0;
		if ($opencart_total > $paypal_total) {
			$correction = $opencart_total - $paypal_total;
		} elseif ($opencart_total < $paypal_total) {
			$correction = $opencart_total - $paypal_total;
		}
		//$data['fields']['subtotal'] = (string)round(((float)$data['fields']['subtotal'] + $correction), 2);


		# Finish the rest of the form
		$data['fields']['business'] = $this->config->get($classname . '_email');
		$data['fields']['currency_code'] = $currency;
		$data['fields']['showShippingAddress'] = 'true';

		# If no shipping address, just use the billing address
		if (!isset($this->session->data['shipping_address_id']) && !isset($this->session->data['guest']['shipping'])) {

			// Shipping Address uses payment address
			$data['fields']['first_name'] = html_entity_decode($order_info['payment_firstname'], ENT_QUOTES, 'UTF-8');
			$data['fields']['last_name'] = html_entity_decode($order_info['payment_lastname'], ENT_QUOTES, 'UTF-8');
			//$data['fields']['address1'] = html_entity_decode($order_info['payment_address_1'], ENT_QUOTES, 'UTF-8');
			//$data['fields']['address2'] = html_entity_decode($order_info['payment_address_2'], ENT_QUOTES, 'UTF-8');
			$data['fields']['address1'] = ($order_info['payment_address_1']);
			$data['fields']['address2'] = ($order_info['payment_address_2']);
			$data['fields']['city'] = html_entity_decode($order_info['payment_city'], ENT_QUOTES, 'UTF-8');
			//$data['fields']['zip'] = html_entity_decode($order_info['payment_postcode'], ENT_QUOTES, 'UTF-8');
			$data['fields']['zip'] = ($order_info['payment_postcode']);
			$data['fields']['country'] = $order_info['payment_iso_code_2'];

			$phone = preg_replace("/[^0-9.]/", "", html_entity_decode($order_info['telephone'], ENT_QUOTES, 'UTF-8'));
			//if ($order_info['payment_iso_code_2'] == 'US') {
				$this->load->model('localisation/zone');
				$zone = $this->model_localisation_zone->getZone($order_info['payment_zone_id']);
				if (isset($zone['code'])) {
					$data['fields']['state'] = html_entity_decode($zone['code'], ENT_QUOTES, 'UTF-8');
				}
			//}
			if ($order_info['payment_iso_code_2'] == 'US') {
				$data['fields']['night_phone_a'] = html_entity_decode(substr($phone,0,3), ENT_QUOTES, 'UTF-8');
				$data['fields']['night_phone_b'] = html_entity_decode(substr($phone,3,3), ENT_QUOTES, 'UTF-8');
				$data['fields']['night_phone_c'] = html_entity_decode(substr($phone,6), ENT_QUOTES, 'UTF-8');
			} else {
				//$data['fields']['night_phone_a'] = html_entity_decode(substr($phone,0,2), ENT_QUOTES, 'UTF-8');
				$data['fields']['night_phone_b'] = html_entity_decode(substr($phone,0,15), ENT_QUOTES, 'UTF-8');
			}

			// Billing Address
			$data['fields']['billing_first_name'] = html_entity_decode($order_info['payment_firstname'], ENT_QUOTES, 'UTF-8');
			$data['fields']['billing_last_name'] = html_entity_decode($order_info['payment_lastname'], ENT_QUOTES, 'UTF-8');
			//$data['fields']['billing_address1'] = html_entity_decode($order_info['payment_address_1'], ENT_QUOTES, 'UTF-8');
			//$data['fields']['billing_address2'] = html_entity_decode($order_info['payment_address_2'], ENT_QUOTES, 'UTF-8');
			$data['fields']['billing_address1'] = ($order_info['payment_address_1']);
			$data['fields']['billing_address2'] = ($order_info['payment_address_2']);
			$data['fields']['billing_city'] = html_entity_decode($order_info['payment_city'], ENT_QUOTES, 'UTF-8');
			//$data['fields']['billing_zip'] = html_entity_decode($order_info['payment_postcode'], ENT_QUOTES, 'UTF-8');
			$data['fields']['billing_zip'] = ($order_info['payment_postcode']);
			$data['fields']['billing_country'] = $order_info['payment_iso_code_2'];

			$this->load->model('localisation/zone');
			$zone = $this->model_localisation_zone->getZone($order_info['payment_zone_id']);
			if ($order_info['payment_iso_code_2'] == 'US') {
				if (isset($zone['code'])) {
					$data['fields']['billing_state'] = html_entity_decode($zone['code'], ENT_QUOTES, 'UTF-8');
				}
			} else {
				if (isset($zone['name'])) {
					$data['fields']['billing_state'] = html_entity_decode($zone['name'], ENT_QUOTES, 'UTF-8');
				}
			}
		} else { // if there is a shipping address, separate the two

			// Shipping Address uses shipping address
			$data['fields']['first_name'] = html_entity_decode($order_info['shipping_firstname'], ENT_QUOTES, 'UTF-8');
			$data['fields']['last_name'] = html_entity_decode($order_info['shipping_lastname'], ENT_QUOTES, 'UTF-8');
			//$data['fields']['address1'] = html_entity_decode($order_info['shipping_address_1'], ENT_QUOTES, 'UTF-8');
			//$data['fields']['address2'] = html_entity_decode($order_info['shipping_address_2'], ENT_QUOTES, 'UTF-8');
			$data['fields']['address1'] = ($order_info['shipping_address_1']);
			$data['fields']['address2'] = ($order_info['shipping_address_2']);
			$data['fields']['city'] = html_entity_decode($order_info['shipping_city'], ENT_QUOTES, 'UTF-8');
			//$data['fields']['zip'] = html_entity_decode($order_info['shipping_postcode'], ENT_QUOTES, 'UTF-8');
			$data['fields']['zip'] = ($order_info['shipping_postcode']);
			$data['fields']['country'] = $order_info['shipping_iso_code_2'];

			$phone = preg_replace("/[^0-9.]/", "", html_entity_decode($order_info['telephone'], ENT_QUOTES, 'UTF-8'));

			$this->load->model('localisation/zone');
			$zone = $this->model_localisation_zone->getZone($order_info['shipping_zone_id']);
			if ($order_info['payment_iso_code_2'] == 'US') {
				if (isset($zone['code'])) {
					$data['fields']['state'] = html_entity_decode($zone['code'], ENT_QUOTES, 'UTF-8');
				}
			} else {
				if (isset($zone['code'])) {
					$data['fields']['state'] = html_entity_decode($zone['name'], ENT_QUOTES, 'UTF-8');
				}
			}

			if ($order_info['shipping_iso_code_2'] == 'US') {
				$data['fields']['night_phone_a'] = html_entity_decode(substr($phone,0,3), ENT_QUOTES, 'UTF-8');
				$data['fields']['night_phone_b'] = html_entity_decode(substr($phone,3,3), ENT_QUOTES, 'UTF-8');
				$data['fields']['night_phone_c'] = html_entity_decode(substr($phone,6), ENT_QUOTES, 'UTF-8');
			} else {
				//$data['fields']['night_phone_a'] = html_entity_decode(substr($phone,0,2), ENT_QUOTES, 'UTF-8');
				$data['fields']['night_phone_b'] = html_entity_decode(substr($phone,0,15), ENT_QUOTES, 'UTF-8');
			}

			// Billing Address
			$data['fields']['billing_first_name'] = html_entity_decode($order_info['payment_firstname'], ENT_QUOTES, 'UTF-8');
			$data['fields']['billing_last_name'] = html_entity_decode($order_info['payment_lastname'], ENT_QUOTES, 'UTF-8');
			//$data['fields']['billing_address1'] = html_entity_decode($order_info['payment_address_1'], ENT_QUOTES, 'UTF-8');
			//$data['fields']['billing_address2'] = html_entity_decode($order_info['payment_address_2'], ENT_QUOTES, 'UTF-8');
			$data['fields']['billing_address1'] = ($order_info['payment_address_1']);
			$data['fields']['billing_address2'] = ($order_info['payment_address_2']);
			$data['fields']['billing_city'] = html_entity_decode($order_info['payment_city'], ENT_QUOTES, 'UTF-8');
			//$data['fields']['billing_zip'] = html_entity_decode($order_info['payment_postcode'], ENT_QUOTES, 'UTF-8');
			$data['fields']['billing_zip'] = ($order_info['payment_postcode']);
			$data['fields']['billing_country'] = $order_info['payment_iso_code_2'];

			$data['fields']['logoImage'] = ($store_url . 'image/' . $this->config->get('config_logo'));
			
			$this->load->model('localisation/zone');
			$zone = $this->model_localisation_zone->getZone($order_info['payment_zone_id']);
			if ($order_info['payment_iso_code_2'] == 'US') {
				if (isset($zone['code'])) {
					$data['fields']['billing_state'] = html_entity_decode($zone['code'], ENT_QUOTES, 'UTF-8');
				}
			} else {
				if (isset($zone['name'])) {
					$data['fields']['billing_state'] = html_entity_decode($zone['name'], ENT_QUOTES, 'UTF-8');
				}
			}
		}

		$data['fields']['showBillingPhone'] = 'false';

		$data['fields']['showHostedThankyouPage'] = 'false'; // for iframe only.. or maybe not

		$data['fields']['buyer_email'] = $order_info['email'];
		//$data['fields']['invoice'] = $this->session->data['order_id'] . ' - ' . html_entity_decode($order_info['payment_firstname'], ENT_QUOTES, 'UTF-8') . ' ' . html_entity_decode($order_info['payment_lastname'], ENT_QUOTES, 'UTF-8');
		$data['fields']['invoice'] = $this->session->data['order_id'];
		//$data['fields']['lc'] = $this->session->data['language'];

		$currCountryLang = strtoupper($order_info['payment_iso_code_2']);
		$allowed_Country_Lang = array(
			'AU' => 'AU',
			'AT' => 'AT',
			'BE' => 'BE',
			'BR' => 'BR',
			'CA' => 'CA',
			'CH' => 'CH',
			'CN' => 'CN',
			'DE' => 'DE',
			'ES' => 'ES',
			'GB' => 'GB',
			'FR' => 'FR',
			'IT' => 'IT',
			'NL' => 'NL',
			'PL' => 'PL',
			'PT' => 'PT',
			'RU' => 'RU',
			'US' => 'US',
			'DK' => 'da_DK',
			'HE' => 'he_IL',
			'ID' => 'id_ID',
			'JP' => 'ja_JP',
			'NO' => 'no_NO',
			'BR' => 'pt_BR',
			'LT' => 'ru_RU',
			'SE' => 'sv_SE',
			'TH' => 'th_TH',
			'TR' => 'tr_TR',
			'HK' => 'zh_HK',
			'TW' => 'zh_TW'
		);
		if (in_array($currCountryLang, array_keys($allowed_Country_Lang))) {
			$langCode = $allowed_Country_Lang[$order_info['payment_iso_code_2']];
		} else {
			$langCode = 'US';
		}
		$data['fields']['lc'] = $langCode;
		//$data['fields']['rm'] = '2';
		$data['fields']['charset'] = 'utf-8';

		$data['fields']['address_override'] = 'false';


		if (!$this->config->get($classname . '_transaction')) {
			$data['fields']['paymentaction'] = 'authorization';
		} else {
			$data['fields']['paymentaction'] = 'sale';
		}

		//$data['fields']['return'] = ($store_url . 'index.php?route=payment/' . $classname . '/pdt');
		//$data['fields']['return'] = ($store_url . 'index.php?route=checkout/success');
		//$data['fields']['return'] = ($store_url . 'catalog/controller/payment/pp_hosted_return.php');
		$data['fields']['return'] = ($store_url . 'index.php?route=payment/' . $classname . '/xreturn');
		$data['fields']['notify_url'] = ($store_url . 'index.php?route=payment/' . $classname . '/callback');

		if (method_exists($this->document, 'addBreadcrumb')) { //1.4.x
			if ($this->request->get['route'] != 'checkout/guest_step_3') {
				$data['fields']['cancel_return'] = ($store_url . 'index.php?route=checkout/payment');
			} else {
				$data['fields']['cancel_return'] = ($store_url . 'index.php?route=checkout/guest_step_2');
			}
		} else {
			$data['fields']['cancel_return'] = ($store_url . 'index.php?route=checkout/checkout');
		}

		$data['total'] = $total;

		$data['fields']['custom'] = $this->session->data['order_id'];

		if ($this->config->get($classname . '_debug')) { file_put_contents(DIR_LOGS . $classname . '_debug.txt', "FORM FIELDS\r\n" . print_r($data['fields'],1)); }

		# Compatibility
		if (version_compare(VERSION, '2.2', '>=')) { // v2.2.x Compatibility
			return $this->load->view($extension_type . '/'. $classname, $data);
		} elseif (version_compare(VERSION, '2.0', '>=')) { // v2.0.x Compatibility
			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/' . $extension_type . '/'. $classname . '.tpl')) {
				return $this->load->view($this->config->get('config_template') . '/template/' . $extension_type . '/'. $classname . '.tpl', $data);
			} else {
				return $this->load->view('default/template/' . $extension_type . '/'. $classname . '.tpl', $data);
			}
		} elseif (version_compare(VERSION, '2.0', '<')) {  // 1.5.x Backwards Compatibility
			$this->data = array_merge($this->data, $data);
			$this->id 	= 'payment';
			if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/' . $classname . '.tpl')) {
				$this->template = $this->config->get('config_template') . '/template/payment/' . $classname . '.tpl';
			} else {
				$this->template = 'default/template/payment/' . $classname . '.tpl';
			}
        	$this->render();
		}
	}

	private function fail($msg = false) {
		$failurl = $this->url->link('checkout/cart');
		// Mijo Support
		if (strpos(DIR_SYSTEM, 'mijo') !== false) { $failurl = str_replace('route', 'option=com_mijoshop&format=raw&tmpl=component&route', $failurl); }
		if (!$msg) { $msg = (!empty($this->session->data['error']) ? $this->session->data['error'] : 'Unknown Error'); }
		echo '<html><head><script type="text/javascript">';
		echo 'alert("'.addslashes($msg).'");';
		echo 'parent.location="' . $failurl . '";';
		echo '</script></head></html>';
		exit;
	}
	
	public function xreturn() {
		$url = $this->url->link('checkout/success');
		if (strpos(DIR_SYSTEM, 'mijo') !== false) { $url = str_replace('route', 'option=com_mijoshop&format=raw&tmpl=component&route', $url); }
		echo '<script language="Javascript">parent.location="'.$url.'"</script>';
		exit();
	}

	public function callback() {
		# Generic Init
		$extension_type 			= 'payment';
		$classname 					= str_replace('vq2-' . basename(DIR_APPLICATION) . '_' . strtolower(get_parent_class($this)) . '_' . $extension_type . '_', '', basename(__FILE__, '.php'));
		$data['classname'] 			= $classname;
		$data 						= array_merge($data, $this->load->language($extension_type . '/' . $classname));

		// Debug
		if ($this->config->get($classname . '_debug')) { file_put_contents(DIR_LOGS . $classname . '_debug.txt', __FUNCTION__ . "\r\nGET: " . print_r($_GET,1) . "\r\n" . "POST: " . print_r($_POST,1) . "\r\n", FILE_APPEND); }

		if (isset($_REQUEST['memo'])) {
			$memo = $_REQUEST['memo'];
		} else {
			$memo = '';
		}

		if (isset($_REQUEST['custom'])) {
			$order_id = ($_REQUEST['custom']);
		} else {
			$order_id = 0;
		}

	  	$this->load->model('checkout/order');
		$order_info = $this->model_checkout_order->getOrder($order_id);

		// If there is no order info then fail.
		if (!$order_info) {
			$this->session->data['error'] = $this->language->get('error_no_order');
			$this->fail();
		}

		$postdata = $_REQUEST;

		// need to add ipn verification check
		/*
		$request = 'cmd=_notify-validate';

		$get_magic_quotes_exists = false;
	    if (function_exists('get_magic_quotes_gpc')) {
	        $get_magic_quotes_exists = true;
	    }

		foreach ($_REQUEST as $key => $value) {
			if ($get_magic_quotes_exists && get_magic_quotes_gpc() == 1) {
				//$request .= '&' . $key . '=' . urlencode(stripslashes($value));
				$request .= '&' . $key . '=' . urlencode($value);
			} else {
				//$request .= '&' . $key . '=' . urlencode(stripslashes($value));
				$request .= '&' . $key . '=' . urlencode($value);
				//$request .= '&' . $key . '=' . html_entity_decode(urlencode($value));
			}
		}

		if (!$this->config->get($classname . '_test')) {
			$ch = curl_init('https://securepayments.paypal.com/acquiringweb?cmd=_hosted-payment');
		} else {
			$ch = curl_init('https://securepayments.sandbox.paypal.com/acquiringweb');
		}

		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($request)));
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_VERBOSE, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

		$response = curl_exec($ch);

		curl_close($ch);

		if ($this->config->get($classname . '_debug')) {
			$this->log->write("PP_HOSTED :: IPN REQ  --> $request");
			$this->log->write("PP_HOSTED :: IPN RESP <-- $response");
		}

		if (!$this->validate($this->request->post)) {
			if ($this->order_info['order_status_id'] == '0') {
				$this->model_checkout_order->confirm($order_id, $this->config->get($classname . '_order_status_id_pending'), $memo . "\r\n\r\n" . $this->error);
			} elseif ($this->order_info['order_status_id'] != $this->config->get($classname . '_order_status_id')) {
				$this->model_checkout_order->update($order_id, $this->config->get($classname . '_order_status_id_pending'),  $this->error, FALSE);
			}
			mail($this->config->get('config_email'), sprintf($this->language->get('text_attn_email'), $order_id), $this->error . "\r\n\r\n" . str_replace("&", "\n", $p_msg));
		}

		$verified = false;
		if (strcmp($response, 'VERIFIED') == 0) {
			$verified = true;
		}
		*/
		$verified = true;

		//$updateComment = $postdata['reason_code'];
		$updateComment  = 'Paypal Transaction ID: ' . $postdata['txn_id'] . "\r\n";
		$updateComment .= ('Paypal Status: ' . isset($postdata['payment_status']) ? $postdata['payment_status'] : 'N/A');

		switch($postdata['payment_status']){
			case 'Completed':
				$order_status_id = $this->config->get($classname . '_order_status_id');
				break;
			case 'Canceled_Reversal':
				$order_status_id = $this->config->get($classname . '_order_status_id_canceled_reversal');
				break;
			case 'Denied':
				$order_status_id = $this->config->get($classname . '_order_status_id_denied');
				break;
			case 'Failed':
				$order_status_id = $this->config->get($classname . '_order_status_id_failed');
				break;
			case 'Pending':
				$order_status_id = $this->config->get($classname . '_order_status_id_pending');
				$updateComment .= "\r\n" . $postdata['pending_reason'];
				break;
			case 'Refunded':
				$order_status_id = $this->config->get($classname . '_order_status_id_refunded');
				break;
			case 'Reversed':
				$order_status_id = $this->config->get($classname . '_order_status_id_reversed');
				break;
			default:
				$order_status_id = $this->config->get($classname . '_order_status_id_unspecified');
		}

		if (isset($postdata['payment_type']) && $postdata['payment_type'] == 'echeck') {
			$order_status_id = $this->config->get('config_order_status_id');
		}

		if (!$verified) {
			//$order_status_id = $this->config->get('config_order_status_id');
		}

		// Update Order
		if (version_compare(VERSION, '2.0', '>=')) { // v20x
			$this->model_checkout_order->addOrderHistory($order_id, $order_status_id, $updateComment, true);
		} else { //v15x
			$this->model_checkout_order->confirm($order_id, $order_status_id, $updateComment);
		}

		if ($postdata['payment_status'] != 'Completed') {
			if (!isset($postdata['payment_type']) || (isset($postdata['payment_type']) && $postdata['payment_type'] == 'echeck')) {
				mail($this->config->get('config_email'), sprintf($this->language->get('text_attn_email'), $order_id), ($this->language->get('error_non_complete')));
			}
		}

		$this->db->query("UPDATE `" . DB_PREFIX . "order` SET `payment_method` = '" . $this->language->get('text_title') . " (Paypal Txn ID: " . $this->db->escape($postdata['txn_id']) . ")' WHERE `order_id` = '" . (int)$order_id . "'");

		$this->response->redirect($this->url->link('checkout/success'));
	}

	private function file_get_contents_curl($url) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

		$data = curl_exec($ch);

		curl_close($ch);

		return $data;
	}

	private function validate($data = array()) {
		$data = array_merge($data, $this->load->language('payment/' . $classname));

		// verify there was some response
		if (empty($data)) {
			$this->error = $this->language->get('error_no_data');
		}

		// verify totals match
		if (isset($data['cc'])) { // PDT
			$currency = $data['cc'];
		} elseif (isset($data['mc_currency'])) { // IPN
			$currency = $data['mc_currency'];
		} else { // Default
			$currency = $order_info['currency'];
		}

		if (isset($data['payment_gross']) && $data['payment_gross']) {
			$amount = $data['payment_gross'];
		} elseif (isset($data['mc_gross']) && $data['mc_gross']) {
			$amount = $data['mc_gross'];
		}

        if (isset($data['payment_status']) && $data['payment_status'] != 'Refunded' && ((float)floor($amount) != (float)floor($this->currency->format($order_info['total'], $currency, False, False)))) {
			$this->error = sprintf($this->language->get('error_amount_mismatch'), $amount, $order_info['total']);
		}

    	if (!$this->error) {
			return TRUE;
    	} else {
    		$this->log->write("PP_HOSTED :: VALIDATION FAILED : $this->error");
      		return FALSE;
    	}
	}
}
?>