<?php
defined('IN_YUNYECMS') or exit('No permission.');
core::load_class('base', false);
core::load_fun('content');
core::load_fun('tree');
core::load_fun('shop');
class cart extends base
{
	public $curmodel;
	function __construct()
	{
		parent::__construct();
		$this->db->tablename = 'cart';
		islogin();
	}
	//首页
	public function index()
	{
		$seo['title'] = $this->lang["seotitle"];
		$seo['keywords'] = $this->lang["seokey"];
		$seo['description'] = $this->lang["seodesc"];
		$seostr = Lan('cart') . "-" . Lan('member_center');
		$seo['title'] = "{$seostr}-{$seo['title']}";
		$seo['keywords'] = "{$seostr}-{$seo['keywords']}";
		$cfg = $this->cfg;
		$lang = $this->lang;
		$token = ugetcookie("loginrnd");
		$breadcumb = array(
			'0' => array('title' => Lan('member_center'), 'url' => url("member/member/index")),
			'1' => array('title' => Lan('cart'), 'url' => url("shop/cart/index"))
		);
		$userid = usafestr(yunyecms_strdecode(ugetcookie("userid")));
		$member = $this->member;
		$pagesize = 20;
		$sqlquery = "select * from `#yunyecms_cart`  ";
		$where = " where gid<>'' and userid={$userid} ";
		$sqlcnt = " select count(*) from `#yunyecms_cart` ";
		$order = " order by `updatetime` desc,`addtime` desc,`id` desc ";
		if (isset($_REQUEST)) {
			if (!empty($_REQUEST["searchkey"])) {
				$searchkey = usafestr(trim($_REQUEST["searchkey"]));
				$where = $where . " and ( `title`  like '%{$searchkey}%' )";
			}
		}
		$pagearr = $this->db->pagelist($sqlcnt, $sqlquery, $where, $order, $pagesize);
		if ($pagearr["count"] != 0) {
			$list = $pagearr["query"];
			foreach ($list as $key => $var) {
				$goods = GetContentById($var["gid"], $var["catid"]);
				$list[$key]["goods"] = $goods;
				$list[$key]["goods"]["url"] = url('content/index/show', array("catid" => $goods["catid"], "id" => $goods["id"]));
				$list[$key]["totalprice"] = round($var["num"] * $var["price"], 2);
				$list[$key]["price"] = round($var["price"], 2);
			}
			$page = $pagearr["page"];
		}
		$totalmoney = GetCartTotal($userid);
		$totalmoney = round($totalmoney, 2);
		include tpl('cart', 'shop');
	}

	function add()
	{
		$cfg = $this->cfg;
		$lang = $this->lang;
		$cat = $this->cat;
		islogin();
		$userid = usafestr(yunyecms_strdecode(ugetcookie("userid")));
		$member = $this->member;
		$_REQUEST = yytrim($_REQUEST);
		if (empty($_REQUEST['num'])) {
			$num = 1;
		} else {
			$num = trim($_REQUEST['num']);
			$num = intval(usafestr($_REQUEST['num']));
		}
		if (!empty($_REQUEST['gid'])) {
			$gid = $_REQUEST['gid'];
			if (!is_numeric($gid)) {
				messagebox(Lan('goodsid_is_notnum'));
			}
		} else {
			messagebox(Lan('goods_parm_error'));
		}
		if (!empty($cat)) {
			$catid = $cat["id"];
			$modelid = getmodelid($catid);
			if (empty($modelid)) {
				messagebox(Lan('model_notexist'), "back", "warn");
			} else {
				$curmodel = getmodel($modelid);
				$tablename = "m_" . $curmodel['tablename'];
				$curgoods = $this->db->getbyid($gid, $tablename);
				if (empty($curgoods['price'])) {
					messagebox(Lan('goods_price_require'));
				}
			}
		} else {
			messagebox(Lan('goods_parm_error'));
		}
		$curtime = time();
		if ($this->check_exist($userid, $catid, $gid)) {
			$where['userid'] = $userid;
			$where['gid'] = $gid;
			$where['catid'] = $catid;
			$data['price'] = $curgoods['price'];
			$data['num'] = "num+$num";
			$data['updatetime'] = $curtime;
			$strsql = "UPDATE `#yunyecms_cart` SET `price`='{$curgoods['price']}',`num`=num+'{$num}',`updatetime`='{$curtime}' WHERE `userid` = '{$userid}' AND `gid` = '{$gid}' AND `catid` = '{$catid}'";
			$retres = $this->db->query($strsql);
			if ($retres !== false) {
				// messagebox("恭喜您! 更新购物车成功 !",url('shop/cart/index'));		
				redirect(url('/cart/'));
			} else {
				messagebox(Lan('cart_update_error'), "back", 'warn');
			}
		} else {
			$data['userid'] = $userid;
			$data['gid'] = $gid;
			$data['title'] = $curgoods['title'];
			$data['catid'] = $catid;
			$data['price'] = $curgoods['price'];
			$data['num'] = $num;
			$data['addtime'] = $curtime;
			$data['updatetime'] = $curtime;
			$insertid = $this->db->insert($data, 'cart', true);
			if ($insertid !== false) {
				redirect(url('/cart/'));
				// messagebox("恭喜您! 添加购物车成功 !",url('shop/cart/index'));		
			} else {
				messagebox(Lan('cart_insert_error'), "back", 'warn');
			}
		}
	}


	//更新购物车数量
	function changenum()
	{
		$userid = usafestr(yunyecms_strdecode(ugetcookie("userid")));
		if (empty($userid)) exit(0);
		$member = $this->member;
		$curtime = time();
		$returndata = array();
		empty($_REQUEST['cartid']) ? exit(0) : $cartid = $_REQUEST['cartid'];
		$cartid = intval(usafestr($cartid));
		empty($_REQUEST['mode']) ? exit(0) : $mode = $_REQUEST['mode'];
		$mode = intval(usafestr($mode));
		empty($_REQUEST['sel_goods']) ? exit(0) : $sel_goods = $_REQUEST['sel_goods'];
		$sel_goods = usafestr($sel_goods);
		if ($mode == 1) {
			$strsql = "UPDATE  `#yunyecms_cart` SET `num`=num+1,`updatetime`='{$curtime}' WHERE `userid` = '{$userid}' AND `id` = '{$cartid}' ";
		} elseif ($mode == 2) {
			$strsql = "UPDATE  `#yunyecms_cart` SET `num`=num-1,`updatetime`='{$curtime}' WHERE `userid` = '{$userid}' AND `id` = '{$cartid}' and num>1 ";
		}
		$retres = $this->db->query($strsql);
		if (empty($retres)) exit(0);
		$cartitem = $this->db->getbyid($cartid, "cart");
		if (empty($cartitem)) exit(0);
		$returndata["num"] = $cartitem["num"];
		$returndata["price"] = $cartitem["price"];
		$returndata["totalprice"] = round($cartitem["num"] * $cartitem["price"], 2);
		$totalmoney = GetCartTotal($userid, $sel_goods);
		$returndata["totalmoney"] = round($totalmoney, 2);
		exit(json_encode($returndata));
	}

	//更新购物车商品
	function changecart()
	{
		$userid = usafestr(yunyecms_strdecode(ugetcookie("userid")));
		if (empty($userid)) exit(0);
		$returndata = array();
		empty($_REQUEST['sel_goods']) ? exit(0) : $sel_goods = $_REQUEST['sel_goods'];
		$sel_goods = yytrim($sel_goods);
		$totalmoney = GetCartTotal($userid, $sel_goods);
		$returndata["totalmoney"] = round($totalmoney, 2);
		exit(json_encode($returndata));
	}

	function pay()
	{
		$seo['title'] = $this->lang["seotitle"];
		$seo['keywords'] = $this->lang["seokey"];
		$seo['description'] = $this->lang["seodesc"];
		$seostr = Lan('cart') . "-" . Lan('member_center');
		$seo['title'] = "{$seostr}-{$seo['title']}";
		$seo['keywords'] = "{$seostr}-{$seo['keywords']}";
		$breadcumb = array(
			'0' => array('title' => Lan('member_center'), 'url' => url("member/member/index")),
			'1' => array('title' => Lan('online_pay'), 'url' => url("shop/cart/pay"))
		);
		islogin();
		checktoken(trim($_POST["token"]));
		$userid = usafestr(yunyecms_strdecode(ugetcookie("userid")));
		$member = $this->member;
		if (empty($member["address"]) || empty($member["name"]) || empty($member["phone"])) {
			messagebox(Lan('improve_info_first'), url('member/member/myinfo'));
			exit;
		}
		if (!empty($_REQUEST['totalamount'])) {
			$totalamount = $_REQUEST['totalamount'];
			if (!is_numeric($totalamount)) {
				messagebox(Lan('goods_parm_error'));
			}
		} else {
			messagebox(Lan('goods_parm_error'));
		}

		if (!is_array($_REQUEST['selcart'])) {
			messagebox(Lan('goods_parm_error'));
		}
		empty($_REQUEST['selcart']) ? messagebox(Lan('goods_least_one')) : $selcart = yytrim($_REQUEST['selcart']);
		empty($_REQUEST['num']) ? messagebox(Lan('error_parameter')) : $numarray = yytrim($_REQUEST['num']);
		if (is_array($selcart)) {
			foreach ($selcart as $key => $var) {
				if (!is_numeric($var)) {
					messagebox(Lan('goods_parm_error'));
				}
			}
			$cartstr = implode(",", $selcart);
		}
		if ($cartstr) $cartlist = $this->db->select("select * from `#yunyecms_cart` where userid={$member["id"]} and id in($cartstr) order by addtime desc");
		if (empty($cartlist)) {
			messagebox(Lan('error_goods_isdelete'));
		}
		foreach ($cartlist as $k => $v) {
			$goods[$k]['gid'] = $v['gid'];
			$goods[$k]['title'] = $v['title'];
			$goods[$k]['catid'] = $v['catid'];
			$goods[$k]['num'] = $v['num'];
			$goods[$k]['price'] = $v['price'];
			foreach ($selcart as $kk => $vv) {
				if ($vv == $v['id']) {
					if ($goods[$k]['num'] != $numarray[$kk]) {
						messagebox(Lan('goods_parm_error'));
					}
				}
			}
		}
		$cartmoney = GetCartTotal($userid, $selcart);
		$goods = serialize($goods);
		$curtime = time();
		$sn = makesn();
		$data['sn'] = $sn;
		$data['userid'] = $userid;
		$data['goods'] = $goods;
		$data['title'] = $cartlist[0]['title'];
		$data['money'] = $cartmoney;
		$data['name'] = $member["name"];
		$data['address'] = $member["address"];
		$data['mobile'] = empty($member["mobile"]) ? $member["phone"] : $member["mobile"];
		$data['addtime'] = $curtime;
		$data['status'] = 0;
		$data['updatetime'] = $curtime;
		$insertid = $this->db->insert($data, 'orders', true);
		if ($insertid !== false) {
			$msgcontent['mod'] = ROUTE_M;
			$msgcontent['act'] = ROUTE_A;
			$msgcontent['ctrl'] = ROUTE_C;
			$msgcontent['table'] = "orders";
			$msgcontent['id'] = $insertid;
			$msgcontent = serialize($msgcontent);
			$msgtitle = sprintf(lan('orders_success_msg'), $sn, $member['username'], $member["name"], $member["mobile"]);
			$remsg = savemsg($msgtitle, 3, $msgcontent, $insertid);
			$retres = $this->db->delete("id in ({$cartstr}) and userid={$userid}", "cart");
			redirect(url('shop/orders/onlinepay', array("orderid" => $insertid)));
		} else {
			messagebox(Lan('error_checkout'), "back", 'warn');
		}
	}

	public function remove()
	{
		islogin();
		$userid = usafestr(yunyecms_strdecode(ugetcookie("userid")));
		if (!empty($_REQUEST["id"])) {
			$id = $_REQUEST["id"];
			$id = usafestr(trim($id));
			if (!is_array($id)) {
				$id = compact('id');
			}
			$idarray = $id;
			if (isset($idarray)) {
				foreach ($idarray as $key => $var) {
					if (!is_numeric($var)) {
						messagebox(lan('operation_failed'), url('shop/cart/index', 'lang'), "warn");
					}
				}
				$idarray = implode(",", $idarray);
				$retres = $this->db->delete("id in ({$idarray}) and userid={$userid}", "cart");
				if ($retres !== false) {
					messagebox(lan('cart_goods_removeok'), url('shop/cart/index', 'lang'), "success");
				} else {
					messagebox(lan('operation_failed'), url('shop/cart/index', 'lang'), "warn");
				}
			} else {
				messagebox(lan('operation_failed'), url('shop/cart/index', 'lang'), "warn");
			}
		} else {
			messagebox(lan('operation_failed'), url('shop/cart/index', 'lang'), "warn");
		}
	}

	private function check_exist($userid, $catid, $gid)
	{
		$userid = trim($userid);
		$gid = trim($gid);
		$catid = trim($catid);
		if (empty($userid) || empty($catid) || empty($gid) || !is_numeric($userid) || !is_numeric($catid) || !is_numeric($gid)) {
			return false;
		} else {
			$cnt = $this->db->GetCount("select count(*) from `#yunyecms_cart` where `userid`= {$userid} and  `catid`= {$catid} and  `gid`= {$gid}");
			if ($cnt >= 1) {
				return true;
			} else {
				return false;
			}
		}
	}
}
