<?php
session_start();
$username = $_SESSION['membership'];

if($_POST["Back"] == "Back To Cart")
{
	echo "<script language='javascript'>window.location='subtemcart.php'</script>"; 
}
if($_POST["Back"] == "Back")
{
	echo "<script language='javascript'>window.location='bookmenu.php'</script>"; 
}
if($_POST["Delete"] == "Clear All")
{
	include("connect.php");
	$result5 = mysql_query("SELECT * FROM temcart WHERE temID = '$username'");
	$total_records = mysql_num_rows($result5);
	
	for($i=0; $i<$total_records; $i++){
	$row5 = mysql_fetch_array($result5);
	
	$temQuantity = $row5["temQuantity"];
	
	$ISBN = $row5["temItem"];
	
	$result4 = mysql_query("SELECT * FROM item WHERE ISBN = '$ISBN'");
	$row = mysql_fetch_array($result4);
	$oldQuantity = $row["itemQuantity"];
	$oldSales = $row["itemSales"];
	
	$newQuantity = $oldQuantity + $temQuantity;
	$newSales = $oldSales - $temQuantity;
	$result2 = mysql_query("UPDATE item SET itemQuantity = '$newQuantity', itemSales = '$newSales' WHERE ISBN = '$ISBN'");

	$query=mysql_query("delete from temCart where temID='$username'&&temItem='$ISBN'");
	}
	echo "<script>alert('All item is remove from cart.')</script>";
	echo "<script language='javascript'>window.location='bookmenu.php'</script>"; 
}
else{
include("connect.php");
include("temcartID.php");
session_start();
$username = $_SESSION['membership'];

$cartTotal = $_POST["cartTotal"];
$cartName = $username;
$cartAddress = $_POST["cartAddress"];
$cartTel = $_POST["cartTel"];
$cartEmail = $_POST["cartEmail"];
$cartCode = $_POST["cartCode"];
$cartCity = $_POST["cartCity"];
$cartState = $_POST["cartState"];
$cartDate = date("Y-m-d");
$cartPay = $_POST["cartPay"];
$cartShip = $_POST["temShip"];
$total = $_POST["total"];
$cartNo = $index;

$point = $total/10;

$result4 = mysql_query("SELECT memberpoint FROM membership WHERE memberLname = '$username'");
$row4 = mysql_fetch_array($result4);
$oldpoint = $row4["memberpoint"];
$memberpoint = $oldpoint + $point;

$result1 = mysql_query("INSERT INTO cart(cartNo, cartName, cartAddress, cartDate, cartTel, cartEmail, cartCode, cartCity, cartState, cartTotal, cartShip, cartPay)VALUES('$cartNo', '$cartName', '$cartAddress', '$cartDate', '$cartTel', '$cartEmail', '$cartCode', '$cartCity', '$cartState','$cartTotal', '$cartShip', '$cartPay')");

$result2 = mysql_query("UPDATE temcart SET temcartNo = '$cartNo' WHERE temID = '$username'");

$result3 = mysql_query("INSERT INTO cartitem(cartItem, cartQuantity, cartPrice, cartNo) SELECT temItem, temQuantity, temPrice, temcartNo FROM temcart WHERE temID = '$username'");

$result5 = mysql_query("UPDATE membership SET memberpoint = '$memberpoint' WHERE memberLname = '$username'");

$query=mysql_query("delete from temCart where temID='$username'");
$query=mysql_query("delete from tem where temID='$username'");
$db = mysql_close();
echo "<script>alert('Thanks you!')</script>";
echo "<script language='javascript'>window.location='subtemcart.php'</script>";
}

?>