<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<?php session_start();
if(isset($_SESSION['email']))
{
echo "";
}
else
{
	header( "Location: login.php" ); 
}
?>
<html>
 <head>
  <title> New Document </title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <style>
  p{
	  font-family: Calibri;
	  color: black;
	  font-size: 20;
	}
  </style>
  <script type="text/javascript">
function submit()
{
	document.order.submit();
}
function Homesubmit()
{
	document.home.submit();
}
</script>
 </head>
 <body style="background-image:url('gray.jpg');background-size:100% 100%;
background-repeat:no-repeat;">
 <?php

//retrieving stock data and storing them in the database
$row = 1;
if (($handle = fopen("http://download.finance.yahoo.com/d/quotes.csv?s=AAPL+ADBE+AMZN+APOL+CSCO+CTSH+DELL+ERIC+GOOG+INFY+INTC+MSFT+ORCL+PROV+QCOM+SNDK+SWIR+VRTU+YHOO+ACCL+ACIW+BBSI+BITS+BLKB+BCSI+CVLT+CNQR+CCUR+PROJ+ELRC+ERII+FFDF+FNGN+GSBC+GRNB+GCBC+HALL+HBNK+HBHC+IBOC+JXSB+JFBC+KINS
+LKFN+SIRI+RAX+VVUS+DNDN+EBAY+RMBS&f=nsabp5c1v", "r")) !== FALSE)
{
	$con = mysql_connect("localhost:3306","","");
	if (!$con)
	{
		die('Could not connect: ' . mysql_error());
	}
	mysql_select_db("test", $con);
	mysql_query("delete from stockdata");
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) 
	{
		$num = count($data);
		$row++;
		for ($c=0; $c < $num; $c++) 
		{
		   $var[$c]= $data[$c] ;
		}
		//inserting fields into stockdata database
		mysql_query("INSERT INTO stockdata (company,symbol,ask,bid,price,stockchange,stockvolume)
		VALUES ('$var[0]','$var[1]','$var[2]','$var[3]','$var[4]','$var[5]','$var[6]')");
	}
	mysql_close($con);
    fclose($handle);
}
?>

 <?php error_reporting (E_ALL ^ E_NOTICE);
	//processing transaction
	$ticker=$_POST["ticker"];
	$quantity=$_POST["quantity"];
	$buysell=$_POST["buySellAction"];
	$ordertype=$_POST["otype"];
	$company=$_POST["tickerhide"];
	$lprice=$_POST["lprice"];
	$sprice=$_POST["sprice"];
	$con= mysql_connect("localhost:3306","","");
	if (!$con)
	{
		die('Could not connect: ' . mysql_error());
	}
	mysql_select_db("test", $con);

	//fetching updated askprice and bid price
	$askbidresult=mysql_query("select ask,bid from stockdata where symbol='$ticker'");
	while($row=mysql_fetch_array($askbidresult))
	{
		$askPrice=$row['ask'];
		$bidPrice=$row['bid'];
	}
	$email=$_SESSION['email'];
	$useridres=mysql_query("select userid from userdata where Email='$email';");
	while($row=mysql_fetch_array($useridres))
	{
		$userid=$row['userid'];
	}
	//Processing market buy orders

	mysql_query("SET autocommit=0;");
	if($buysell=="buy" && $ordertype=="market")
	{
		$portfolio_result=mysql_query("select cashbalance from portfolio where userid=$userid;");
		while($row = mysql_fetch_array($portfolio_result))
		{
			$cash_val = $row['cashbalance'];
		}
		$stockprice=$quantity*$bidPrice;
		$commission=$stockprice/100;
		$d=$stockprice+$commission;
		if($cash_val<$d)
		{
			echo "YOU DON'T HAVE ENOUGH FUNDS"."</br>";
			mysql_close($con);
		}
		else
		{
			$cash_val=$cash_val-$d;
			mysql_query("update portfolio set cashbalance=$cash_val,datemodified=SYSDATE() where userid=$userid;");
			mysql_query("insert into orders(company,tickersymbol,price,action,order_type,threshold1,threshold2,quantity,transaction_date,status,userid,commission) values('$company','$ticker',$bidPrice,'$buysell','$ordertype',null,null,$quantity,SYSDATE(),'completed',$userid,$commission);");
			mysql_query("commit");
			echo "<p>";
			echo "YOUR TRANSACTION HAS BEEN PROCESSED"."</br>"."</br>";
			echo "Transaction Summary:"."</br>";
			echo "Ticker-symbol:".$ticker."</br>";
			echo "BidPrice:".$bidPrice.'$'."</br>";
			echo "Quantity:".$quantity."</br>";
			echo "Action:".$buysell."</br>";
			echo "Order-type:".$ordertype."</br>";
			echo "Commission fee:".$commission.'$'."</br>";
			echo "</p>";
			
			//email-notification
			require_once("email.php");
			$objEmail	=	new CI_Email();
			$objEmail->from('tradefun2011@gmail.com', 'TradeFun');
			$objEmail->to($email);
			$objEmail->subject('Transaction Summary');
			$objEmail->message('Transaction Summary:'.nl2br("\nTicker-symbol:$ticker").nl2br("\nBidPrice:$bidPrice$").nl2br("\nQuantity:$quantity").nl2br("\nAction:$buysell").nl2br("\nOrder-type:$ordertype").nl2br("\nCommission fee:$commission$"));
			if ($objEmail->send())
				echo 'E-mail notification sent.';
			else
				echo 'An error occured while sending email notification';
			mysql_close($con);
		}
		
	}
	
	//processing market sell orders
	if($buysell=="sell" && $ordertype=="market")
	{
		$ticker_result1=mysql_query("select sum(quantity) as count from orders
		where tickersymbol='$ticker' and userid=$userid and status='completed' and action='buy'");
		while($row = mysql_fetch_array($ticker_result1))
		{
			$stock_bought = $row['count'];
		}
		$ticker_result2=mysql_query("select sum(quantity) as count from orders
		where tickersymbol='$ticker' and userid=$userid and status='completed' and action='sell'");
		while($row = mysql_fetch_array($ticker_result2))
		{
			$stock_sold = $row['count'];
		}
		$stock_num=$stock_bought-$stock_sold;
		if($stock_num>=$quantity)
		{
			$portfolio_result=mysql_query("select cashbalance from portfolio where userid=$userid;");
			while($row = mysql_fetch_array($portfolio_result))
			{
				$cash_val = $row['cashbalance'];
			}
				$stockprice=$quantity*$askPrice;
				$commission=$stockprice/100;
				$cash_val=$cash_val+$stockprice-$commission;
				mysql_query("update portfolio set cashbalance=$cash_val,datemodified=SYSDATE() where userid=$userid;");
				mysql_query("insert into orders(company,tickersymbol,price,action,order_type,threshold1,threshold2,quantity,transaction_date,status,userid,commission) values('$company','$ticker',$bidPrice,'$buysell','$ordertype',null,null,$quantity,SYSDATE(),'completed',$userid,$commission);");
				mysql_query("commit");
				echo "<p>";
				echo "YOUR TRANSACTION HAS BEEN PROCESSED"."</br>"."</br>";
				echo "Transaction Summary:"."</br>";
				echo "Ticker-symbol:".$ticker."</br>";
				echo "AskPrice:".$askPrice.'$'."</br>";
				echo "Quantity:".$quantity."</br>";
				echo "Action:".$buysell."</br>";
				echo "Order-type:".$ordertype."</br>";
				echo "Commission fee:".$commission.'$'."</br>";
				echo "</p>";
				mysql_close($con);
				require_once("email.php");
				$objEmail	=	new CI_Email();
				$objEmail->from('tradefun2011@gmail.com', 'TradeFun');
				$objEmail->to($email);
				$objEmail->subject('Transaction Summary');
				$objEmail->message('Transaction Summary:'.nl2br("\nTicker-symbol:$ticker").nl2br("\nAskPrice:$askPrice$").nl2br("\nQuantity:$quantity").nl2br("\nAction:$buysell").nl2br("\nOrder-type:$ordertype").nl2br("\nCommission fee:$commission$"));
				if ($objEmail->send())
					echo 'E-mail notification sent.';
				else
					echo 'An error occured while sending email notification';
			}
			else
			{
				echo "YOU DON'T HAVE ENOUGH SHARES IN YOUR PORTFOLIO"."</br>";
				mysql_close($con);
			}
	}
	//Processing limit buy orders
	if($buysell=="buy" && $ordertype=="limit")
	{
		
			mysql_query("insert into orders(company,tickersymbol,price,action,order_type,threshold1,threshold2,quantity,transaction_date,status,userid,commission) values('$company','$ticker',null,'$buysell','$ordertype',$lprice,null,$quantity,SYSDATE(),'pending',$userid,null);") or die(mysql_error());
			mysql_query("commit");
			echo "<p>";
			echo "YOUR TRANSACTION IS PENDING"."</br>"."</br>";
			echo "Transaction Summary:"."</br>";
			echo "Ticker-symbol:".$ticker."</br>";
			echo "Limit Price:".$lprice.'$'."</br>";
			echo "Quantity:".$quantity."</br>";
			echo "Action:".$buysell."</br>";
			echo "Order-type:".$ordertype."</br>";
			echo "</p>";
			mysql_close($con);
		
	}
	
	//Processing limit sell orders
	if($buysell=="sell" && $ordertype=="limit")
	{
		
				mysql_query("insert into orders(company,tickersymbol,price,action,order_type,threshold1,threshold2,quantity,transaction_date,status,userid,commission) values('$company','$ticker',null,'$buysell','$ordertype',$lprice,null,$quantity,SYSDATE(),'pending',$userid,null);");
				mysql_query("commit");
				echo "<p>";
				echo "YOUR TRANSACTION IS PENDING"."</br>"."</br>";
				echo "Transaction Summary:"."</br>";
				echo "Ticker-symbol:".$ticker."</br>";
				echo "Limit Price:".$lprice.'$'."</br>";
				echo "Quantity:".$quantity."</br>";
				echo "Action:".$buysell."</br>";
				echo "Order-type:".$ordertype."</br>";
				echo "</p>";
				mysql_close($con);
	}
	//Processing stop buy orders
	if($buysell=="buy" && $ordertype=="stop")
	{
		
			mysql_query("insert into orders(company,tickersymbol,price,action,order_type,threshold1,threshold2,quantity,transaction_date,status,userid,commission) values('$company','$ticker',null,'$buysell','$ordertype',null,$sprice,$quantity,SYSDATE(),'pending',$userid,null);");
			mysql_query("commit");
			echo "<p>";
			echo "YOUR TRANSACTION IS PENDING"."</br>"."</br>";
			echo "Transaction Summary:"."</br>";
			echo "Ticker-symbol:".$ticker."</br>";
			echo "Limit Price:".$sprice.'$'."</br>";
			echo "Quantity:".$quantity."</br>";
			echo "Action:".$buysell."</br>";
			echo "Order-type:".$ordertype."</br>";
			echo "</p>";
			mysql_close($con);
		
	}
	//Processing stop sell orders
	if($buysell=="sell" && $ordertype=="stop")
	{
		
				mysql_query("insert into orders(company,tickersymbol,price,action,order_type,threshold1,threshold2,quantity,transaction_date,status,userid,commission) values('$company','$ticker',null,'$buysell','$ordertype',null,$sprice,$quantity,SYSDATE(),'pending',$userid,null);");
				mysql_query("commit");
				echo "<p>";
				echo "YOUR TRANSACTION IS PENDING"."</br>"."</br>";
				echo "Transaction Summary:"."</br>";
				echo "Ticker-symbol:".$ticker."</br>";
				echo "Limit Price:".$sprice.'$'."</br>";
				echo "Quantity:".$quantity."</br>";
				echo "Action:".$buysell."</br>";
				echo "Order-type:".$ordertype."</br>";
				echo "</p>";
				mysql_close($con);
	}
	
 ?>
 <form name="order" action="tradestocks.php">
 <input type="button" value="Create New Order" onclick="submit()" />
 </form>
</body>
</html>