<?php
class ControllerPaypal extends Controller { 
	var $error = array();
	function index() {    		
//        phpinfo(); exit;
//		ini_set("display_errors", "On");

		$config    =& $this->locator->get('config');
		$customer  =& $this->locator->get('customer');
		$database  =& $this->locator->get('database');
		$language  =& $this->locator->get('language');
		$order     =& $this->locator->get('order');
		$request   =& $this->locator->get('request');
	    $cart      =& $this->locator->get('cart'); 
	    $currency  =& $this->locator->get('currency');
	    $url      =& $this->locator->get('url');
	    
 		if (!isset($_REQUEST['reference'])) { exit; }
		
		 $order_info = $database->getRow("select order_id,data,reference from `order_data` where reference = '".$_REQUEST['reference']."'");
//		 	exit('come'); 
		  if(!$order_info)
    	 {
    	 	$this->checkoutorder($_REQUEST['reference']);

			$order_info=$database->getRow("select order_id,data,reference from `order_data` where reference = '".$_REQUEST['reference']."'");
			if (!$order_info)
			{
				echo "<script language=\"JavaScript\">alert(\"Update order failure, return @ catalog/controller/dhpay.php line 38\");</script>";
				exit;
			}
    	 }
    	 
    	 $order_data=unserialize($order_info['data']);    
    	 
		 switch ($order_data['currency'])
			{
				case 'USD':
				case 'DKK':
				case 'ILS':
				case 'RUB':
				case 'CAD':
			    case 'HUF':
			    case 'MXN':
			    case 'NOK':
			    case 'CZK':
			    case 'SGD':
			    case 'NZD':
			    case 'JPY':
			    case 'EUR':
			    case 'PLN':
			    case 'THB':
			    case 'AUD':
			    case 'SEK':	
			    case 'CHF':
			    case 'GBP':
			    case 'PHP':						   
				{
					$currency=$order_data['currency']; 
					$amount=$_POST['ApplyMoney']; 
					
					break;
				}
				default:
				{
					$currency='USD'; 
					$amount=$_POST['ApplyUSD'];
					break;
				}
			}
				
    
      	 $first_name=$order_data['firstname'];
		 $last_name=$order_data['lastname'];
        
		 $address=$order_data['shipping_address_1'];
		 $city=$order_data['shipping_city'];
		 $zip=empty($order_data['shipping_postcode'])?'12345':$order_data['shipping_postcode'];	 
			
		 $ship_country=$database->getRow("select country_id, iso_code_2 from country where name='".$order_data['shipping_country']."'");
         $country_code = $ship_country['iso_code_2'];
         $country_zone=$database->getRow("select code from zone where country_id= '".$ship_country['country_id']."' AND name LIKE '".$order_data['shipping_zone']."'"); 
         $state_code=empty($country_zone)?00000:$country_zone['code'];
                    
		$business=$config->get('paypal_email'); // 设置收款邮箱
		$buyer_email=$order_data['email'];
		$reference=$order_info['reference'];     
		$paypal_notify=$url->ssl('paypal_notify');
		$paypal_sucess=$url->ssl('paypal_sucess'); 
		$paypal_cancel=$url->ssl('paypal_cancel'); 
		
/* Do not upload shopping cart information */ 
/*		  $parameter = array(
				'cmd'	=> "_xclick",	
				'business'	=> $config->get('paypal_email'),
				'invoice'	=> $order_info['reference'],
				'item_name'	=> $order_info['order_id'],		
				'currency_code'	=> $currency,		
				'amount'	=> $amount,			
				'email'	=> $buyer_email,
				'address_override'	=> 0,
				'first_name'	=> $first_name,
				'last_name'	=> $last_name,
				'country'	=> $order_data['shipping_country'],	// $country_code
				'state'	=> $state_code,		
				'zip'	=> $zip,				
				'city'	=> $city,
				'address1'	=> $address,	
				'lc'	=> "US",	
				'rm'	=> 2,
				'no_note'	=> 1,						
				'return'	=> $paypal_sucess,					
				'cancel_return'	=> $paypal_cancel,
				'notify_url'	=> $paypal_notify		
		); */
		
// upload shopping cart infomation
			$parameter = array(
				'cmd'	=> "_xclick",
				'business'	=> $config->get('paypal_email'),
				'invoice'	=> $order_info['reference'],	
				'item_name'	=> $order_info['reference'],			
				'currency_code'	=> $currency,
				'amount'	=> $amount,		
				'email'	=> $buyer_email,
				'address_override'	=> 0,
				'first_name'	=> $first_name,
				'last_name'	=> $last_name,
				'country'	=> $order_data['shipping_country'],					
				'zip'	=> $zip,				
				'city'	=> $city,
				'address1'	=> $address,					
				'charset'	=> "utf-8",	
				'lc'	=> "US",	
				'rm'	=> 2,
				'no_note'	=> 1,						
				'return'	=> $paypal_sucess,					
				'cancel_return'	=> $paypal_cancel,
				'notify_url'	=> $paypal_notify		
		);
		
		
//		print_r($parameter);	exit;
/*		foreach ($parameter as $key => $value) {
	    	echo $key."=>".$value."<br/>";
		}exit; */
		
		 $sHtml = "<form id='paypal_submit' name='paypal_submit' action='https://www.paypal.com/cgi-bin/webscr' method='post'>";
		while (list ($key, $value) = each ($parameter)) {
            $sHtml.= "<input type='hidden' name='".$key."' value='".$value."'/>";
        }
        $sHtml.= "<input type='submit' value='you are redirecting to paypal offical website..., Please be patient to wait'>";         
		$sHtml.="<script>document.forms['paypal_submit'].submit();</script></form>";
		echo($sHtml);
		exit;  
  	}

  	function checkoutorder($reference)
	{

		$address   =& $this->locator->get('address');

		$calculate =& $this->locator->get('calculate');

		$cart      =& $this->locator->get('cart');

		$config    =& $this->locator->get('config');

	$coupon   =& $this->locator->get('coupon');

		$currency  =& $this->locator->get('currency');

		$customer  =& $this->locator->get('customer');

		$database  =& $this->locator->get('database');

		$language  =& $this->locator->get('language');

		$module    =& $this->locator->get('module');

		$order     =& $this->locator->get('order');

		$payment   =& $this->locator->get('payment');

		$request   =& $this->locator->get('request');

		$session   =& $this->locator->get('session');

		$shipping  =& $this->locator->get('shipping');

		$tax       =& $this->locator->get('tax');

		$template  =& $this->locator->get('template');

		$url       =& $this->locator->get('url');

		$image    =& $this->locator->get('image');

	    $sql="select vip_rank from customer where customer_id='?'";

        $profile=$database->getRow($database->parse($sql, (int)$customer->getId()));

	    $vip_rank=$profile['vip_rank'];

	    $sql_vip="select discount from vip where vip_rank='$vip_rank'";

	    $discount=$database->getrow($sql_vip);

	    $vip_discount=$discount['discount'];

		$totals = $calculate->getTotals($vip_discount);

    	$product_data = array();

    	foreach ($cart->getProducts() as $product) {
      		$option_data = array();

      		foreach ($product['option'] as $option) {
        		$option_data[] = array(

          			'name'  => $option['name'],

          			'value' => $option['value']
        		);
      		}
      		$product_data[] = array(

				'product_id' => $product['product_id'],

        		'href'       => $url->href('product', FALSE, array('product_id' => $product['product_id'])),

        		'name'       => $product['name'],        	

        		'thumb'    => $image->resize($product['image'], 100, 100),

        		'option'     => $option_data,

        		'quantity'   => $product['quantity'],

				'tax'        => $tax->getRate($product['tax_class_id']),

        		'price'      => $currency->format($tax->calculate($product['price'], $product['tax_class_id'], $config->get('config_tax'))),
        		
        		'amount'      => $tax->calculate($product['price'], $product['tax_class_id'], $config->get('config_tax')),

				'discount'   => ($product['discount'] ? $currency->format($tax->calculate($product['price'] - $product['discount'], $product['tax_class_id'], $config->get('config_tax'))) : NULL),

        		'total'      => $currency->format($tax->calculate($product['total'], $product['tax_class_id'], $config->get('config_tax')))
      		);
    	}

		$order->set('products', $product_data);

		$order->set('totals', $totals);

		$order->set('customer_id', $customer->getId());

		$order->set('firstname', $customer->getFirstName());

		$order->set('lastname', $customer->getLastName());

		$order->set('email', $customer->getEmail());

		$order->set('telephone', $customer->getTelephone());

		$order->set('order_status_id', $config->get('config_order_status_id'));

		$order->set('total', $cart->getTotal());

		$order->set('currency', $currency->getCode());

		$order->set('value', $currency->getValue($currency->getCode()));

		$order->set('ip', $_SERVER['REMOTE_ADDR']);

		$order->set('shipping_firstname', $address->getFirstName($session->get('shipping_address_id')));

		$order->set('shipping_lastname', $address->getLastName($session->get('shipping_address_id')));

		$order->set('shipping_company', $address->getCompany($session->get('shipping_address_id')));

		$order->set('shipping_address_1', $address->getAddress1($session->get('shipping_address_id')));

		$order->set('shipping_city', $address->getCity($session->get('shipping_address_id')));

		$order->set('shipping_postcode', $address->getPostCode($session->get('shipping_address_id')));

		$order->set('shipping_zone', $address->getZone($session->get('shipping_address_id')));

		$order->set('shipping_country', $address->getCountry($session->get('shipping_address_id')));

		$order->set('shipping_address_format', $address->getFormat($session->get('shipping_address_id')));

		$order->set('shipping_method', $shipping->getTitle($session->get('shipping_method')));

		$order->set('payment_firstname', $address->getFirstName($session->get('payment_address_id')));

		$order->set('payment_lastname', $address->getLastName($session->get('payment_address_id')));

		$order->set('payment_company', $address->getCompany($session->get('payment_address_id')));

		$order->set('payment_address_1', $address->getAddress1($session->get('payment_address_id')));

		$order->set('payment_city', $address->getCity($session->get('payment_address_id')));

		$order->set('payment_postcode', $address->getPostCode($session->get('payment_address_id')));

		$order->set('payment_zone', $address->getZone($session->get('payment_address_id')));

		$order->set('payment_country', $address->getCountry($session->get('payment_address_id')));

		$order->set('payment_address_format', $address->getFormat($session->get('payment_address_id')));

		$order->set('payment_method', $payment->getTitle($session->get('payment_method')));

		$order->set('payment_method_id', $session->get('payment_method'));		
			
/*		$order->set('email_subject', $language->get('email_subject', $reference));

		$order->set('comment', $session->get('comment'));

		//$order->set('email_html', $email->fetch('content/checkout_email.tpl'));

		$order->set('email_text', $language->get('email_message', $config->get('config_store'), $reference, $url->ssl('account_invoice', FALSE, array('reference' => $reference)), date($language->get('date_format_long')), strip_tags($session->get('comment')))); */

		$order->save($reference);
   }
  
}

?>
