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

$con = mysql_connect("localhost","*****","*****");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("university", $con);

//get orders from database where order time older then 1 day
$sql="SELECT * FROM natty_orders WHERE OrderTime < NOW() - INTERVAL 1 DAY";

$result = mysql_query($sql);

while ($row = mysql_fetch_array($result))
{
$OrderState = $row['OrderState'];
$OrderNum = $row['OrderNum'];
$OrderItemInCart = $row['OrderItemInCart'];


if ($OrderState=="Live")
{
//increase item numbers in stock to original qty

//copy ordered item details to local array
for ($x=0; $x!=$OrderItemInCart; $x++)
{
$y=$x+1;
$Item = 'OrderItemID' . $y;
$FromMbro = 'OrderFromMbro' . $y;
$FromStock = 'OrderFromStock' . $y;

$OrderItem[$x] = $row[$Item];
$OrderFromMbro[$x] = $row[$FromMbro];
$OrderFromStock[$x] = $row[$FromStock];
}

//loop to get item details from database
for ($x=0; $x != $OrderItemInCart; $x++)
{
$query=mysql_query("SELECT * FROM natty WHERE ItemID=$OrderItem[$x]");
$row=mysql_fetch_object($query);
echo mysql_error();

$InMbro[$x]=$row->ItemInMbro;
$InStock[$x]=$row->ItemInStockton;
}

//calculate new quantity
for ($x=0; $x != $OrderItemInCart; $x++)
{
$NewInMbro[$x]=$InMbro[$x] + $OrderFromMbro[$x];
$NewInStock[$x]=$InStock[$x] + $OrderFromStock[$x];

//update available items in stores
$sql="UPDATE natty SET ItemInMbro=$NewInMbro[$x], ItemInStockton=$NewInStock[$x]
WHERE ItemID=$OrderItem[$x] ";

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

//change order status to "expired"
$sql="UPDATE natty_orders SET OrderState='Expired' WHERE OrderNum='$OrderNum' ";

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