<?php
	error_reporting(0);	
	$mysqli = new mysqli("127.0.0.1", "tr-iv", "", "taschenrechner");
	$operands = array("+", "-", "*", "/", "(", ")", "sin(", "cos(", "tan(");
	$numeric = array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "(-)");

	if(isset($_POST["key"]))
	{
		$key = $_POST["key"];
	} else {
		$key = "";
	}

	if($key == "AC")
	{
		// reset calc id
		for ($i=0; $i < rand(1, 10); $i++) { 
			$calcId = newCalc($mysqli);
		}	




	} else {
		$calcId = (isset($_POST["calcId"]) ? $_POST["calcId"] : newCalc($mysqli));
	}

	
	
	$currentInput = isset($_POST["currentInput"]) ? $_POST["currentInput"] : "";



	if(in_array($key, $operands))
	{
		// this is an operand
		if(in_array($key, array("sin(", "cos(", "tan("))) {
			// this is sin cos or tan

			$trigArr = array("sin(" => "s", "cos(" => "c", "tan(" =>"t");

			addToHistory($trigArr[$key], $calcId, $mysqli);
		} else {
			$operand = $key;
			addToHistory($operand, $calcId, $mysqli);
		}

		$currentInput = "";

	} else if(in_array($key, $numeric)) {
		// this is numeric

		// if current input already contains a . 
		if($key == ".")
		{		
			if(strpos($currentInput, ".") !== false)
			{
				// . is in current(array)rentInput
			} else {
				$currentInput .= $key;
				addToHistory($key, $calcId, $mysqli);
			}

		} else if($key == "(-)") {
			$currentInput .= "(-)";
			addToHistory("m", $calcId, $mysqli);
		} else {
			$currentInput .= $key;
			addToHistory($key, $calcId, $mysqli);
		}	
		
	} else if($key == "=") {

		// this is equal sign

	}

	$error = false;
	$historyOutput = "";	
	if(isset($_POST["key"])) { 
		if($_POST["key"] == "=") { 
			$result = calcThisShit($calcId, $mysqli); 
			if(isset($result["Error"])) { 
				if($result["Error"] == "Division by zero")
				{
					$historyOutput = "Fehler - durch Null geteilt"; 	
				} else {
					$historyOutput = "Fehler - Syntax?";
				}


				$error = true;
			} else { 
				$historyOutput = $result["Value"]; 
			} 
		} else if($_POST["key"] == "AC") { 
			/* Do nothing */ 
		} else { 
			$historyOutput = getHistory($calcId, $mysqli); 
		} 
	} 

	function addToHistory($key, $calcId, $mysqli) 
	{
		$mysqli->query("INSERT INTO `history` (`calc_id`, `calc_char`) VALUES ('$calcId', '$key')");
	}
	
	function getHistory($calcId, $mysqli)
	{
		$operands = array("+", "-", "*", "/", "(", ")", "s", "c", "t");

		$result = $mysqli->query("SELECT * FROM history WHERE `calc_id` = '$calcId';"); 

		$stringArray = array();
		$operatorOccured = false; 
 		while($row = $result->fetch_assoc())
 		{
 			$stringArray[] = $row["calc_char"];	
 		}

 		$reversed = array_reverse($stringArray);

 		$operatorFound = false;
 		$output = "";
 		foreach ($reversed as $key => $value) {

 			if(in_array($value, $operands) && !$operatorFound)
 			{
 				$operatorFound = true;
 				$output = "";
 			}

 			$output .= $value;
 		}
 		if(!$operatorFound)
 		{
 			$output = "";
 		} else {
 			$output = strrev($output);
 		}
 		
 		
 		return replaceTrig($output);
	}

	function sortByLength($a,$b){
    	return strlen($b)-strlen($a);
	}


	function newCalc($mysqli)
	{
		$unique = false;

		while(!$unique)
		{
			// generate new calc_id
			$calcId = (int)rand(0, 3000);

			$query = "SELECT COUNT(*) AS Count FROM `history` WHERE `calc_id` = '" . $calcId . "'";
			$result = $mysqli->query($query);
			$count = $result->fetch_object()->Count;

			if($count == 0)
			{
				$unique = true;	
			}
		}

		return $calcId;
	}

	function calcThisShit($calcId, $mysqli)
	{
		$output = array();
		$result = $mysqli->query("SELECT * FROM history WHERE `calc_id` = '$calcId';");

		$string = "";
		$operatorOccured = false; 
 		while($row = $result->fetch_assoc())
 		{
 			$string .= $row["calc_char"];	
 		}

 		$string = replaceTrig($string);
 		$string = strtr($string, array("(-)" => "(-1)*"));
 		
 		$openParaethesisCount = substr_count($string, "(");
 		$closeParenthesisCount = substr_count($string, ")");
 		
 		// add missing parenthesis
 		// calculate!!!!!!!!1111!
 		if($openParaethesisCount > $closeParenthesisCount)
 		{
 			$delta = $openParaethesisCount - $closeParenthesisCount;
 			$string .= str_repeat(")", $delta);
 		}

 		$result = eval("return $string;");
 		
 		if($result === false)
 		{
 			$error = error_get_last();
 			if($error["message"] == "Division by zero")
 			{
 				$output["Error"] = "Division by zero";
 			} else {
 				$output["Error"] = "Syntax Error";
 			}
 		} else {
 			$output["Value"] = $result;
 		}

 		return $output;
	}

	function historyText($calcId, $mysqli)
	{
		if($_POST["key"] == "=") 
		{ 
			return calcThisShit($mysqli);
		} else { 

			$history = replaceTrig(getHistory($classalcId, $mysqli));
			
			return $history;
		}
	}

	function replaceTrig($input)
	{
		$trigArrReplacement = array("s" => "sin(", "c" => "cos(", "t" => "tan(", "m" => "(-)");

		return strtr($input, $trigArrReplacement);
	}
?>
<html>
	<head>
		<title>Taschenrechner - @glanch</title>
		<link rel="stylesheet" href="style.css" />
		<link href='http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:700' rel='stylesheet' type='text/css'>

	</head>

	<body>
		<form method="POST">
			<input type="hidden" name="calcId" value="<?php echo $calcId; ?>"/>
			<div id="taschenrechner"	>
				<div>
					<input type="text" id="currentInput" name="currentInput" value="<?php echo ($key == "AC" || $error ? "" : $currentInput); ?>"/>
				</div>
				<br />
				<div >
					<input type="text" id="history" name="history" value="<?php echo $historyOutput; ?>"/>
				</div>
				<br />

				<div id="keys">
					<input type="submit" class="key operand" name="key" value="sin(" />
					
					<input type="submit" class="key operand" name="key" value="cos(" />
					
					<input type="submit" class="key operand" name="key" value="tan(" />

					<input type="submit" class="key operand" name="key" value="(" />

					<input type="submit" class="key operand" name="key" value=")" />

					<br style="clear: left;"/>

					<input type="submit" class="key" name="key" value="1" />
					
					<input type="submit" class="key" name="key" value="2" />
					
					<input type="submit" class="key" name="key" value="3" />

					<input type="submit" class="key operand" name="key" value="+" />

					<input type="submit" class="key operand" name="key" value="AC" />

					<br style="clear: left;"/>
					<input type="submit" class="key" name="key" value="4" />
					
					<input type="submit" class="key" name="key" value="5" />
					
					<input type="submit" class="key" name="key" value="6" />

					<input type="submit" class="key operand" name="key" value="-" />

					<br style="clear: left;"/>
					<input type="submit" class="key" name="key" value="7" />
					
					<input type="submit" class="key" name="key" value="8" />
					
					<input type="submit" class="key" name="key" value="9" />
					<input type="submit" class="key operand" name="key" value="*" />


					<br style="clear: left;"/>

					<input type="submit" class="key" name="key" value="." />

					<input type="submit" class="key" name="key" value="0" />

					<input type="submit" class="key" name="key" value="=" />

					<input type="submit" class="key operand" name="key" value="/" />

					<input type="submit" class="key operand" name="key" value="(-)" />

					
				</div>
			</div>

		</div>
	</body>
</html>