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

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

} else if (isset($_SESSION['temp_user_bb'])) {
	$user_id = htmlspecialchars(strip_tags(trim($_SESSION['temp_user_bb'])), ENT_QUOTES, 'UTF-8');
	$whr = 'temp_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');

if (array_key_exists('add_to_cart', $_POST)) {
	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 bookdetails 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_bb'])) {
				$user_id = htmlspecialchars(strip_tags(trim($_SESSION['normal_user_bb'])), ENT_QUOTES, 'UTF-8');
				
				$sql_usr = mysqli_fetch_assoc(mysqli_query($conn, "SELECT cusID, order_id FROM customer_reg WHERE cusID = $user_id"));
				$sql_invo = mysqli_query($conn, "SELECT inv_no 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_no'];
				}
				
				$oid = $sql_usr['order_id'];
				$txt = "User_ID = ".$user_id;
				$uid = $sql_usr['cusID'];
				$tmp_id = 0;
			
			} else {
				if (isset($_SESSION['temp_user_bb'])) {
					$user_id = htmlspecialchars(strip_tags(trim($_SESSION['temp_user_bb'])), ENT_QUOTES, 'UTF-8');
					$sql_invo = mysqli_query($conn, "SELECT inv_no FROM live_cart WHERE temp_id = $user_id");
					if(mysqli_num_rows($sql_invo) == 0) {
						$inv = '';
					
					} else {
						$row_invo = mysqli_fetch_assoc($sql_invo);
						$inv = $row_invo['inv_no'];
					}
					
					$oid = 1;
					$txt = "temp_id = ".$user_id;
					$uid = 'tmp_'.$user_id;
					$tmp_id = $user_id;
				
				} else {
					$sql_inv = mysqli_fetch_assoc(mysqli_query($conn, "SELECT token_no FROM invoice_no"));
					$new_uid = $sql_inv['token_no'];
					$sql_v = "UPDATE invoice_no SET token_no=token_no+1";
					
					if(mysqli_query($conn, $sql_v)) {
						$ts1 = mysqli_query($conn, "SELECT temp_id FROM live_cart WHERE temp_id='$new_uid'");
						$ts2 = mysqli_query($conn, "SELECT temp_id FROM cart_details WHERE temp_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_bb'] = $new_uid;
							$user_id = htmlspecialchars(strip_tags(trim($_SESSION['temp_user_bb'])), ENT_QUOTES, 'UTF-8');
						
						} else {
							//mysqli_query($conn, "UPDATE invoice_no SET token_no=token_no+1");
							$user_id = '';
						}
					
					} else {
						$user_id = '';
					}
					
					$oid = 1;
					$inv = '';
					$txt = "temp_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");
				
				if(mysqli_num_rows($sqls) == 0) {
					$sql_itm = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM bookdetails WHERE id = $itm_id"));
					$dis_val = ($sql_itm['price'] * $sql_itm['discount']/100);
					$discount = $sql_itm['price'] - $dis_val;
					
					$itm = $sql_itm['name'];
					$img = $sql_itm['front_image'];
					if(empty($img)) { $img = 'noimg.jpg'; }
					$itm_price = $sql_itm['price'];
					$isbn = $sql_itm['isbn'];
					$weight = $sql_itm['weight'];
					$search_id = $sql_itm['search_id'];
					
					if($dis_val > 0) { $price = $discount; } else {  $price = $sql_itm['price']; }
					
					$sql = "INSERT INTO live_cart SET User_ID='$uid', temp_id='$tmp_id', Item=$itm_id, name='$itm', img='$img', Qty='$qty', weight='$weight', isbn='$isbn', price='$price', item_price='$itm_price', order_id=$oid, date=now(), search_id='$search_id'";
					
					if(empty($inv)) {
						genID($conn, $sql);
					
					} else {
						$sql_new = $sql.", inv_no='$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;
					
					//if($stock_qty >= $new_qty) {
						$sql_up = "UPDATE live_cart SET Qty=Qty+$qty, date=now() 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, $sql) {
	$inv_id = mt_rand(100000, 999999);
	$s1 = mysqli_query($conn, "SELECT inv_no FROM live_cart WHERE inv_no='$inv_id'");
	$s2 = mysqli_query($conn, "SELECT inv_no FROM cart_details WHERE inv_no='$inv_id'");
	$s3 = mysqli_query($conn, "SELECT inv_no FROM order_details_temp WHERE inv_no='$inv_id'");
	$s4 = mysqli_query($conn, "SELECT inv_no FROM order_details WHERE inv_no='$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_no='$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 qty FROM bookdetails 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 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_bb'])) {
			$user_id = htmlspecialchars(strip_tags(trim($_SESSION['normal_user_bb'])), 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_bb'])) {
		$user_id = htmlspecialchars(strip_tags(trim($_SESSION['normal_user_bb'])), 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_item_details', $_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 = $cat_name = $author_n = $pub_n = array();
		
		// Book Details
		$sql = mysqli_query($conn, "SELECT name, price, front_image AS fimg, back_image AS bimg, isbn, publisher AS pub, weight, stock_out AS stk, discount AS dis, qty, search_id AS sid FROM bookdetails WHERE id='$itm_id'"); 
		$row = mysqli_fetch_assoc($sql);
		
		// Publisher
		$sql_pub = mysqli_fetch_assoc(mysqli_query($conn, "SELECT name AS pub, search_id AS sid FROM publisher WHERE id=".$row['pub']));
		$pub_n = $sql_pub;

		// Category
		$sql_cat = mysqli_query($conn, "SELECT category AS ct, search_id AS sid FROM category WHERE id IN (SELECT Cat_ID FROM category_map WHERE Book_ID=$itm_id)");
		while($row_cat = mysqli_fetch_assoc($sql_cat)) {
			$cat_name[] = $row_cat;
		}
		
		// Author
		$sql_au = mysqli_query($conn, "SELECT name AS auth, search_id AS sid FROM author WHERE id IN (SELECT Auth_ID FROM author_map WHERE Book_ID=$itm_id)");
		while($row_au = mysqli_fetch_assoc($sql_au)) {
			$author_n[] = $row_au;
		}

		array_push($data, $row);
		array_push($data, $cat_name);
		array_push($data, $author_n);
		array_push($data, $pub_n);
		
		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)) {
	$del_method = htmlspecialchars(strip_tags(trim($_POST['type'])), ENT_QUOTES, 'UTF-8');
	
	if(isset($_POST['country'])) {
		$country = htmlspecialchars(strip_tags(trim($_POST['country'])), ENT_QUOTES, 'UTF-8');
	} else {
		$country = '';
	}
	
	$sqlw = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(weight*Qty) AS tot_weight FROM live_cart WHERE $whr=$user_id"));
	$tot_weight = $sqlw['tot_weight'];
	
	$sql_cou = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM courier_charges"));
	
	$del_fee = 0;
	if($tot_weight > 0) {
		if($del_method == 1) { // Postal
			$sql_del = mysqli_fetch_assoc(mysqli_query($conn, "SELECT fee FROM postal_charges WHERE low_w < '$tot_weight' AND high_w >='$tot_weight'"));
			$del_fee = $sql_del['fee'];
			$max_w = 20000;
			echo json_encode(array("del_fee" => $del_fee, "tot_weight" => $tot_weight, "max_weight" => $max_w, "msgType" => 1));
		
		} else if($del_method == 2) { // Courier
			$a = floor($tot_weight/1000);
		
			
			if($tot_weight >= 0 && $tot_weight <= 1000) {
				$del_fee = $sql_cou['courier_fee'];
			
			} else {
				$del_fee = $sql_cou['courier_fee'] + ($a * $sql_cou['courier_1kg']);
			}
			$max_w = '';
			echo json_encode(array("del_fee" => $del_fee, "tot_weight" => $tot_weight, "max_weight" => $max_w, "msgType" => 1));
		  
		} else if($del_method == 4) { // Cash on Delivery
			$a = floor($tot_weight/1000);

			if($tot_weight >= 0 && $tot_weight <= 1000) {
				$del_fee = $sql_cou['cash_on_del'];

			} else {
				$del_fee = $sql_cou['cash_on_del'] + ($a * $sql_cou['cash_on_1kg']);
			}
			$max_w = '';
			echo json_encode(array("del_fee" => $del_fee, "tot_weight" => $tot_weight, "max_weight" => $max_w, "msgType" => 1));
	
		} else if($del_method == 3) { // EMS
			if(empty($country)) {
				echo json_encode(array("msgType" => 2));
				
			} else {
				$row_wgt = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM ems_charges WHERE country = '$country'"));
				$max_w = $row_wgt['max_kg']*1000;
				
				if($row_wgt['max_kg'] == 20) {
					if($tot_weight > 10000) { // 10001-20000 Grams
						$f = $row_wgt['kg_20'];
						
						$r = $tot_weight - 1000;
						$w = ceil($r/500);
						$del_fee = $row_wgt['kg_1'] + ($w * $f);
					
					} else if($tot_weight > 1000) { // 1001-10000 Grams
						$f = $row_wgt['kg_10'];
						
						$r = $tot_weight - 1000;
						$w = ceil($r/500);
						$del_fee = $row_wgt['kg_1'] + ($w * $f);
					
					} else if($tot_weight > 500) { // 501-1000 Grams
						$del_fee = $row_wgt['kg_1'];
					
					} else if($tot_weight > 250) { // 251-500 Grams
						$del_fee = $row_wgt['g_500'];
					
					} else { // 0-250 Grams
						$del_fee = $row_wgt['g_250'];
					}
					
					$del_fee += 250; // Packing Charges
				
				} else if($row_wgt['max_kg'] == 30) {
					if($tot_weight > 20000) { // 20001-30000 Grams
						$f = $row_wgt['kg_30'];
						
						$r = $tot_weight - 1000;
						$w = ceil($r/500);
						$del_fee = $row_wgt['kg_1'] + ($w * $f);
					
					} else if($tot_weight > 10000) { // 10001-20000 Grams
						$f = $row_wgt['kg_20'];
						
						$r = $tot_weight - 1000;
						$w = ceil($r/500);
						$del_fee = $row_wgt['kg_1'] + ($w * $f);
					
					} else if($tot_weight > 1000) { // 1001-10000 Grams
						$f = $row_wgt['kg_10'];
						
						$r = $tot_weight - 1000;
						$w = ceil($r/500);
						$del_fee = $row_wgt['kg_1'] + ($w * $f);
							
					} else if($tot_weight > 500) { // 501-1000 Grams
						$del_fee = $row_wgt['kg_1'];
					
					} else if($tot_weight > 250) { // 251-500 Grams
						$del_fee = $row_wgt['g_500'];
					
					} else { // 0-250 Grams
						$del_fee = $row_wgt['g_250'];
					}
					
					$del_fee += 250; // Packing Charges
				}
				echo json_encode(array("del_fee" => $del_fee, "tot_weight" => $tot_weight, "max_weight" => $max_w, "msgType" => 1));
			}
		}
	}
}

?>