<?php
if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ))
{
include_once "../includes/connectConfig.php";

/*****************************************ADDING ITEM TO CART TABLE***************************/

if(isset($_POST['addCart']) && isset($_POST['addam']) == "addCart"){
	$prd_id = test_input($_POST['addto']);
	$user_id = $set_sess;
	
	$prd_attr = (isset($_POST['attr'])) ? test_input($_POST['attr']) : NULL;
	
	//CHECK FROM DB IF USER ALREADY HAS CART ITEMS 
	$mk_cart = $db_con->prepare("SELECT * FROM my_cart WHERE pqrcode = '$prd_id' AND session_rec = '$user_id'");
	$mk_cart->execute(); $ftc_crt = $mk_cart->fetch(); $rowcount = $mk_cart->rowCount();
	if(!empty($ftc_crt) && $rowcount > 0)
	{	
		//IF ALREADY HAS MATCHING PRODUCT, THEN UPDATE QUANTITY
		$quantity = (isset($_POST['cntupto']) && !empty($_POST['cntupto'])) ? $_POST['cntupto'] : ($ftc_crt['qty'] + 1);
		
		$crt_ins = $db_con->prepare("UPDATE my_cart SET qty=:quantity, prd_attr=:prd_attr WHERE pqrcode=:prd_id AND session_rec=:user_id");
		$crt_ins->bindParam(':quantity',$quantity); $crt_ins->bindParam(':prd_attr',$prd_attr); $crt_ins->bindParam(':prd_id',$prd_id); $crt_ins->bindParam(':user_id',$user_id);	$crt_ins->execute();
	}
	else //INSERT NEW RECORD 
	{
		$quantity = (isset($_POST['cntupto']) && !empty($_POST['cntupto'])) ? $_POST['cntupto'] : 1;
		
		$crt_ins = $db_con->prepare("INSERT INTO my_cart(session_rec, pqrcode, qty, prd_attr) VALUES(:user_id,:prd_id,:quantity, :prd_attr)");
		$crt_ins->bindParam(':user_id',$user_id);  $crt_ins->bindParam(':prd_id',$prd_id);  $crt_ins->bindParam(':quantity',$quantity);  $crt_ins->bindParam(':prd_attr',$prd_attr);  $crt_ins->execute();
		
		
		$chk_prdz = $db_con->prepare("SELECT psell,pdiscount,pqrcode,ksp_id, pname FROM kmartstockprds WHERE pqrcode = '$prd_id' ");
		$chk_prdz->execute(); $pdz = $chk_prdz->fetch();	
		$gt_imgs = gtOne("kprdw_imgs"," prd_rec = '$pdz[pqrcode]' ORDER BY kmg_id ASC","pjm_pic");
		
		$chk_mgi = $gt_imgs;     $chk_sl = $pdz['psell'];    $chk_ds = $pdz['pdiscount'];
		if($prd_attr == 'promo'){
		//FROM GENERAL FEATURED SPECIAL PROMO
		$chk_ftp = $db_con->prepare("SELECT * FROM kmt_ft_prds WHERE ksp_id = '$pdz[ksp_id]'  AND delete_status = 0");
		$chk_ftp->execute(); $fpd = $chk_ftp->fetch();
		
		$chk_mgi = (!empty($fpd) && !empty($fpd['prd_img'])) ?  $fpd['prd_img'] : $gt_imgs;
		$chk_sl = (!empty($fpd) && !empty($fpd['km_sell'])) ? $fpd['km_sell'] : $pdz['psell'];
		$chk_ds = (!empty($fpd) && !empty($fpd['km_discount'])) ? $fpd['km_discount'] : $pdz['pdiscount'];
		}
		
		$prd_img = (!empty($chk_mgi) && file_exists('../prdimgs/'.$chk_mgi)) ? "prdimgs/".$chk_mgi : 'img/kmart-icon.png';
		
		$shw_pec = calcprcs($chk_sl,$chk_ds,'spc');
		$shw_ds = calcprcs($chk_sl,$chk_ds,'ssl');
		$shw_dsc = calcprcs($chk_sl,$chk_ds,'sds');
											
		$output["minidrp"] = 	'<li>
				<div class="minicart-item" data-cart="'.$prd_id.'">
					<div class="thumb">
						<a href="javascript:void(0);"><img src="'.$prd_img.'" width="90" height="90" alt="Cart Icon"></a>
					</div>
					<div class="left-info">
						<div class="product-title"><a href="javascript:void(0);" class="product-name mkells">'.$pdz['pname'].'</a></div>
						<div class="price">
							<ins><span class="price-amount"><span class="currencySymbol">GH₵</span>'.$shw_ds.'</span></ins>
							
						</div>
						<div class="qty">
							<label>Qty:'.$quantity.'</label>
						</div>
					</div>
					<div class="action">
						<a href="javascript:void(0);" class="remove"><i class="fa fa-trash-o" aria-hidden="true"></i></a>
					</div>
				</div>
			</li>';
	}
	$output["itemscount"] = cart_stk("tot_crt");
	$output["amt_count"] = "GH₵ ".cart_stk("cart_amt");
	echo json_encode($output);
	exit;
}	

/*************************************TO FETCH USER CART BAG ITEMS*********************************
if(isset($_POST['fetch_cart']))
{
	$item_total = 0; 
	$item_discount = 0;
	//CHECK IF USER SESSION HAS ITEMS IN CART TABLE
	$mk_cart = $db_con->prepare("SELECT * FROM my_cart WHERE session_id = '$set_sess' ORDER BY cart_id");
	$mk_cart->execute();
	$rowcount = $mk_cart->rowCount();
	
	if($rowcount > 0) //IF YES, THERE ARE ITEMS
	{
		$i = 0;
		$output["cartitems"] = '';
		
		$ftc_crt = $mk_cart->fetchAll();
		
		if(!empty($ftc_crt))
		{
			foreach($ftc_crt as $crt)
			{
				$i++;
				
				//FETCH PRODUCT
				$prds = $db_con->prepare("SELECT * FROM products WHERE prd_id = '".$crt['prd_code']."' ");
				$prds->execute();
				$product = $prds->fetch();
				

				$prd_id = $product["prd_id"];
				
				//DISCOUNT Check
				$pds_dis = check_discount($prd_id,$product["prd_discount"]);
			
				$item_total += (($product["prd_sellprice"] - $pds_dis)*$crt["quantity"]);

				$item_discount += ($pds_dis*$crt["quantity"]); 
				
				$item_price = ($product["prd_sellprice"] - $pds_dis);
				
				//check if attribute is set
				if(!empty($crt['prd_attr'])){ $atr = ' - '.$crt['prd_attr']; } else{ $atr = ""; }
				
			$output["cartitems"] .= 
			'
				<div class="product product-widget">
					<div class="product-thumb">
						<img src="./products_img/'.gtOne("prd_images"," prd_id = '$prd_id' ORDER BY im_id ASC LIMIT 1","im_file").'" alt="'.ucfirst($product['prd_title']).'">
					</div>
					<div class="product-body">
						<h4 class="product-price">GH₵ '.($product["prd_sellprice"] - $pds_dis) .' <span class="qty">x'.$crt['quantity'].$atr.'</span></h4>
						<h2 class="product-name"><a href="product?preg='.$product['prd_url'].'" target="_blank" class="pd_alnk">'.ucfirst($product['prd_title']).'</a></h2>
					</div>
					<button type="button" class="cancel-btn btncartRemove" id="cart_'.$crt['cart_id'].'"><i class="fa fa-trash"></i></button>
				</div>
				';
			}
		}
	}
	else //MEANING THERE ARE NO ITEMS IN CART TABLE RELATED TOP USER SESSION
	{
		$output["cartitems"] = 
		' <h5 class="text-center"> <i class="fa fa-shopping-cart " style="font-size:35px;color:#F8694A;"></i> <br/> Cart is empty</h5>	';
	}
	
	echo json_encode($output);
	exit;
}	************************************************************/
	
	/*********************************************UPDATING CART ITEM QUANTING AND COUNTING TOTAL CAR PRICE*****************/
if(isset($_POST['update_cart_quantity']))
{
	$cart_id = $_POST['cart_id'];
	$new_quantity = $_POST['new_quantity'];

	//UPDATE CART QUANTITY
	$upd = $db_con->prepare("UPDATE my_cart SET quantity =:new_quantity WHERE prd_code =:cart_id  AND session_id =:set_sess ");
	$upd->bindParam(':new_quantity',$new_quantity);
	$upd->bindParam(':cart_id',$cart_id);
	$upd->bindParam(':set_sess',$set_sess);
	$upd->execute();
	
	
	$item_total = 0; 
	$item_discount = 0;
	$tt = 0;

	$sel_crt = $db_con->prepare("SELECT * FROM my_cart WHERE session_id = '$set_sess' ORDER BY cart_id");
	$sel_crt->execute();
	$fetch_crt = $sel_crt->fetchAll();
				
	if(!empty($fetch_crt))
	{
		foreach($fetch_crt as $rs)
		{	
		
			$sel_prds = $db_con->prepare("SELECT * FROM products WHERE prd_id = '".$rs['prd_code']."' ");
			$sel_prds->execute();
			$rt = $sel_prds->fetch();
				
				$ds_it = ($rt['prd_sellprice'])* $rs["quantity"];
				
				//DISCOUNT Check
				$pds_dis = check_discount($rs['prd_code'],$rt['prd_discount']);
			
				if(!empty($pds_dis) && $pds_dis !=0)
				{ 
					$ds_cur = ($rt['prd_sellprice'] - $pds_dis)* $rs["quantity"];
					
					$ds_dc = ($pds_dis)* $rs["quantity"];
				} 
				else
				{
					$ds_cur = $rt['prd_sellprice']* $rs["quantity"];
					$ds_dc = 0;
				}
			
				$item_total += $ds_it;
				$item_discount += $ds_dc;
				$tt += $ds_cur;
		}
	}
							
	
	$output["subitem"] = "GH₵ ". $ds_cur;
	$output["subtotal"] = "GH₵ ". $item_total;
	$output["discount"] = "GH₵ ". $item_discount;
	$output["totals"] = "GH₵ ". ($tt);
	$output["totals_tp"] = "₵ ". ($tt);
		echo json_encode($output);
	exit;
}

/************************************TO REMOVE SINGLE CART ITEM **************************/
if(isset($_POST['outDelCart'])){
	$cart_id = $_POST['shiftcart'];
	$fetch_crt = getOne("my_cart"," pqrcode = '$cart_id' AND session_rec = '$set_sess' ","id");	
	$output["cartrec"] = '';
	if(!empty($fetch_crt)){
		$upd = $db_con->prepare("DELETE FROM my_cart WHERE id =:cart_id  AND session_rec =:set_sess ");
		$upd->bindParam(':cart_id',$fetch_crt); $upd->bindParam(':set_sess',$set_sess); $upd->execute();
		$output["cartrec"] = 'cart';
	}
	
	/*$item_total = 0; 
	$item_discount = 0;
	$tt = 0;
	
	$sel_crt = $db_con->prepare("SELECT * FROM my_cart WHERE session_id = '$set_sess' ORDER BY cart_id");
	$sel_crt->execute();
	$fetch_crt = $sel_crt->fetchAll();
				
	if(!empty($fetch_crt))
	{
		foreach($fetch_crt as $rs)
		{
			$sel_prds = $db_con->prepare("SELECT * FROM products WHERE prd_id = '".$rs['prd_code']."' ");
			$sel_prds->execute();
			$rt = $sel_prds->fetch();
			
			//DISCOUNT Check
			$pds_dis = check_discount($rs['prd_code'],$rt['prd_discount']);
				
				$ds_it = ($rt['prd_sellprice'])* $rs["quantity"];
				
				if(!empty($pds_dis) && $pds_dis !=0)
				{ 
					$ds_cur = ($rt['prd_sellprice'] - $pds_dis)* $rs["quantity"];
					
					$ds_dc = ($pds_dis)* $rs["quantity"];
				} 
				else
				{
					$ds_cur = $rt['prd_sellprice']* $rs["quantity"];
					$ds_dc = 0;
				}
			
				$item_total += $ds_it;
				$item_discount += $ds_dc;
				$tt += $ds_cur;
		}
	}
	
	$output["subtotal"] = "GH₵ ". $item_total;
	$output["discount"] = "GH₵ ". $item_discount;
	$output["totals"] = "GH₵ ". ($tt);
	*/
	
	
	$output["itemscount"] = cart_stk("tot_crt");
	$output["amt_count"] = cart_stk("cart_amt");
	echo json_encode($output);
	exit;
}


	
}

?>






