<?php
/**
 *      [XCECP] (C) COLNET Inc.
 *      This is NOT a freeware, use is subject to license terms
 */
if(!defined("IN_QKWEB")){exit("Access Denied");}
class PurchaseModel extends BaseModel{
	function del($id){
		$sql  = "delete from qk_shoppingcart where id='$id'";
		if($this->db->query($sql)){
			return true;
		}
		return false;
	}
	function clear(){
		$userId = $_SESSION['userId'];
		if(!$userId){return false;}
		$sql  = "delete from qk_shoppingcart where userId='$userId'";
		if($this->db->query($sql)){
			return true;
		}
		return false;		
	}

	function cartMerger(){
		$userId = $_SESSION['userId'];
		$sessionId = session_id();
		if($userId && $sessionId){
			$sql = "select * from qk_shoppingcart where sessionId='$sessionId'";
			$scarts = $this->db->getAll($sql);
			foreach($scarts as $item){
				$sql = "select id from qk_shoppingcart where goodsId='".$item['goodsId']."' and userId='$userId'";
				$cartId = $this->db->getOne($sql);
				if(!$cartId){
					$sql = "update qk_shoppingcart set userId='$userId',sessionId='' where id='".$item['id']."'";
				}else{
					$sql = "delete from qk_shoppingcart where id='".$item['id']."'";
				}
				$this->db->query($sql);
			}
		}
		return false;
	}

	function cartInfo(){
		//$sql = "select cart.*,goods.price from qk_shoppingcart as cart  left join qk_goods as goods on cart.goodsId=goods.id where cart.userId='$userId'  or sessionId='".session_id()."' order by id desc";
		load_class("goods");
		$gm = new GoodsModel();
		$userId = $_SESSION['userId'];
		if($userId){$wheres=" or userId='$userId'";}else{$wheres="";}
		$sql = "select * from qk_shoppingcart where sessionId='".session_id()."' $wheres order by id desc";
		
		$cartInfo = $this->db->getAll($sql);
		$i=0;
		foreach($cartInfo as $item){
			$cartInfo[$i]['goodsInfo'] = $gm->getInfo($item['goodsId']);
			$cartInfo[$i]['price'] = $cartInfo[$i]['goodsInfo']['price'];
			$cartInfo[$i]['priceNow'] = $cartInfo[$i]['goodsInfo']['priceNow'];
			if($item['prizeId']){
				$cartInfo[$i]['prizePrice'] = $cartInfo[$i]['price'];
			}else{
				$cartInfo[$i]['prizePrice'] = 0;		
			}
			$cartInfo[$i]['index'] = $i;
			$i++;
		}
		unset($i);
		return $cartInfo;
	}

	function cartInfoWeight($cartInfo=false){
		$weight = 0;
		if(!$cartInfo) $cartInfo = $this->cartInfo();
		foreach($cartInfo as $item){
			$weight += $item['goodsInfo']['weight']*$item['pnum'];
		}
		return $weight;
	}

	function cartInfoScorePrice($cartInfo=false){
		$scorePrice = 0;
		if(!$cartInfo) $cartInfo = $this->cartInfo();
		foreach($cartInfo as $item){
			$scorePrice += $item['goodsInfo']['scorePrice']*$item['pnum'];
		}
		return $scorePrice;
	}

	function cartInfoScore($cartInfo=false){
		$score = 0;
		if(!$cartInfo) $cartInfo = $this->cartInfo();
		foreach($cartInfo as $item){
			$score += $item['goodsInfo']['score']*$item['pnum'];
		}
		return $score;
	}
}
?>