<?php 



class ControllerPotentialOrder extends Controller {

	var $error = array();

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

  	function index() {

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

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

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

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

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

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

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

    	$template->set('content', $this->getForm());

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

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

  	}

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

  	function getForm() {        	

	

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        

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

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

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

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

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

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

		$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_order_history', $language->get('text_order_history'));

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

 /*    	echo "<script>alert('reference=".$_REQUEST['reference']."');</script>";

     	echo "<script>alert('order_id=".$_REQUEST['order_id']."');</script>"; */

 

		 if(isset($_REQUEST['reference'])&&!empty($_REQUEST['reference'])){

			$order_info = $database->getRow("select * from `order_data` where reference = '".$_REQUEST['reference']."'"); 

		 }else if(isset($_REQUEST['order_id'])&&!empty($_REQUEST['order_id'])){

			$order_info = $database->getRow("select * from `order_data` where order_id = ".$_REQUEST['order_id']); 			

		 }else{ 

			echo "<script language=\"JavaScript\">alert(\"can not find order by order_id and reference, load recent order\");</script>";		

			$order_info=$database->getRow("select * from order_data where customer_id='".$customer->getId()."' order by order_id desc");			

		 }		 

		

        if (!$order_info)

		{

			$order_id=$_REQUEST['order_id']; $reference = $_REQUEST['reference'];

			echo "<script language=\"JavaScript\">alert(\"Tips: Load order=$order_id reference=$reference failure @ catalog/controller/potiential_order.php line 95\");</script>";			

			exit;

		}

		 if ($order_info['order_status']) {		 	

		 	$view->set('action','cancel');			

		 }else{

		 	$view->set('action','delete');

		 }

		 

		$Reference = $order_info['reference']; //不管是那种方式传递过来的，都要给与正确的订单号

		$order_data  = unserialize($order_info['data']);	

		$order->data=$order_data; // 把从数据库读出来的数据值复制给Order实例		    

      

		$view->set('email', $order_data['email']);

		$view->set('telephone', $order_data['telephone']);

		 

		  $view->set('tag_id',$order_info['order_id']);

    	  $shipping_address = array(

      		'firstname' => trim($order_data['shipping_firstname']),

      		'lastname'  => trim($order_data['shipping_lastname']),

      		'company'   => $order_data['shipping_company'],

      		'address_1' => $order_data['shipping_address_1'],

      		'city'      => $order_data['shipping_city'],

      		'postcode'  => $order_data['shipping_postcode'],

      		'zone'      => $order_data['shipping_zone'],

      		'country'   => $order_data['shipping_country']

    	);



    	$view->set('shipping_address', $address->format($shipping_address, $order_data['shipping_address_format'], '<br />'));

    	$view->set('shipping_method', $order_data['shipping_method']);

		$view->set('checkout_payment', $url->ssl('checkout_payment')); // 修改支付方式的Change按钮的链接

		

		$payment_address = array(

      		'firstname' => $order_data['payment_firstname'],

      		'lastname'  => $order_data['payment_lastname'],

      		'company'   => $order_data['payment_company'],

      		'address_1' => $order_data['payment_address_1'],

      		'city'      => $order_data['payment_city'],

      		'postcode'  => $order_data['payment_postcode'],

      		'zone'      => $order_data['payment_zone'],

      		'country'   => $order_data['payment_country']

    	);    	

    	

    	$view->set('payment_address', nl2br($address->format($payment_address, $order_data['payment_address_format'])));

    	$view->set('payment_method', $order_data['payment_method']);

		//==============================================================================================================================================================================

$product_data  = array();

    	foreach ($order_data['products'] as $product) {

	        $currency_info=$database->getRow("select * from currency where code='".$order_data['currency']."'");

	        $image_info=$database->getRow("select i.filename from product p left join image i on p.image_id=i.image_id where p.product_id='".$product['product_id']."'");

			$price=(strlen($product['price'])>6)?$product['price']:$currency_info['symbol_left'].' '.round($product['price']*$order_data['value'],2);

			$total=(strlen($product['total'])>6)?$product['total']:$currency_info['symbol_left'].' '.round($product['total']*$order_data['value'],2);

	         if( !empty( $product['option'] ) )

			 {

	        	$product_option_info=$database->getRow('select pto.product_to_option_id from `option` o left join `option_value` ov on o.option_id=ov.option_id left join `product_to_option` pto on pto.option_id=o.option_id where pto.product_id="'.$product['product_id'].'" and o.name="'.$product['option'][0]['name'].'" and ov.name="'.$product['option'][0]['value'].'"');

	        	$product_data[] = array(

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

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

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

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

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

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

	          		'product_to_option_id'=>$product_option_info['product_to_option_id'],

	          		'price'    => $price, 

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

					'total'    => $total

	        	);

	        }else {

	        	 $product_data[] = array(

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

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

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

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

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

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

	          		'price'    => $price, 

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

					'total'    => $total

	        	);

	        }        	

    	}

        $arr_product_id=array();

        foreach($product_data as $k=>$pd)

        {  

             $arr_product_id[$k]=$pd['id'];

               if(isset($pd['product_to_option_id'])){

             	$arr_product_to_option_id[$k]=$pd['product_to_option_id'];

             }    

        }      

       if(isset($arr_product_to_option_id)){

        	$view->set('arr_product_to_option_id',implode(',',$arr_product_to_option_id));

        }

		

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

		$view->set('arr_product_id',implode(',',$arr_product_id));  

//===========================================================================================================================

		// 点了使用优惠劵按钮

		$use_coupon=0;

		$coupon_code="";

		$message="";

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

		 {			 		 

		 	$coupon_code=$_POST['coupon'];

			

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

		 

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

			$use_coupon=1;

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

				

				$order_data=$order->data;

				

				$message=$language->get('text_coupon');

			}

			else

			{

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

				$use_coupon=3;				

			    $message=$language->get('error_coupon');	

			}		

		 }

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

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

		 if ($use_coupon!=2)

		 {			

			$totals = $calculate->getTotals();

		 }	

		 if ( @$order_data['coupon_id'] )

		 {

			 $view->set('coupon_vaild', $coupon->isValid($order_data['coupon_id']));

		 }

		 else

		 {

			 $view->set('coupon_vaild', true);

		 }

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

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

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

	  	$view->set('Currency', $order_data['currency']);					

		

//==================================================================================================================================================

						$usd_value= number_format(end(array_slice(end($order_data['totals']), -2, 1)), 2, '.', '');  	

		                $currency_info=$database->getRow("select code,value,symbol_left  from currency where code ='".$order_data['currency']."'");

                        $currency_value=number_format($usd_value*$currency_info['value'], 2, '.', '');  

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

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

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

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

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

			

	$methods = $payment->getMethods();	

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

//	print_r($order_data);exit;

    if(isset($order_data['payment_method_id'])){

    	$view->set('payment_method_code', $order_data['payment_method_id']);

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

    }else{

    	    $order->set('payment_method_id', 'amopay');

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

    	    $order->save($Reference);	     	    	

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

			$view->set('payment_method_code', 'amopay');					

		}	   	

   		

	    //付款提醒设置

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

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

		



		//客户资料

		$customer_info=$database->getRow("select customer_id,current_points from customer where customer_id='".$customer->getId()."'");

	

		$view->set("customer_info",$customer_info);	



		// 显示视图页面

		return $view->fetch('content/potential_order.tpl');



  	}

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

  	function cancel()

	{

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

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

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

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

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

//		$sql = "delete from order_data where reference = '?' and customer_id='?'"; // 删除订单

	    $sql = "update order_data set order_status=0 where reference = '?' and customer_id='?'"; // 取消订单

		$database->query($database->parse($sql, $request->get('reference'),$customer->getId()));		

		

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

	}

	

	function delete()

	{

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

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

		$database =& $this->locator-