<?php







class Order {







	var $reference = NULL;



	var $data      = array();



	var $browser   = NULL;



	//var $expire    = 3600;







 	var $expire    = 2592000; // 订单的有效期是30天, 30×24×3600秒







	function __construct(&$locator) {		







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



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



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



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



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



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



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



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



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



	}







	function getData() {



		return (isset($this->data) ? $this->data : NULL);



	}



	function getReference() {



	// 如果当前实例里的订单号为NULL，则产生一个新订单号



	 	if(NULL==$this->reference){



	 	$random   = strtoupper(uniqid());



		$this->reference = substr($random, 0, 5) . '-' . substr($random, 5, 5) . '-' . substr($random . rand(10, 99), 10, 5);



	    }	 



		return $this->reference;



	}



	function setReference($reference) {



	// 如果当前实例里的订单号为NULL，则产生一个新订单号



	    $this->reference=$reference;



	}



	function set($key, $value) {



		$this->data[$key] = $value;



	}







	function get($key) {



		return (isset($this->data[$key]) ? $this->data[$key] : NULL);



	}



	



	function GetAmountUSD() {



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



		return $usd_value;



	}



function GetAmount() {			



		



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



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



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



		return $currency_value;



	}



	



	function load($reference) {			



		$sql        = "select distinct * from order_data where reference = '?'";



		$order_info = $this->database->getRow($this->database->parse($sql, $reference));



		if ($order_info) {



			$this->reference = $reference;



			$this->data      = unserialize($order_info['data']);



			$this->browser      = $order_info['browser'];



			return TRUE;







		} else {



			$sql        = "select distinct * from order_data where order_id = '?'";



			$order_info = $this->database->getRow($this->database->parse($sql, $reference));



			$this->reference = $reference;



			$this->data      = unserialize($order_info['data']);



			$this->browser      = $order_info['browser'];



			return TRUE;



		}



		return FALSE;



	}



	function load_by_id($order_id) {	



		$sql  = "select distinct * from order_data where order_id = '?'";







		$order_info = $this->database->getRow($this->database->parse($sql, $order_id));



		if ($order_info) {







			$this->reference = $order_info['reference'];







			$this->data      = unserialize($order_info['data']);







			$this->browser      = $order_info['browser'];



			return TRUE;







		} else {



			return FALSE;



		}



	}







// 更新旧订单数据，或者创建新订单到数据库，与数据库的最近一个订单比较，如果有产品数据发生变化就生成新订单，没有的话就更新order_data表里的旧订单数据







	function save($reference) {		



	        	  



	 // 不管是更新还是插入新订单, 都要置为当前订单号



	 $this->reference = $reference;



	 



	 date_default_timezone_set('Asia/Hong_Kong');



	 



	 $browser = $_SERVER['HTTP_USER_AGENT'];	



	 



	 // 重新计算order_data里的total值, 让它存储最终的美金值



	 $this->data['total']= round(end(array_slice(end($this->data['totals']), -2, 1)),2);



	 



	 // 拿订单号到数据库里去找



	 $order_info = $this->database->getRow("select reference, date_added from order_data where reference='".$reference."' and order_status!=0 order by order_id desc");	 	



	 



	 // 如果数据库里有该订单号, 则更新订单



	 if($order_info)



	 {



		   $sql = "update order_data set expire = '?', data='?',date_added='?' where reference='?'";



		   return $this->database->query($this->database->parse($sql, time() + $this->expire, serialize($this->data), date('Y-m-d H:i:s',time()), $reference));	 



	 }



	 else // 如果数据库里没有该订单号



	 {



			 // 查找最该客户的近订单



			$recent_order=$this->database->getRow("select * from order_data where customer_id='".$this->customer->getId()."' and order_status!=0 order by order_id desc");



			



			// 该客户没有最近订单



			if (!$recent_order)



			{	



				$sql = "insert into order_data set reference = '?', customer_id ='?',data = '?', browser = '?', expire = '?',date_added = '?'";



                return $this->database->query($this->database->parse($sql, $reference, $this->customer->getId(),serialize($this->data), $browser, time() + $this->expire, date('Y-m-d H:i:s',time())));			



			}



		



		    // 如果有最近订单



			$recent_order_data=unserialize($recent_order['data']);			



			



			// 如果新订单和最近订单比较, 产品或者订单金额发生了变化, 则生成新订单



			if( $this->data['products']!=$recent_order_data['products'] )



			{



				// 当前订单最终美金值



				$current_usd_value= round(end(array_slice(end($this->data['totals']), -2, 1)), 2);



				$recent_usd_value= round(end(array_slice(end($recent_order_data['totals']), -2, 1)), 2);



				// 当前订单最终美金值小于或者等于数据库里的订单最终美金值, 则冲掉数据库里的订单



/*				if ($current_usd_value<=$recent_usd_value) 



				{



					$sql = "update order_data set reference = '?', expire = '?', data='?',date_added='?' where order_id='?'";



			   	return $this->database->query($this->database->parse($sql, $reference, time() + $this->expire, serialize($this->data),date('Y-m-d H:i:s',time()),$recent_order['order_id']));



				}



				else // 当前大于数据库的美金值, 生成新订单, 主要是数据库里的最近订单用了优惠劵, 但是优惠劵无效了, 这个时候客户要生成新订单



				{ */



					$sql = "insert into order_data set reference = '?', customer_id ='?',data = '?', browser = '?', expire = '?',date_added = '?'";



				return $this->database->query($this->database->parse($sql, $reference, $this->customer->getId(),serialize($this->data), $browser, time() + $this->expire, date('Y-m-d H:i:s',time())));



//				}	



			



			}



			// 其它的情况一律更新订单数据,不生成新订单



		    else 



		    {



		    	$sql = "update order_data set reference = '?', expire = '?', data='?',date_added='?' where order_id='?'";



			   	return $this->database->query($this->database->parse($sql, $reference, time() + $this->expire, serialize($this->data),date('Y-m-d H:i:s',time()),$recent_order['order_id']));



			}	



	  }



 }



    // 执行process之前一定要先load订单进来



	function process($order_status_id = NULL) {



         



		 if (!$this->data){			 



			$order_data = $this->database->getRow("select * from `order_data` where reference  = '".$this->reference."'");



		    $this->data =unserialize($order_data['data']);   



		}



		$row = $this->database->getRow("select reserve from `order_data` where reference  = '".$this->reference."'");  



		



		 // 更新customer表里的order_count字段(+1)		



		$this->database->query("update customer set order_count = (order_count+1) where customer_id = '". $this->data['customer_id']."'");







date_default_timezone_set('Asia/Hong_Kong');       



				



			$sql = "insert into `order` set customer_id = '?', reference = '?', firstname = '?', lastname = '?', email = '?', telephone = '?', order_status_id = '?', total = '?', currency = '?', value = '?', ip = '?', shipping_firstname = '?', shipping_lastname = '?', shipping_company = '?', shipping_address_1 = '?', shipping_city = '?', shipping_postcode = '?', shipping_zone = '?', shipping_country = '?', shipping_address_format = '?', shipping_method = '?', payment_firstname = '?', payment_lastname = '?', payment_company = '?', payment_address_1 = '?', payment_city = '?', payment_postcode = '?', payment_zone = '?', payment_country = '?', payment_address_format = '?', payment_method = '?', payment_method_id = '?', date_modified = '?', date_added = '?'";



			



			// 重新计算order_data里的total值, 让它存储最终的美金值



			$end1=end($this->data['totals']); $slice1=array_slice($end1, -2, 1);$end2=end($slice1);



	        $this->data['total']= round($end2,2);



	 



			$this->database->query($this->database->parse($sql, $this->data['customer_id'], $this->reference, $this->data['firstname'], $this->data['lastname'], $this->data['email'], $this->data['telephone'], ($order_status_id ? $order_status_id : $this->data['order_status_id']), $this->data['total'], $this->data['currency'], $this->data['value'], $this->data['ip'], $this->data['shipping_firstname'], $this->data['shipping_lastname'], $this->data['shipping_company'], $this->data['shipping_address_1'], $this->data['shipping_city'], $this->data['shipping_postcode'], $this->data['shipping_zone'], $this->data['shipping_country'], $this->data['shipping_address_format'], $this->data['shipping_method'], $this->data['payment_firstname'], $this->data['payment_lastname'], $this->data['payment_company'], $this->data['payment_address_1'], $this->data['payment_city'], $this->data['payment_postcode'], $this->data['payment_zone'], $this->data['payment_country'], $this->data['payment_address_format'], $this->data['payment_method'], $this->data['payment_method_id'], date('Y-m-d H:i:s',time()), date('Y-m-d H:i:s',time())));







			$order_id = $this->database->getLastId();







			$get_data = $this->database->getRow("select order_id from `order_data` where reference  = '".$this->reference."'");



			







			foreach ($this->data['products'] as $product) {







				$sql = "insert into order_product set order_id = '?', name = '?', price = '?', discount = '?', total = '?', quantity = '?',itemcode = '?'";



                $parse=$this->database->parse($sql, $order_id, $product['name'], $product['price'], $product['discount'], $product['total'], $product['quantity'],$product['product_id']);



				$this->database->query($parse);



				



//				print_r ($product);



//echo $parse;



//		exit;







				$order_product_id = $this->database->getLastId();



				foreach ($product['option'] as $option) {



					$sql = "insert into order_option set order_id = '?', order_product_id = '?', name = '?', `value` = '?', price = '?', prefix = '?'";







					$this->database->query($this->database->parse($sql, $order_id, $order_product_id, $option['name'], $option['value'], $product['price'], '+')); // $option['prefix']







				}







			    $product_info=$this->database->getRow("select product_id, quantity from product where product_id='".(int)$product['product_id']."'");







                $product_stock=$product_info['quantity']>=$product['quantity']?$product['quantity']:0;







				if ($this->config->get('config_stock_subtract')) {







                    $get_order_option_info = $this->database->getRows("select op.itemcode as product_id,oo.value from `order_option` oo left join `order_product` op on oo.order_product_id=op.order_product_id where oo.order_id  = '$order_id' and op.itemcode='".(int)$product['product_id']."'");                   	







                    if(!empty($get_order_option_info)){







	                    foreach ($get_order_option_info as $v){







	                    	$order_option_info=$this->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 ov.option_value_id=pto.option_value_id where pto.product_id  = '".(int)$product['product_id']."' and ov.name='".$v['value']."'");







	                        if($order_option_info){







	                        	$this->database->query("update product_to_option set stock = (stock - " . (int)$product['quantity'] . ") where product_to_option_id = '" . $order_option_info['product_to_option_id'] . "'");







	                        }                        







	                    }







                    }







					$this->database->query("update product set quantity = (quantity - " . $product_stock . "),sales = (sales + " . (int)$product['quantity'] . "),sold = (sold + " . (int)$product['quantity'] . "),shelf_off_time = '".date('Y-m-d H:i:s',time())."' where product_id = '" . (int)$product['product_id'] . "' and quantity>0");







				}



				else{







                    $get_order_option_info = $this->database->getRows("select op.itemcode as product_id,oo.value from `order_option` oo left join `order_product` op on oo.order_product_id=op.order_product_id where oo.order_id  = '$order_id' and op.itemcode='".(int)$product['product_id']."'");                   	







                    if(!empty($get_order_option_info)){







	                    foreach ($get_order_option_info as $v){







	                    	$order_option_info=$this->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 ov.option_value_id=pto.option_value_id where pto.product_id  = '".(int)$product['product_id']."' and ov.name='".$v['value']."'");







	                        if($order_option_info){







	                        	$this->database->query("update product_to_option set stock = (stock - " . (int)$product['quantity'] . ") where product_to_option_id = '" . $order_option_info['product_to_option_id'] . "'");



	                        }                        







	                    }







                    }







					$this->database->query("update product set quantity = (quantity - " . $product_stock . "),sales = (sales + " . (int)$product['quantity'] . "),sold = (sold + " . (int)$product['quantity'] . "),shelf_off_time = '".date('Y-m-d H:i:s',time())."' where product_id = '" . (int)$product['product_id'] . "' and quantity>0");



				}







			}







			$sql = "insert into order_history set order_id = '?', order_status_id = '?', date_added = '?', notify = '1', comment = '?'";







  		 	$comment=isset($this->data['comment'])?$this->data['comment']:'';



			$this->database->query($this->database->parse($sql, $order_id, ($order_status_id ? $order_status_id : $this->data['order_status_id']), date('Y-m-d H:i:s',time()), strip_tags($comment)));











			foreach ($this->data['totals'] as $total) {







				$sql = "insert into order_total set order_id = '?', title = '?', text = '?', `value` = '?', sort_order = '?'";







				$this->database->query($this->database->parse($sql, $order_id, $total['title'], $total['text'], $total['value'], $total['sort_order']));



			}



			



			if (isset($this->data['coupon_id'])) {







                // 记录优惠劵使用信息



				$this->coupon->redeem($this->data['coupon_id'], $this->data['customer_id'], $order_id);



				



				// 禁用优惠劵



				$coupon_id=$this->data['coupon_id'];



			



	            $this->database->query("update coupon set status=(usable_times-1), usable_times=(usable_times-1), date_added='".date('Y-m-d H:i:s',time())."' where coupon_id=$coupon_id");



			}				



							$domain = "beststoreitems.com";



							$from = "sales@beststoreitems.com";



							$sender="beststoreitems";



							



				   $website="http://www.".$domain;



				 



						   



//                 send email







                $html ='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">















						<html xmlns="http://www.w3.org/1999/xhtml">















							<head>















							<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />















							<title>PO#'.$this->reference.' has been paid successfully</title>















							</head>















							<body>















							<table style="margin:0 auto;" cellspacing="0" cellpadding="0" border="0" width="650" align="center">















							  <tbody>















							  <tr>















							  <td>















							<html dir="ltr" lang="en">















							<head>















							<title>Order PO#'.$this->reference.' has been paid successfully</title>















							<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">						















							</head>















							<body>











						<table width="100%" cellpadding="0" cellspacing="0" border="0">















							<tbody>















								<tr>















									<td colspan="3"><img src="'.$website.'/media/letter3_01.jpg" /></td>                    















						  </tr>















								<tr>















									<td valign="top" style="background:#cdced2;"><img src="'.$website.'/media/letter3_02.jpg" /></td>















									<td width="622" valign="top">















										<table width="100%" cellpadding="0" cellspacing="0" border="0">















											<tbody>















												<tr>















													<td  width="20"></td>















													<td valign="top" style="font:11px/150% Verdana, Arial;">















														<div>















																<h4 style="margin:10px 0px 6px;color: #000; font:13px/150% Verdana, Arial; font-weight:bold;">Dear Customer:</h4>















																<div style="font:11px/150% Verdana, Arial; padding:0 0 5px;">Thank you for shopping with <a href="'.$website.'" target="blank">'.$domain.'</a>, your payment for PO#'.$this->reference.' has been accepted. We will begin to process your order. During this time, you are unable to do any operation on your order.</div>    



													</td>







													<td width="72" valign="top"  style="background:url('.$website.'/media/letter3_04.jpg) no-repeat 1px 0 scroll #fff"></td>







												</tr>















											</tbody>















										</table>















										<div style="height:8px; overflow:hidden;"></div>















										<table cellpadding="0" cellspacing="0" border="0">















											<tbody>















												<tr>















													<td width="20"></td>















													<td width="582">















														<div style="border:1px solid #ddd; padding:5px; background:#fbfbfb;">















															<table width="550"  cellpadding="0" cellspacing="0" border="0">















																	<tbody>















																		<tr>















																			<td style="font:11px/150% Verdana, Arial, Helvetica, sans-serif; color:#000; width:33.3%; vertical-align:top; "><b>Order Referency</b><br />















																			'.$this->reference.'<br />















																			<br />















																			<b>E-Mail</b><br />















																			'.$this->data['email'].'<br />















																			<br />











																			<b>Payment Method</b><br />















																			'.$this->data['payment_method'].'</td>















																			<td style="font:11px/150% Verdana, Arial, Helvetica, sans-serif; color:#000; width:33.3%;vertical-align:top; ">          <b>Shipping Address</b><br />















																			'.$this->data['shipping_lastname'].' '.$this->data['shipping_firstname'].'<br />'.$this->data['shipping_address_1'].'<br />'.$this->data['shipping_city'].'<br />'.$this->data['shipping_zone'].' '.$this->data['shipping_postcode'].'<br />'.$this->data['shipping_country'].'<br />'.$this->data['telephone'].'</td>















																			<td style="font:11px/150% Verdana, Arial, Helvetica, sans-serif; color:#000; width:33.3%; vertical-align:top; "><b>Payment Address</b><br />















																			'.$this->data['payment_lastname'].' '.$this->data['payment_firstname'].'<br />'.$this->data['payment_address_1'].'<br />'.$this->data['payment_city'].'<br />'.$this->data['payment_zone'].' '.$this->data['payment_postcode'].'<br />'.$this->data['payment_country'].'<br />'.$this->data['telephone'].'</td>















																		</tr>















																	</tbody>















																</table>







														</div> 







														<div style="height:10px"></div>







														<div style="border:1px solid #ddd; padding:5px; background:#fbfbfb;">







														<table width="550" class="c">



																	<tr style="font:11px/150% Verdana, Arial, Helvetica, sans-serif; color:#000; font-weight:bold;">



																		<th align="left" width="280">Product</th>



																		<th align="center">Item No.</th>



																		<th align="center">Quantity</th>



																		<th align="center">Unit Price</th>



																		<th align="right">Total</th>



																	  </tr>







																	  ';















															foreach ($this->data['products'] as $pro_info){







                                                                 $product_data_info=$this->database->getRow("select product_id,image_id from product where product_id='".$pro_info['product_id']."'");







					                                            $image_data_info=$this->database->getRow("select filename from image where image_id='".$product_data_info['image_id']."'");







					                                            $thumb_url=$this->image->resize($image_data_info['filename'], 65, 65);







																$html.='<tr>











																		<td align="left" width="280" style="font:11px/150% Verdana, Arial; padding:4px 0;">







																			<div style="float:left;"><a href="'.$website.'/index.php?controller=product&product_id='.$pro_info['product_id'].'"><img width="65" height="65" border="0" src="'.$thumb_url.'" ></a></div>







																			<div style="loat:left; width:205px; padding-left:5px; overflow:hidden;"><a style="font-size:10px; color:blue;" target="_blank" href="'.$website.'/index.php?controller=product&product_id='.$pro_info['product_id'].'">'.$pro_info['name'].'</a></div>







																		</td>















																		<td align="center" style="font:11px/150% Verdana, Arial; padding:4px 0;">'.$pro_info['product_id'].'</td>















																		<td align="center" style="font:11px/150% Verdana, Arial; padding:4px 0;">'.$pro_info['quantity'].'</td>















																		<td align="center" style="font:11px/150% Verdana, Arial; padding:4px 0;">'.$pro_info['price'].'</td>















																		<td align="right"  style="font:11px/150% Verdana, Arial; padding:4px 0;">'.$pro_info['total'].'</td>















																	  </tr>';	







															}



															



														$html.='



														</table>







															<div class="f">















																<div style="float:right;">















																			  <table>';











																		foreach ($this->data['totals'] as $totals){















																		$html.= '<tr>















																					<td style="font:11px/150% Verdana, Arial; text-align:right; padding-right:10px;">'.$totals['title'].'</td>















																					<td style="font:11px/150% Verdana, Arial; text-align:right;">'.$totals['text'].'</td>















																				 </tr>';















																		}











																	$html.='</table></div>















																<div style="clear:both;"></div>















															</div>



															</div> 















																<div style="height:10px;"></div>















																<div>















																	<p style="margin:0; padding:0; height:38px; background:url('.$website.'/media/letter3_06.jpg) no-repeat"></p>















						<p style=" font:11px/40px Arial, Helvetica, sans-serif;margin: 0px 0px 10px; color:#666;text-align: right; border-bottom: 3px solid #e9e9e9;">'.$domain.' </p>



																</div>



															</td>



															<td width="20"></td>



															</tr>



															<tr>



																<td colspan="3"><img src="'.$website.'/media/letter3_05.jpg" /></td>



															</tr>







															</tbody>



														</table>



									</td>







									<td valign="top" style="background:#cdced2;"><img src="'.$website.'/media/letter3_03.jpg" /></td>



								</tr>



							</tbody>







						</table>







    					</td>







						</tr>



						</tbody>



					</table>



							</body>



						 </html>';     



				$this->mail->setTo($this->data['email']);



				$this->mail->setFrom($from);



				$this->mail->setSender($sender);



				$this->mail->setSubject('PO#'.$this->reference.' has been paid successfully');				



				$this->mail->setHtml($html);



				$this->mail->send();



	



		     // 删除session里的cart 



			$this->session->delete('cart');



					



		     // 删除未付款订单



			$sql = "delete from order_data where reference = '?'";		           



			$result=$this->database->query($this->database->parse($sql, $this->reference));		



			



		    // 清空购物车



			unset($this->data);	$this->data = array();				



//			$return=$this->database->query("update customer set cart = '".$this->data."' where customer_id = '".$this->customer->getId()."'");					



		}



}







?>