<?php
session_start();
$username = $_SESSION['membership'];
$ISBN = $_GET["ISBN"];
$itemName = $_GET["itemName"];
$itemPrice = $_GET["itemPrice"];
$temQuantity = $_GET["temQuantity"];

if($_SESSION['membership']!= null)
{
include("connect.php");
if($_GET["add"] == "Add Cart"){
if(($username!= "")&&($ISBN!=""))
	{
		$result2 = mysql_query("SELECT * FROM tem WHERE temID = '$username'"); 
		if(mysql_num_rows($result2) == 0){
		$temID = $username;
		$temship = None;
		$result3 = mysql_query("INSERT INTO tem(temID, temship)VALUES('$temID', '$temship')");
		}
	
		$result = mysql_query("SELECT * FROM temcart WHERE temID = '$username'&&temItem = '$ISBN'"); 
		if(mysql_num_rows($result) >= 1)
		{
			echo "<script>alert('You already add this item into your cart.')</script>";
			echo "<script language='javascript'>window.location='bookmenu.php'</script>"; 
		}else{
$temID = $username;
$temItem = $ISBN;
$temName = $itemName;
$temPrice = $itemPrice;

	$result4 = mysql_query("SELECT * FROM item WHERE ISBN = '$ISBN'");
	$row = mysql_fetch_array($result4);
	$oldQuantity = $row["itemQuantity"];
	$oldSales = $row["itemSales"];
	$itemDate = $row["itemDate"];
	$date = date("Y-m-d");
	
if(date("Y-m-d",strtotime($date))>date("Y-m-d",strtotime($itemDate))){
	$newQuantity = $oldQuantity - $temQuantity;
	$newSales = $oldSales + $temQuantity;
	$result2 = mysql_query("UPDATE item SET itemQuantity = '$newQuantity', itemSales = '$newSales' WHERE ISBN = '$ISBN'");

	$result = mysql_query("INSERT INTO temcart(temID, temPrice, temName, temQuantity, temItem)VALUES('$temID', '$temPrice', '$temName', '$temQuantity', '$temItem')");
}else{
	$oldSales = $oldSales - $oldQuantity;
	$newSales = $oldSales + $temQuantity;
	$result2 = mysql_query("UPDATE item SET itemSales = '$newSales' WHERE ISBN = '$ISBN'");

	$result = mysql_query("INSERT INTO temcart(temID, temPrice, temName, temQuantity, temItem)VALUES('$temID', '$temPrice', '$temName', '$temQuantity', '$temItem')");
}
	$db = mysql_close();
	echo "<script language='javascript'>alert('Item enter into cart.')</script>";
	echo "<script language='javascript'>window.location='bookmenu.php'</script>";
	}
}}}else{
	echo "<script language='javascript'>alert ('Please login or register before add item to cart.')</script>";
	echo "<script language='javascript'>window.location='bookmenu.php'</script>";
}
?>