<?


session_start();
include("conexion.php");
$buyer = $_GET["buyer"];
$idbuy = $_GET["idbuy"];



$query = "SELECT * FROM User WHERE login ='".$buyer."'";
$result = mysql_query($query, $conexion);
$row = mysql_fetch_array($result);

$idbuy = $_GET["idbuy"];
$query = "SELECT * FROM Sell WHERE id = ".$idbuy;
$result = mysql_query($query, $conexion);
$row2 = mysql_fetch_array($result);
$amount = $row2["price"] * $row2["volume"] ; 
$total = $row["cash"] - $amount;
if ($row["cash"] > $amount){
	//The user that wants to buy will have less cash
	$query = "update User set cash=".$total." where login='".$_SESSION['login']."'";
	mysql_query($query, $conexion);
	
	
	//The user that sell will have more cash
	$usertosell = $row2["user"];
	$query = "update User set cash=cash +".$amount." where id = ".$usertosell;
	mysql_query($query, $conexion);
	
	//The user that buy will have more stocks
	$query = "select * from Ownership where user=".$row["id"]." and stock=".$row2["stock"]." and price=".$row2["price"];
	$result = mysql_query($query, $conexion);
	if (mysql_affected_rows($conexion) == 0) {
		$query = "insert into Ownership(user, stock, volume, price) values (".$row["id"].",".$row2["stock"].",".$row2["volume"].",".$row2["price"].")";
		mysql_query($query, $conexion);
	} else {
		$query = "update Ownership set volume=volume +".$row2["volume"]." where user='".$row["id"]."' and stock=".$row2["stock"];
		mysql_query($query, $conexion);
	}
	
	//The user that sell will have less stocks
	$query = "update Ownership set volume=volume -".$row2["volume"]." where user='".$usertosell."' and stock=".$row2["stock"];
	mysql_query($query, $conexion);
	
	//Delete the row with volume=0 in the table ownership
	$query = "delete from Ownership where volume <= 0";
	$result = mysql_query($query, $conexion);

	
	
	//Delete the sell in the table
	$query= "delete from Sell where id=".$idbuy;
	mysql_query($query, $conexion);
	
	//Insert the info in History
	$query = "insert into History(time, price, buyer, seller, stock, volume) values (now(),".$row2["price"].",".$row["id"].",".$usertosell.",".$row2["stock"].",".$row2["volume"].")";
	mysql_query($query, $conexion);
	
	
	header("Location: ../index.php");
}






?>