<?php



class ControllerCheckoutConfirm extends Controller { 



	var $error = array();

	

/*****************************************************************************************************************************************************/

	function index() {      



		$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');



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



		$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');

		

		// 页面调用前进行合法性检查， 判断是否登录， 是否购物车有产品，产品是否都有库存， 是否设置了发货地址，是否选择了付款方式等

	if (!$customer->isLogged()&&!isset($_POST)) {

			$session->set('redirect', $url->ssl('checkout_shipping'));

	  		$response->redirect($url->ssl('account_login'));

    	}

    	elseif(isset($_POST)&&isset($_POST['cancel_return'])){



        	



        	echo '



        	       <form action="https://www.paypal.com/cgi-bin/webscr" method="post"  id="form" name="form">



        	       



        	          <input type="hidden" name="cmd" value="'.$_POST['cmd'].'" />



        	          <input type="hidden" name="business" value="wutingjing@hotmail.com" />



        	          <input type="hidden" name="item_name" value="'.$_POST['item_name'].'" />



        	          <input type="hidden" name="currency_code" value="'.$_POST['currency_code'].'" />



        	           <input type="hidden" name="amount" value="'.$_POST['amount'].'" />



        	          <input type="hidden" name="first_name" value="'.$_POST['first_name'].'" />



        	          <input type="hidden" name="last_name" value="'.$_POST['last_name'].'" />



        	          <input type="hidden" name="address1" value="'.$_POST['address1'].'" />
        	          
        	          
        	          <input type="hidden" name="charset" value="utf-8" />
        	           
        	          <input type="hidden" name="lc" value="US" />



        	          <input type="hidden" name="city" value="'.$_POST['city'].'" />



        	          <input type="hidden" name="zip" value="'.$_POST['zip'].'" />



        	          <input type="hidden" name="country" value="'.$_POST['country'].'" />



        	          <input type="hidden" name="address_override" value="0" />



        	          <input type="hidden" name="notify_url" value="https://www.beststoreitems.com/payment/paypal/paypal_notify.php" />



        	          <input type="hidden" name="email" value="'.$_POST['email'].'" />



        	           <input type="hidden" name="invoice" value="'.$_POST['invoice'].'" />



        	          <input type="hidden" name="return" value="https://www.beststoreitems.com/paypal_sucess.html" />



        	          <input type="hidden" name="rm" value="2" />



        	          <input type="hidden" name="no_note" value="1" />



        	          <input type="hidden" name="cancel_return" value="https://www.beststoreitems.com/paypal_cancel.html" />



        	          



        	          <script language="javascript">



						   document.form.submit();



					  </script>



				   </form>	 



        	';



        	exit;



        }

        // 购物车是否有产品

    	if ((!$cart->hasProducts())) { //  || ((!$cart->hasStock()) && (!$config->get('config_stock_checkout')))



	  		$response->redirect($url->ssl('cart'));

    	}

       // 是否选择了发货方式

    	if ($cart->hasShipping()) {

    		if (!$session->get('shipping_address_id')) {

	  			$response->redirect($url->ssl('checkout_address', 'shipping'));

    		}

		} else {	

			$session->delete('shipping_method');

		}

        // sessionL里是否记录了付款方式， 该付款方式是否存在

		if (!$session->get('payment_method')) {

	  		$response->redirect($url->ssl('checkout_payment'));

    	}

    	if (!$payment->hasMethod($session->get('payment_method'))) {

	  		$response->redirect($url->ssl('checkout_payment'));

		}

		$language->load('controller/checkout_confirm.php');

    	$template->set('title', $language->get('heading_title')); 

		$view = $this->locator->create('template');



     

		// 如果调用页面有传递订单号过来就用它的订单号，如果没有的话就自己生产新的订单号

		 if(isset($_REQUEST['reference'])){

			$Reference=$_REQUEST['reference'];

		 }else{ // 如果调用页没有传递订单号过来的话，则随机生成一个新的订单号

			 $Reference=$order->getReference();

//			 echo $Reference;

/*			 echo "<script language=\"JavaScript\">alert(\"no reference, get a new reference @ catalog/controller/checkout_confirm.php line 92\");</script>";*/

		 }

        $view->set('reference',$Reference); 

		

    	$view->set('heading_title', $language->get('heading_title'));



    	$view->set('text_shipping_address', $language->get('text_shipping_address'));



    	$view->set('text_shipping_method', $language->get('text_shipping_method'));



    	$view->set('text_payment_address', $language->get('text_payment_address'));



    	$view->set('text_payment_method', $language->get('text_payment_method'));



    	$view->set('text_your_comments', $language->get('text_your_comments'));



    	$view->set('text_change', $language->get('text_change'));



    	$view->set('text_product', $language->get('text_product'));



    	$view->set('text_model', $language->get('text_model'));



    	$view->set('text_quantity', $language->get('text_quantity'));



    	$view->set('text_price', $language->get('text_price'));



    	$view->set('text_total', $language->get('text_total'));



		$view->set('entry_coupon', $language->get('entry_coupon'));



    	$view->set('button_continue', $language->get('button_continue'));



		$view->set('button_back', $language->get('button_back'));



    	$view->set('button_update', $language->get('button_update'));



		$view->set('error', @$this->error['message']);		

		

    	$view->set('message', $session->get('message'));



		$session->delete('message');			

		

		if (($request->isPost()) && ($request->get('address_id', 'post'))) {

	    $session->set($request->get('change_address_type', 'post').'_address_id', $request->get('address_id', 'post')); 

		}

		$address_id=$request->get('address_id', 'post');

/*		echo "<script>alert('address_id=$address_id');</script>"; */

		

	

    	$view->set('shipping_address', $address->getFormatted($session->get('shipping_address_id'), '<br />'));



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



    	$view->set('checkout_shipping', $url->ssl('checkout_shipping'));



    	$view->set('checkout_shipping_address', $url->ssl('checkout_address', 'shipping'));



		$view->set('payment_address', $address->getFormatted($session->get('payment_address_id'), '<br />'));



		$view->set('payment_method_code', $session->get('payment_method'));



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

    	

    	$view->set('checkout_payment', $url->ssl('checkout_payment'));



    	$view->set('checkout_payment_address', $url->ssl('checkout_address', 'payment'));	



    	$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'],



//        		'model'      => $product['model'],



        		'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')))

      		); 

    	} 



    	

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

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

		$view->set('back', $url->ssl('checkout_payment'));

		

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

	

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



		$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('comment', $session->get('comment'));

		$totals=array();

	  	// 点应用优惠劵按钮, 并且刷新的时候都会来到这里

		$use_coupon=0;

		$coupon_code="";

  		if($request->get('apply_coupon')&& $_POST['coupon'])

		 {			 		 

		 $coupon_code=$_POST['coupon'];

		 

/*		 echo "<script>alert('apply_coupon=$coupon_code');</script>"; */

		 

			// 使用优惠劵，如果使用成功，则Coupon被载入， (使用的时候优惠劵面值要小于订单金额)

			$use_coupon=0;

			if ($coupon->set($request->get('coupon', 'post')))

			{

/*				echo "<script>alert('use coupon successfully=$coupon_code');</script>"; */

				$use_coupon=2;

				

				// 优惠劵载入后再次请求获取totals值，此时优惠劵的值已经导入totals数组里了

				$totals = $calculate->getTotals();			

				

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

				// 保存订单，优惠劵的值在totals里，相当于保存了优惠劵

				

				$order->set('coupon_id', $coupon->getId());

				// 设置新的totals给当前实例，然后保存成新订单

				

		  		$order->save($Reference);	          

				

				$response->redirect("index.php?controller=potential_order&reference=$Reference");

			}

			else

			{

/*				echo "<script>alert('use coupon failure=$coupon_code');</script>"; */

				$use_coupon=3;

				

			    $view->set('message', $language->get('error_coupon'));	

			}

		

		 }

		 if ($use_coupon!=2)

		 {	

			 $totals = $calculate->getTotals();

		 }	

	

		// 把totals设置到几个对象里面

		$view->set('coupon', $coupon_code);

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

//      var_dump($totals); exit;

//==================================================================付款跳转链接设置============================================================================

//

		$view->set('Currency', $currency->getCode());	

			$MerchantOrderID=$Reference.'-'.rand(10,99);

			$view->set('MerchantOrderID', $MerchantOrderID);

			$usd_total=$calculate->getTotalUsd();

			$view->set('ApplyUSD', $usd_total);

			$currency_info=$database->getRow("select value from currency where code ='".$currency->getCode()."'");

        	$currency_total=number_format($usd_total*$currency_info['value'], 2, '.', ''); 

			$view->set('ApplyMoney', $currency_total);

			

	    	if($session->get('payment_method')=='amopay')

			{ 

				$view->set('payment_url', HTTP_SERVER.'index.php?controller=amopay&reference='.$Reference);		

				date_default_timezone_set('Asia/Hong_Kong');

		  				$china_time=date('Y-m-d H:i:s',time());

		  				$SubmitTime = str_replace(':',"",str_replace('-',"",$china_time));

		  				$SubmitTime = str_replace(' ',"",$SubmitTime);

		  				$view->set('SubmitTime', $SubmitTime);							

			}

//		 echo $session->get('payment_method');exit;

	     $view->set('payment_url', HTTP_SERVER.'index.php?controller='.$session->get('payment_method').'&reference='.$Reference);

//

//==================================================================付款跳转链接设置============================================================================		

		

		//付款提醒设置

		$payment_setting=$database->getRow("select * from payment_setting");



	  	$view->set('payment_setting', $payment_setting);

		

		// 显示视图

    	$template->set('content', $view->fetch('content/checkout_confirm.tpl'));



		$template->set($module->fetchPublic());



		$response->set($template->fetch('layout.tpl'));	

	}

	

/*****************************************************************************************************************************************************/

function paylater() {



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

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

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

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

		$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');

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

		$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');

			

		// 合法性检查，调用该页面生成订单的前提条件，例如要客户先登录，购物车有产品，选择了发货方式和付款方式

    	if (!$customer->isLogged()) {

			$session->set('redirect', $url->ssl('checkout_shipping'));

	  		$response->redirect($url->ssl('account_login'));

			}

    	if ((!$cart->hasProducts()) || ((!$cart->hasStock()) && (!$config->get('config_stock_checkout')))) {

	  		$response->redirect($url->ssl('cart'));

    	}

    	if ($cart->hasShipping()) {

    		if (!$session->get('shipping_address_id')) {

	  			$response->redirect($url->ssl('checkout_address', 'shipping'));

				}

		} else {

			$session->delete('shipping_method');

			}

		if (!$session->get('payment_method')) {

	  		$response->redirect($url->ssl('checkout_payment'));

    	}

    	if (!$payment->hasMethod($session->get('payment_method'))) {

	  		$response->redirect($url->ssl('checkout_payment'));

    	}

    	if (!$address->has($session->get('payment_address_id'))) { 

	  		$response->redirect($url->ssl('checkout_address', 'payment'));

    	}

		

		// 通过页面调用合法性检查后，开始提取数据生成订单

		$language->load('controller/checkout_confirm.php');

    	$template->set('title', $language->get('heading_title')); 	 	

	

    	$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'],

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

        		'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')))



      		); 

    	}     	

       

	   //生成订单开始   

		$totals = $calculate->getTotals();	

		

		$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('comment', $session->get('comment'));

		$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'));			

			

		$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'],



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



        		'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('total', $cart->getTotal());

		

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

		

/*		$order->set('email_subject', $language->get('email_subject', $order->getReference()));

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

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

	      

		// 前面设置数据到Order对象里后，在开始保存订单到数据库

		$session->delete('reference'); // 删除session里面记录的订单号

		$order->save($order->getReference());		

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

		$response->redirect($url->ssl('account'));

	}	

/*****************************************************************************************************************************************************/	

}

?>



