<?php
require_once("dbconn.php");
require_once("phpFunctions.php");

$updateSucess = false;

if (isset($_GET["p"])) {
    $page = $_GET["p"];
    if ($userType == 2 || isset($superUser)) {
        $dbTable = ($page === "ipep") ? "predata_ip" : 
                   (($page === "ipes") ? "predata_ew" : 
                   (($page === "ipfd") ? "predata_fd" : 
                   (($page === "iptemp") ? "predata_temp" : "table-error")));
    } elseif ($userType == 1 || $userType == 3) {
        $dbTable = ($page === "ipep") ? "input_production" : 
                   (($page === "ipes") ? "egg_weight" : 
                   (($page === "ipfd") ? "feed_delivery" : 
                   (($page === "iptemp") ? "input_temp" : "table-error")));
    } else {
        $dbTable = "table-error";
    }
} else {
    $dbTable = "table-error";
}
	
mysqli_begin_transaction($conn);

if (isset($_POST["NewRowButton"]) && isset($_GET["p"]) && $_GET["p"] !== "es") 
{
	try
	{
		$result = executeQuery($conn, "INSERT INTO {$dbTable} (addedby_user, ProductionDate) VALUES (?,?)", "ss", [$userName, $ProductionDate]);
		
		if ($result === false) { 
			throw new Exception("Error executing query: " . $conn->error);
		} else {
			$updateSucess = true;
		} 
		
		mysqli_commit($conn);
		
		if ($updateSucess) 
		{
			$_SESSION["added_success"] = true;
			
			header("Location: " . $_SERVER["REQUEST_URI"]);
			exit();
		}
	} 
	catch (Exception $e) 
	{
        mysqli_rollback($conn);
		// Log the error message
        error_log($e->getMessage());
		// Redirect to an error page or display an error message
        //header("Location: error_page.php");
        //exit();
    }
}

if (isset($_POST["NewRowButton"]) && isset($_GET["p"]) && $_GET["p"] === "es") 
{
	try
	{
		$result = executeQuery($conn, "INSERT INTO egg_standards (addedby_user,is_deleted,version,is_current) VALUES (?,FALSE,?,TRUE)", "ss", [$userName, $currentVersion]);
		
		if ($result === false) { 
			throw new Exception("Error executing query: " . $conn->error);
		} else {
			$updateSucess = true;
		} 
		
		mysqli_commit($conn);
		
		if ($updateSucess) 
		{
			$_SESSION["added_success"] = true;
			header("Location: " . $_SERVER["REQUEST_URI"]);
			exit();
		}
	} 
	catch (Exception $e) 
	{
        mysqli_rollback($conn);
		// Log the error message
        error_log($e->getMessage());
		// Redirect to an error page or display an error message
        //header("Location: error_page.php");
        //exit();
    }
}

if (isset($_SESSION["added_success"])) 
{
	?>
	<script>
		$( ".dispMessage" ).append( "<div class='alert alert-primary d-flex align-items-center shadow' role='alert'><h4>Added Successfully!</h4></div>" );
	</script>
	<?php
    unset($_SESSION["added_success"]);
}
?>