<?php 
include '../backend/db/db.php';
session_start();

if (isset($_SESSION['normal_user_cey'])) {
	$user_id = htmlspecialchars(strip_tags(trim($_SESSION['normal_user_cey'])), ENT_QUOTES, 'UTF-8');
	$whr = 'User_ID';

} else if (isset($_SESSION['temp_user_cey'])) {
	$user_id = htmlspecialchars(strip_tags(trim($_SESSION['temp_user_cey'])), ENT_QUOTES, 'UTF-8');
	$whr = 'tmp_id';

} else {
	$user_id = '';
}

/**********************  Load Shopping Cart *******************/

if (array_key_exists('load_mini_cart', $_POST)) {
	if(!empty($user_id)) {
		$sql = "SELECT * FROM live_cart WHERE $whr = $user_id";
		$result = mysqli_query($conn, $sql);
		$data = array();
		
		if(mysqli_num_rows($result) > 0) {
			while($row = mysqli_fetch_assoc($result)) {
				$data1[] = $row;
				$data2[] = $row['Item'];
			}
			array_push($data, $data1);
			array_push($data, $data2);
			
		} else {
			$data = '';
		}
	
	} else {
		$data = '';
	}
	echo json_encode($data);
}

/********************** Add To Cart ********************/

date_default_timezone_set('Asia/Colombo');
$now = date('Y-m-d H:i:s');

//if (array_key_exists('add_to_cart', $_POST)) {
if (isset($_POST['add_to_cart'])) {
	if(isset($_POST['item_id'])) {
		$itm_id = htmlspecialchars(strip_tags(trim($_POST['item_id'])), ENT_QUOTES, 'UTF-8');
	
	} else {
		$itm_id = '';
	}
	
	if(isset($_POST['qty'])) {
		$qty = htmlspecialchars(strip_tags(trim($_POST['qty'])), ENT_QUOTES, 'UTF-8');
	
	} else {
		$qty = 1;
	}
	
	
	if(empty($qty) || $qty <= 0) { $qty = 1; }
	
	if(!empty($itm_id)) { // Stock Validation
		//$sql_itmv = mysqli_fetch_assoc(mysqli_query($conn, "SELECT qty FROM items WHERE id = $itm_id AND stock_out=0 AND weight>0"));
		//$stock_qty = $sql_itmv['qty'];
		
		//if($stock_qty >= $qty) {
			if (isset($_SESSION['normal_user_cey'])) {
				$user_id = htmlspecialchars(strip_tags(trim($_SESSION['normal_user_cey'])), ENT_QUOTES, 'UTF-8');
				
				$sql_usr = mysqli_fetch_assoc(mysqli_query($conn, "SELECT cusID, order_id FROM customer WHERE cusID = $user_id"));
				$sql_invo = mysqli_query($conn, "SELECT inv_id FROM live_cart WHERE User_ID = $user_id");
				if(mysqli_num_rows($sql_invo) == 0) {
					$inv = '';
				
				} else {
					$row_invo = mysqli_fetch_assoc($sql_invo);
					$inv = $row_invo['inv_id'];
				}
				
				$oid = $sql_usr['order_id'];
				$txt = "User_ID = ".$user_id;
				$uid = $sql_usr['cusID'];
				$tmp_id = 0;
			
			} else {
				if (isset($_SESSION['temp_user_cey'])) {
					$user_id = htmlspecialchars(strip_tags(trim($_SESSION['temp_user_cey'])), ENT_QUOTES, 'UTF-8');
					$sql_invo = mysqli_query($conn, "SELECT inv_id FROM live_cart WHERE tmp_id = $user_id");
					if(mysqli_num_rows($sql_invo) == 0) {
						$inv = '';
					
					} else {
						$row_invo = mysqli_fetch_assoc($sql_invo);
						$inv = $row_invo['inv_id'];
					}
					
					$oid = 1;
					$txt = "tmp_id = ".$user_id;
					$uid = 'tmp_'.$user_id;
					$tmp_id = $user_id;
				
				} else {
					$sql_inv = mysqli_fetch_assoc(mysqli_query($conn, "SELECT token FROM invoice_no"));
					$new_uid = $sql_inv['token'];
					$sql_v = "UPDATE invoice_no SET token=token+1";
					
					if(mysqli_query($conn, $sql_v)) {
						$ts1 = mysqli_query($conn, "SELECT tmp_id FROM live_cart WHERE tmp_id='$new_uid'");
						$ts2 = mysqli_query($conn, "SELECT tmp_id FROM cart_details WHERE tmp_id='$new_uid'");
						$ts3 = mysqli_query($conn, "SELECT user_id FROM order_details_temp WHERE user_id='$new_uid' AND guest=1");
						$ts4 = mysqli_query($conn, "SELECT user_id FROM order_details WHERE user_id='$new_uid' AND guest=1");
						
						if(mysqli_num_rows($ts1) == 0 && mysqli_num_rows($ts2) == 0 && mysqli_num_rows($ts3) == 0 && mysqli_num_rows($ts4) == 0) {
							$_SESSION['temp_user_cey'] = $new_uid;
							$user_id = htmlspecialchars(strip_tags(trim($_SESSION['temp_user_cey'])), ENT_QUOTES, 'UTF-8');
						
						} else {
							//mysqli_query($conn, "UPDATE invoice_no SET token=token+1");
							$user_id = '';
						}
					
					} else {
						$user_id = '';
					}
					
					$oid = 1;
					$inv = '';
					$txt = "tmp_id = ".$user_id;
					$uid = 'tmp_'.$user_id;
					$tmp_id = $user_id;
				}
			}

			if(!empty($user_id) && !empty($itm_id)) {
				$sqls = mysqli_query($conn, "SELECT * FROM live_cart WHERE ".$txt." AND Item = '$itm_id'");
				$sql_itm = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM items WHERE id = '$itm_id'"));
				
				$dis_val = 0; //($itm_price * $sql_itm['discount']/100);
				$discount = 0; //$itm_price - $dis_val;
				
				$itm = $sql_itm['item_name'];
				$f_img = $sql_itm['f_img'];
				$item_code = $sql_itm['item_code'];
				// $search_id = $sql_itm['search_id'];
				$p_price = $sql_itm['price'];
				
				
				if(empty($inv)) {
					$inv = genID($conn);
				}
				
			
				

					if(mysqli_num_rows($sqls) == 0) {
						echo$sql = "INSERT INTO live_cart SET User_ID='$uid', tmp_id='$tmp_id', Item=$itm_id, name='$itm', img='$f_img', Qty='$qty',  Item_Code='$item_code', price='$p_price', order_id=$oid, order_date='$now'";
						
						if(empty($inv)) {
							echo json_encode(array("msgType" => 4, "msg" => "empty"));
						
						} else {
							$sql_new = $sql.", inv_id='$inv'";
							if(mysqli_query($conn, $sql_new)) {
								echo json_encode(array("msgType" => 1, "msg" => "success"));
							
							} else {
								echo json_encode(array("msgType" => 2, "msg" => "Sorry ! Could not be Save your Data"));
							}
						}
					
					} else {
						$rows = mysqli_fetch_assoc($sqls);
						$qty_ct = $rows['Qty'];
						$new_qty = $qty_ct+$qty;
						$p_price = $sql_itm['price'];
						
						
						//if($stock_qty >= $new_qty) {
							$sql_up = "UPDATE live_cart SET Qty='$new_qty', order_date='$now', price='$p_price' WHERE ".$txt." AND Item = $itm_id";
							if(mysqli_query($conn, $sql_up)) {
								echo json_encode(array("msgType" => 1, "msg" => "success"));
							
							} else {
								echo json_encode(array("msgType" => 2, "msg" => "Sorry ! Could not be Save your Data"));
							}
						
						//} else {
							//echo json_encode(array("msgType" => 3, "msg" => "stock out"));
						//}
					}
			
			} else {
				echo json_encode(array("msgType" => 4, "msg" => "empty"));
			}
	
		//} else {
			//echo json_encode(array("msgType" => 3, "msg" => "stock out"));
		//}
	}
}

function genID($conn) {
	$inv_id = mt_rand(100000, 999999);
	$s1 = mysqli_query($conn, "SELECT inv_id FROM live_cart WHERE inv_id='$inv_id'");
	$s2 = mysqli_query($conn, "SELECT inv_id FROM cart_details WHERE inv_id='$inv_id'");
	$s3 = mysqli_query($conn, "SELECT inv_id FROM order_details_temp WHERE inv_id='$inv_id'");
	$s4 = mysqli_query($conn, "SELECT inv_id FROM order_details WHERE inv_id='$inv_id'");

	if(mysqli_num_rows($s1) == 0 && mysqli_num_rows($s2) == 0 && mysqli_num_rows($s3) == 0 && mysqli_num_rows($s4) == 0) {
		return $inv_id;
	
	} else {
		genID($conn);
	}
}

/*function genID($conn, $sql) {
	$inv_id = mt_rand(100000, 999999);
	$s1 = mysqli_query($conn, "SELECT inv_id FROM live_cart WHERE inv_id='$inv_id'");
	$s2 = mysqli_query($conn, "SELECT inv_id FROM cart_details WHERE inv_id='$inv_id'");
	$s3 = mysqli_query($conn, "SELECT inv_id FROM order_details_temp WHERE inv_id='$inv_id'");
	$s4 = mysqli_query($conn, "SELECT inv_id FROM order_details WHERE inv_id='$inv_id'");

	if(mysqli_num_rows($s1) == 0 && mysqli_num_rows($s2) == 0 && mysqli_num_rows($s3) == 0 && mysqli_num_rows($s4) == 0) {
		$sql_new = $sql.", inv_id='$inv_id'";
		if(mysqli_query($conn, $sql_new)) {
			echo json_encode(array("msgType" => 1, "msg" => "success"));
		
		} else {
			echo json_encode(array("msgType" => 2, "msg" => "Sorry ! Could not be Save your Data"));
		}
	
	} else {
		genID($conn, $sql);
	}
}

/*********************** Remove Item ************************/

if (array_key_exists('remove_item', $_POST)) {
	$id = htmlspecialchars(strip_tags(trim($_POST['id'])), ENT_QUOTES, 'UTF-8');
	$sql = "DELETE FROM live_cart WHERE id=$id";
	
	if(!empty($id)) {
		if(mysqli_query($conn, $sql)) {
			echo json_encode(array("msgType" => 1, "msg" => "success"));
		
		} else {
			echo json_encode(array("msgType" => 2, "msg" => "error"));
		}
	
	} else {
		echo json_encode(array("msgType" => 2, "msg" => "empty id"));
	}
}

/*********************** Update Qty ************************/

if (array_key_exists('update_qty', $_POST)) {
	$id = htmlspecialchars(strip_tags(trim($_POST['id'])), ENT_QUOTES, 'UTF-8');
	$qty = htmlspecialchars(strip_tags(trim($_POST['qty'])), ENT_QUOTES, 'UTF-8');
	if(empty($qty) || $qty == 0) { $qty = 1; }

	if(!empty($id) && !empty($qty)) {
		$sqls = mysqli_query($conn, "SELECT Item FROM live_cart WHERE id = $id");
		if(mysqli_num_rows($sqls) == 0) {
			echo json_encode(array("msgType" => 2, "empty id"));
		
		} else {
			$rows = mysqli_fetch_assoc($sqls);
			$Item = $rows['Item'];
			
			$sql_itmv = mysqli_fetch_assoc(mysqli_query($conn, "SELECT price FROM items WHERE id = '$Item'"));
			$p_price = $sql_itmv['price'];
			
			
			//$sql_itmv = mysqli_fetch_assoc(mysqli_query($conn, "SELECT qty FROM items WHERE id = '$Item' AND stock_out=0 AND weight>0"));
			//$stock_qty = $sql_itmv['qty'];
			
			//if($stock_qty >= $qty) {
				$sql = "UPDATE live_cart SET Qty='$qty', order_date='$now', price='$p_price' WHERE id=$id";
				if(mysqli_query($conn, $sql)) {
					echo json_encode(array("msgType" => 1, "msg" => "success"));
				
				} else {
					echo json_encode(array("msgType" => 2, "msg" => "error"));
				}
			
			//} else {
				//echo json_encode(array("msgType" => 3, "msg" => "stock out"));
			//}
		}
	
	} else {
		echo json_encode(array("msgType" => 2, "empty id"));
	}
}

/********************** Add to wish list **********************/

if (array_key_exists('add_to_wishlist', $_POST)) {
	if(isset($_POST['item_id'])) {
		$itm_id = htmlspecialchars(strip_tags(trim($_POST['item_id'])), ENT_QUOTES, 'UTF-8');
	
	} else {
		$itm_id = '';
	}
	
	if(!empty($itm_id)) {
		if (isset($_SESSION['normal_user_cey'])) {
			$user_id = htmlspecialchars(strip_tags(trim($_SESSION['normal_user_cey'])), ENT_QUOTES, 'UTF-8');
			
			$sql_wh = mysqli_query($conn, "SELECT * FROM wish_list WHERE user_id=$user_id AND item_id=$itm_id");
			if(mysqli_num_rows($sql_wh) == 0) {
				$sql = "INSERT INTO wish_list SET user_id=$user_id, item_id=$itm_id, date='$now'";
				
				if(mysqli_query($conn, $sql)) {
					echo json_encode(array("msgType" => 1, "msg" => "success"));
				
				} else {
					echo json_encode(array("msgType" => 2, "msg" => "Sorry ! Could not be Save your Data"));
				}
			
			} else {
				
			}
		
		} else {
			echo json_encode(array("msgType" => 3, "msg" => "login"));
		}
	}
}

if (array_key_exists('wish_btn_disable', $_POST)) {
	if (isset($_SESSION['normal_user_cey'])) {
		$user_id = htmlspecialchars(strip_tags(trim($_SESSION['normal_user_cey'])), ENT_QUOTES, 'UTF-8');
	
		$sql = "SELECT item_id FROM wish_list WHERE user_id=$user_id";
		$result = mysqli_query($conn, $sql);
		
		if(mysqli_num_rows($result) > 0) {
			while($row = mysqli_fetch_assoc($result)) {
				$data[] = $row;
			}
		} else {
			$data = '';
		}
		
	} else {
		$data = '';
	}	
	echo json_encode($data);
}

/********************** Item Details **********************/

if (array_key_exists('get_items', $_POST)) {
	if(isset($_POST['item_id'])) {
		$itm_id = htmlspecialchars(strip_tags(trim($_POST['item_id'])), ENT_QUOTES, 'UTF-8');
	
	} else {
		$itm_id = '';
	}
	
	if(!empty($itm_id)) {
		$data = array();
		
		// Book Details
		$sql = mysqli_query($conn, "SELECT name, price, front_image AS fimg, back_image AS bimg, item_code, weight, stock_out AS stk, discount AS dis, qty, search_id AS sid FROM items WHERE id='$itm_id'"); 
		$row = mysqli_fetch_assoc($sql);
		
		array_push($data, $row);
		echo json_encode($data);
	}
}

/************************** Get Total Weight **************************/

if (array_key_exists('get_tot_weight', $_POST)) {
	if(!empty($user_id)) {
		$sqlw = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(weight*Qty) AS tot_weight FROM live_cart WHERE $whr=$user_id"));
		echo json_encode($sqlw);
	}
}

/*********************** Get Delivery Charges ***********************/

if (array_key_exists('get_delivery_fee', $_POST)) {
	$sql_cou = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM courier_charges"));
	$del_fee = $sql_cou['courier_fee'];

	echo json_encode(array("del_fee" => $del_fee, "msgType" => 1));
}

?>