<?Php
/*
* @author Istvan Franko
* @copyright 2014
*/

session_start();

if (!isset($_SESSION['cart'])) 
{
  $_SESSION['cart']=array(); 
}

if (!isset($_SESSION['loggedin'])) 
{
  $_SESSION['loggedin'] = '0'; 
}
?>

<html>

<head>
<title>Natty Notebooks Inc.</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>

<body>

<div id="container">

	<div id="header">
	<! header picture in css >
	</div>
	
	<div id="navigation">
		<?php include 'navigation-bar.php'; ?>
	</div>
	
<div id="aside">
	<br><fieldset style="width:85%"><legend>HELP</legend>
	<p>If the field has been filled with all appropriate information a summary is shown here.</p>
	<p>If you get any error message please go back and enter the required data.<p>
	<p>You can continue browsing or confirm your basket with the links 
	on the bottom of the page.</p>
</div>

<div id="content">

<br>
<fieldset style="width:95%"><legend>CART CHECK</legend>
<br>
<p><img width="120" src="images/shopping-cart.png" alt="Shopping Cart" >
<br>


<?php

//read session array to local array
while (list ($key, $val) = each ($_SESSION['cart'])) 
{
$cart[$key] = $val;
}

//check the local array length
$OrderCounter = count($cart);

$validations = 0; //reference variable for validations

if ($_SERVER["REQUEST_METHOD"] == "POST")
{

$phone = test_input($_POST["phone"]);

if (empty($_POST["name"]))
    {
	$validations++;
	echo "Name is required<br><br>";
	}
else
    {$name = test_input($_POST["name"]);
	// check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$name))
      {
	  $validations++;
      echo "Only letters and white space allowed<br><br>";
      }
	}
	
if (empty($_POST["email"]))
    {
	$validations++;
	echo "Email is required<br><br>";
	}
  else
    {$email = test_input($_POST["email"]);
	// check if e-mail address syntax is valid
    if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email))
      {
	  $validations++;
      echo "Invalid email format<br><br>";
      }
	}	
	
	


//loop for get required numbers 
if ($OrderCounter > 0)
	{
	$ItemNumMbro[0] = $_POST['ItemNumMbro'][0];
	$ItemNumStock[0] = $_POST['ItemNumStock'][0];
	}
elseif ($OrderCounter > 1)
	{
	$ItemNumMbro[1] = $_POST['ItemNumMbro'][1];
	$ItemNumStock[1] = $_POST['ItemNumStock'][1];
	}
elseif ($OrderCounter > 2)
	{
	$ItemNumMbro[2] = $_POST['ItemNumMbro'][2];
	$ItemNumStock[2] = $_POST['ItemNumStock'][2];
	}
elseif ($OrderCounter > 3)
	{
	$ItemNumMbro[3] = $_POST['ItemNumMbro'][3];
	$ItemNumStock[3] = $_POST['ItemNumStock'][3];
	}
else 
	{
	$ItemNumMbro[4] = $_POST['ItemNumMbro'][4];
	$ItemNumStock[4] = $_POST['ItemNumStock'][4];
	}	
	
}

function test_input($data)
{
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}	
	
$con = mysql_connect("localhost","*****","*****");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("university", $con);
	
//check requested amount don't more as in stock
	
for ($x=0; $x != $OrderCounter; $x++)
{
$id = $cart[$x];

$query=Mysql_query("SELECT * FROM natty WHERE ItemID=$id ");
$row=mysql_fetch_object($query);
echo mysql_error();

//amount checking
if ($ItemNumStock[$x] > $row->ItemInStockton  or $ItemNumMbro[$x] > $row->ItemInMbro)
	{
	$validations++;
	echo "<p>You requested more than we have in stock.<br><br>";
	}
	
//empty fields checking
if (empty($ItemNumStock[$x]))
	{
		if (empty($ItemNumMbro[$x]))
		{
		$validations++;
		echo "You left both fields empty in at item: " . $row->ItemName . "<br><br>";
		}
	}	
}

//if the required amounts was right the $validations must be 0
if ($validations == 0)
{

echo "<p>Dear " . $name . ",<br>";
echo "Email: " . $email . "<br>";
if (!empty($phone))
	{
	echo "Phone: " . $phone . "<br>";
	}
echo "<br>We received your order.</p><hr/><br>";

$totalprice = 0;

//loop display items in cart
for ($x=0; $x != $OrderCounter; $x++)
{
$id = $cart[$x];

$query=Mysql_query("SELECT * FROM natty WHERE ItemID=$id ");
$row=mysql_fetch_object($query);
echo mysql_error();

if (!empty($ItemNumMbro[$x]))
{
echo "<p>" . $ItemNumMbro[$x] . " qty " . $row->ItemName . " from Middlesbrough shop. Unit price: &#163;" . $row->ItemPrice . "</p><hr/><br>";
$price = $row->ItemPrice;
$totalprice = $totalprice + $price * $ItemNumMbro[$x];
}

if (!empty($ItemNumStock[$x]))
{
echo "<p>" . $ItemNumStock[$x] . " qty " . $row->ItemName . " from Stockton shop. Unit price: &#163;" . $row->ItemPrice . "</p><hr/><br>";
$price = $row->ItemPrice;
$totalprice = $totalprice + $price * $ItemNumStock[$x];
}

}

//replace single quotes from text field to insert to sql
$name2 = str_replace("'", "''", $name);
$email2 = str_replace("'", "''", $email);
$phone2 = str_replace("'", "''", $phone);

//setting time and item state variables
$state = "Uncompleted";
date_default_timezone_set('Europe/London');
$time = date('Y/m/d h:i:s', time());

//construct a valid SQL statement that will be send to the database server.
$sql="INSERT INTO natty_orders (OrderName, OrderEmail, OrderPhone, OrderItemInCart, OrderTime, OrderState) 
VALUES 
('$name2', '$email2', '$phone2', '$OrderCounter', '$time', '$state')";

// run the SQL query on the server (i.e. send the SQL to the database server)
if (!mysql_query($sql,$con))
{
die ('Error: ' . mysql_error());
}


//get order number from database
$result = mysql_query("SELECT * FROM natty_orders WHERE OrderEmail='$email' ORDER BY OrderNum DESC LIMIT 1 ");
while ($row = mysql_fetch_array($result))
{
$OrderNumber=$row['OrderNum'];
}

//display order number
echo "<p>Your order number is: " . $OrderNumber . "</p><hr/><br>";

echo "<p>We will keep them for 24 hours to you for collect.</p><hr/><br>";

//update database to insert items details
for ($x=0; $x != $OrderCounter; $x++)
{
$y = $x+1;
$sql="UPDATE natty_orders SET OrderItemID$y='$cart[$x]', OrderFromMbro$y='$ItemNumMbro[$x]', OrderFromStock$y='$ItemNumStock[$x]'
WHERE OrderNum='$OrderNumber' ";

if (!mysql_query($sql,$con))
{
die ('Error: ' . mysql_error());
}
}

//display total price
echo "<p>Your cart total is: &#163;" . $totalprice . "</p><hr/><br>";

echo "
<form method='POST' action='cart-confirm.php'>
<input type='hidden' name='OrderNumber' value='$OrderNumber'>
<input type='hidden' name='totalprice' value='$totalprice'>
<input type='submit' style='float: right;' value='Confirm'>
</form>
";

}
else
{
echo "Please try again?</p>";
echo "<br><hr>";
echo "<p><a style='float: left' href='product-list.php'>Back to list</a>";
echo "<p><a style='float: right' href='cart-display.php'>Go back to cart</p></a>";

}
mysql_close($con);

?>

</fieldset>

</div>

<div id="footer">
<p align="center">Copyright &#169; Istvan Franko, 2014</p>
</div>


</div>

</body>
</html>