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

$updateSuccess = false;
$rcode = [];

foreach ($_POST as $key => $value) 
{
	if (preg_match("/^id_(\d+)$/", $key, $matches)) 
	{
		$index = intval($matches[1]);
		$rcode[] = $index;
	}
}

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["SaveButton"]) && isset($_GET["p"]) && $_GET["p"] === "ipep") 
{
    try
    {
        for ($i = 0; $i < count($rcode); $i++) 
        {
			$keys = [
				"BatchName_$rcode[$i]", 
				"BatchCode_$rcode[$i]", 
				"BldgNo_$rcode[$i]", 
				"AgeInWeeks_$rcode[$i]", 
				"Hen_Day_$rcode[$i]", 
				"H1_T_$rcode[$i]", 
				"H2_T_$rcode[$i]", 
				"H3_T_$rcode[$i]", 
				"H4_T_$rcode[$i]", 
				"H5_T_$rcode[$i]",
				"H6_T_$rcode[$i]", 
				"H6_PCS_$rcode[$i]", 
				"H_TOTAL_$rcode[$i]", 
				"Mortality_$rcode[$i]", 
				"Reject_$rcode[$i]", 
				"Cull_$rcode[$i]",
				"Depletion_$rcode[$i]", 
				"Inv_Adj_$rcode[$i]", 
				"F_CODE_$rcode[$i]", 
				"ProductionDate", 
				"id_$rcode[$i]"
			];
			
			$data = getDataFromPost($keys, $_POST); 
			$originalData = fetchOriginalData($conn, $data["id_$rcode[$i]"]);
			
			if (hasChanges($originalData, $data)) 
			{
				if ($dbTable === "input_production")
				{
					$result = executeQuery($conn, "SELECT * FROM input_production WHERE id = ? AND is_current = TRUE", "s", [$data["id_$rcode[$i]"]]);
					
					if ($result === false) { 
						throw new Exception("Error executing query: " . $conn->error);
					} 
					
					if ($result->num_rows > 0) {
						$currentRecord = $result->fetch_assoc();
						$id = $currentRecord["id"];
						$currentVersion = $currentRecord["version"];
						
						// Mark the current version as outdated
						$updateOldVersionQuery = "UPDATE input_production SET is_current = FALSE WHERE id = ? AND is_current = TRUE";
						$updateOldResult = executeQuery($conn, $updateOldVersionQuery, "i", [$id]);
						
						if ($updateOldResult === false) { 
							throw new Exception("Error executing query: " . $conn->error);
						} 		
						
						$current_ProductionDate = $currentRecord["ProductionDate"];
						
						// Insert the new version
						$newVersion = $currentVersion + 1;
						$insertNewVersionQuery = "INSERT INTO input_production (addedby_user,ProductionDate,BatchName,BatchCode,BldgNo,AgeInWeeks,Hen_Day,H1_T,H2_T,H3_T,H4_T,H5_T,H6_T,H6_PCS,H_TOTAL,Mortality,Reject,Cull,Depletion,Inv_Adj,F_CODE,version,is_current) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, TRUE)";
						$updateResult = executeQuery($conn, $insertNewVersionQuery, "ssssssssssssssssssssss", [$userName, $current_ProductionDate, $data["BatchName_$rcode[$i]"], $data["BatchCode_$rcode[$i]"], $data["BldgNo_$rcode[$i]"], $data["AgeInWeeks_$rcode[$i]"], $data["Hen_Day_$rcode[$i]"], $data["H1_T_$rcode[$i]"], $data["H2_T_$rcode[$i]"], $data["H3_T_$rcode[$i]"], $data["H4_T_$rcode[$i]"], $data["H5_T_$rcode[$i]"], $data["H6_T_$rcode[$i]"], $data["H6_PCS_$rcode[$i]"], $data["H_TOTAL_$rcode[$i]"], $data["Mortality_$rcode[$i]"], $data["Reject_$rcode[$i]"], $data["Cull_$rcode[$i]"], $data["Depletion_$rcode[$i]"], $data["Inv_Adj_$rcode[$i]"], $data["F_CODE_$rcode[$i]"], $newVersion]);
					
						if ($updateResult === false) { 
							throw new Exception("Error executing query: " . $conn->error);
						} else {
							$updateSuccess = true;
						}
					}
				}
				else
				{	
					$query = "UPDATE predata_ip SET addedby_user=?,BatchName=?,BatchCode=?,BldgNo=?,AgeInWeeks=?,Hen_Day=?,H1_T=?,H2_T=?,H3_T=?,H4_T=?,H5_T=?,H6_T=?,H6_PCS=?,H_TOTAL=?,Mortality=?,Reject=?,Cull=?,Depletion=?,Inv_Adj=?,F_CODE=? WHERE ProductionDate=? AND id=?";
					$result = executeQuery($conn, $query, "ssssiiiiiiiiiiiiiiissi", [$userName, $data["BatchName_$rcode[$i]"], $data["BatchCode_$rcode[$i]"], $data["BldgNo_$rcode[$i]"], $data["AgeInWeeks_$rcode[$i]"], $data["Hen_Day_$rcode[$i]"], $data["H1_T_$rcode[$i]"], $data["H2_T_$rcode[$i]"], $data["H3_T_$rcode[$i]"], $data["H4_T_$rcode[$i]"], $data["H5_T_$rcode[$i]"], $data["H6_T_$rcode[$i]"], $data["H6_PCS_$rcode[$i]"], $data["H_TOTAL_$rcode[$i]"], $data["Mortality_$rcode[$i]"], $data["Reject_$rcode[$i]"], $data["Cull_$rcode[$i]"], $data["Depletion_$rcode[$i]"], $data["Inv_Adj_$rcode[$i]"], $data["F_CODE_$rcode[$i]"], $ProductionDate, $data["id_$rcode[$i]"]]);
				
					if ($result === false) { 
						throw new Exception("Error executing query: " . $conn->error);
					} else {
						$updateSuccess = true;
					}
				}
			}
        }
        mysqli_commit($conn);
        
        if ($updateSuccess) 
        {
            $_SESSION["update_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();
    }
}
elseif (isset($_POST["SaveButton"]) && isset($_GET["p"]) && $_GET["p"] === "ipes") 
{
	try
    {
        for ($i = 0; $i < count($rcode); $i++) 
        {
			$keys = [
				"BatchName_$rcode[$i]", 
				"BatchCode_$rcode[$i]", 
				"AgeInWeeks_$rcode[$i]", 
				"JMB_1_$rcode[$i]", 
				"JMB_2_$rcode[$i]", 
				"JMB_3_$rcode[$i]", 
				"JMB_PCS_$rcode[$i]", 
				"JMB_$rcode[$i]", 
				"XLR_1_$rcode[$i]", 
				"XLR_2_$rcode[$i]", 
				"XLR_3_$rcode[$i]",
				"XLR_PCS_$rcode[$i]", 
				"XLR_$rcode[$i]", 
				"LRG_1_$rcode[$i]", 
				"LRG_2_$rcode[$i]", 
				"LRG_3_$rcode[$i]",
				"LRG_PCS_$rcode[$i]", 
				"LRG_$rcode[$i]", 
				"MED_1_$rcode[$i]", 
				"MED_2_$rcode[$i]", 
				"MED_3_$rcode[$i]",
				"MED_PCS_$rcode[$i]", 
				"MED_$rcode[$i]", 
				"SML_1_$rcode[$i]", 
				"SML_2_$rcode[$i]", 
				"SML_3_$rcode[$i]",
				"SML_PCS_$rcode[$i]", 
				"SML_$rcode[$i]", 
				"PUL_1_$rcode[$i]", 
				"PUL_2_$rcode[$i]", 
				"PUL_3_$rcode[$i]",
				"PUL_PCS_$rcode[$i]", 
				"PUL_$rcode[$i]", 
				"PWE_1_$rcode[$i]", 
				"PWE_2_$rcode[$i]", 
				"PWE_3_$rcode[$i]",
				"PWE_PCS_$rcode[$i]", 
				"PWE_$rcode[$i]", 
				"SPW_1_$rcode[$i]", 
				"SPW_2_$rcode[$i]", 
				"SPW_3_$rcode[$i]",
				"SPW_PCS_$rcode[$i]", 
				"SPW_$rcode[$i]", 
				"B1_$rcode[$i]", 
				"B2_$rcode[$i]", 
				"B3_$rcode[$i]", 
				"M_Dirty_$rcode[$i]", 
				"B_Dirty_$rcode[$i]", 
				"Dirty_$rcode[$i]", 
				"Total_$rcode[$i]", 
				"A_W_$rcode[$i]", 
				"Production_$rcode[$i]", 
				"Variance_$rcode[$i]", 
				"Dev_$rcode[$i]", 
				"ProductionDate", 
				"id_$rcode[$i]"
			];
            
            $data = getDataFromPost($keys, $_POST);  
            $originalData = fetchOriginalData($conn, $data["id_$rcode[$i]"]);
			
			if (hasChanges($originalData, $data)) 
			{
				if ($dbTable === "egg_weight")
				{
					$result = executeQuery($conn, "SELECT * FROM egg_weight WHERE id = ? AND is_current = TRUE", "s", [$data["id_$rcode[$i]"]]);
					
					if ($result === false) { 
						throw new Exception("Error executing query: " . $conn->error);
					} 
					
					if ($result->num_rows > 0) {
						$currentRecord = $result->fetch_assoc();
						$id = $currentRecord["id"];
						$currentVersion = $currentRecord["version"];
						
						// Mark the current version as outdated
						$updateOldVersionQuery = "UPDATE egg_weight SET is_current = FALSE WHERE id = ? AND is_current = TRUE";
						$updateOldResult = executeQuery($conn, $updateOldVersionQuery, "i", [$id]);
						
						if ($updateOldResult === false) { 
							throw new Exception("Error executing query: " . $conn->error);
						} 
						
						$current_ProductionDate = $currentRecord["ProductionDate"];
						
						// Insert the new version
						$newVersion = $currentVersion + 1;
						$insertNewVersionQuery = "INSERT INTO egg_weight (addedby_user,ProductionDate,BatchName,BatchCode,AgeInWeeks,
						JMB_1,JMB_2,JMB_3,JMB_PCS,JMB,
						XLR_1,XLR_2,XLR_3,XLR_PCS,XLR,
						LRG_1,LRG_2,LRG_3,LRG_PCS,LRG,
						MED_1,MED_2,MED_3,MED_PCS,MED,
						SML_1,SML_2,SML_3,SML_PCS,SML,
						PUL_1,PUL_2,PUL_3,PUL_PCS,PUL,
						PWE_1,PWE_2,PWE_3,PWE_PCS,PWE,
						SPW_1,SPW_2,SPW_3,SPW_PCS,SPW,
						B1,B2,B3,M_Dirty,B_Dirty,Dirty,Total,A_W,Production,Variance,Dev,
						version,is_current) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, TRUE)";
						$updateResult = executeQuery($conn, $insertNewVersionQuery, "sssssssssssssssssssssssssssssssssssssssssssssssssssssssss", [
							$userName,
							$current_ProductionDate,
							$data["BatchName_$rcode[$i]"], 
							$data["BatchCode_$rcode[$i]"], 
							$data["AgeInWeeks_$rcode[$i]"], 
							$data["JMB_1_$rcode[$i]"], 
							$data["JMB_2_$rcode[$i]"], 
							$data["JMB_3_$rcode[$i]"], 
							$data["JMB_PCS_$rcode[$i]"], 
							$data["JMB_$rcode[$i]"], 
							$data["XLR_1_$rcode[$i]"], 
							$data["XLR_2_$rcode[$i]"], 
							$data["XLR_3_$rcode[$i]"], 
							$data["XLR_PCS_$rcode[$i]"], 
							$data["XLR_$rcode[$i]"], 
							$data["LRG_1_$rcode[$i]"], 
							$data["LRG_2_$rcode[$i]"], 
							$data["LRG_3_$rcode[$i]"], 
							$data["LRG_PCS_$rcode[$i]"], 
							$data["LRG_$rcode[$i]"], 
							$data["MED_1_$rcode[$i]"], 
							$data["MED_2_$rcode[$i]"], 
							$data["MED_3_$rcode[$i]"], 
							$data["MED_PCS_$rcode[$i]"], 
							$data["MED_$rcode[$i]"], 
							$data["SML_1_$rcode[$i]"], 
							$data["SML_2_$rcode[$i]"], 
							$data["SML_3_$rcode[$i]"], 
							$data["SML_PCS_$rcode[$i]"], 
							$data["SML_$rcode[$i]"], 
							$data["PUL_1_$rcode[$i]"], 
							$data["PUL_2_$rcode[$i]"], 
							$data["PUL_3_$rcode[$i]"], 
							$data["PUL_PCS_$rcode[$i]"], 
							$data["PUL_$rcode[$i]"], 
							$data["PWE_1_$rcode[$i]"], 
							$data["PWE_2_$rcode[$i]"], 
							$data["PWE_3_$rcode[$i]"], 
							$data["PWE_PCS_$rcode[$i]"], 
							$data["PWE_$rcode[$i]"], 
							$data["SPW_1_$rcode[$i]"], 
							$data["SPW_2_$rcode[$i]"], 
							$data["SPW_3_$rcode[$i]"], 
							$data["SPW_PCS_$rcode[$i]"], 
							$data["SPW_$rcode[$i]"], 
							$data["B1_$rcode[$i]"], 
							$data["B2_$rcode[$i]"], 
							$data["B3_$rcode[$i]"], 
							$data["M_Dirty_$rcode[$i]"], 
							$data["B_Dirty_$rcode[$i]"], 
							$data["Dirty_$rcode[$i]"], 
							$data["Total_$rcode[$i]"], 
							$data["A_W_$rcode[$i]"], 
							$data["Production_$rcode[$i]"], 
							$data["Variance_$rcode[$i]"], 
							$data["Dev_$rcode[$i]"], 
							$newVersion
						]);
					
						if ($updateResult === false) { 
							throw new Exception("Error executing query: " . $conn->error);
						} else {
							$updateSuccess = true;
						}
					}					
				}
				else
				{
					$query = "UPDATE predata_ew SET addedby_user=?,BatchName=?,BatchCode=?,AgeInWeeks=?,
					JMB_1=?,JMB_2=?,JMB_3=?,JMB_PCS=?,JMB=?,
					XLR_1=?,XLR_2=?,XLR_3=?,XLR_PCS=?,XLR=?,
					LRG_1=?,LRG_2=?,LRG_3=?,LRG_PCS=?,LRG=?,
					MED_1=?,MED_2=?,MED_3=?,MED_PCS=?,MED=?,
					SML_1=?,SML_2=?,SML_3=?,SML_PCS=?,SML=?,
					PUL_1=?,PUL_2=?,PUL_3=?,PUL_PCS=?,PUL=?,
					PWE_1=?,PWE_2=?,PWE_3=?,PWE_PCS=?,PWE=?,
					SPW_1=?,SPW_2=?,SPW_3=?,SPW_PCS=?,SPW=?,
					B1=?,B2=?,B3=?,M_Dirty=?,B_Dirty=?,Dirty=?,Total=?,A_W=?,Production=?,Variance=?,Dev=? WHERE ProductionDate=? AND id=?";
					$result = executeQuery($conn, $query, "sssssssssssssssssssssssssssssssssssssssssssssssssssssssss", [
						$userName, 
						$data["BatchName_$rcode[$i]"], 
						$data["BatchCode_$rcode[$i]"], 
						$data["AgeInWeeks_$rcode[$i]"], 
						$data["JMB_1_$rcode[$i]"], 
						$data["JMB_2_$rcode[$i]"], 
						$data["JMB_3_$rcode[$i]"], 
						$data["JMB_PCS_$rcode[$i]"], 
						$data["JMB_$rcode[$i]"], 
						$data["XLR_1_$rcode[$i]"], 
						$data["XLR_2_$rcode[$i]"], 
						$data["XLR_3_$rcode[$i]"], 
						$data["XLR_PCS_$rcode[$i]"], 
						$data["XLR_$rcode[$i]"], 
						$data["LRG_1_$rcode[$i]"], 
						$data["LRG_2_$rcode[$i]"], 
						$data["LRG_3_$rcode[$i]"], 
						$data["LRG_PCS_$rcode[$i]"], 
						$data["LRG_$rcode[$i]"], 
						$data["MED_1_$rcode[$i]"], 
						$data["MED_2_$rcode[$i]"], 
						$data["MED_3_$rcode[$i]"], 
						$data["MED_PCS_$rcode[$i]"], 
						$data["MED_$rcode[$i]"], 
						$data["SML_1_$rcode[$i]"], 
						$data["SML_2_$rcode[$i]"], 
						$data["SML_3_$rcode[$i]"], 
						$data["SML_PCS_$rcode[$i]"], 
						$data["SML_$rcode[$i]"], 
						$data["PUL_1_$rcode[$i]"], 
						$data["PUL_2_$rcode[$i]"], 
						$data["PUL_3_$rcode[$i]"], 
						$data["PUL_PCS_$rcode[$i]"], 
						$data["PUL_$rcode[$i]"], 
						$data["PWE_1_$rcode[$i]"], 
						$data["PWE_2_$rcode[$i]"], 
						$data["PWE_3_$rcode[$i]"], 
						$data["PWE_PCS_$rcode[$i]"], 
						$data["PWE_$rcode[$i]"], 
						$data["SPW_1_$rcode[$i]"], 
						$data["SPW_2_$rcode[$i]"], 
						$data["SPW_3_$rcode[$i]"], 
						$data["SPW_PCS_$rcode[$i]"], 
						$data["SPW_$rcode[$i]"], 
						$data["B1_$rcode[$i]"], 
						$data["B2_$rcode[$i]"], 
						$data["B3_$rcode[$i]"], 
						$data["M_Dirty_$rcode[$i]"], 
						$data["B_Dirty_$rcode[$i]"], 
						$data["Dirty_$rcode[$i]"], 
						$data["Total_$rcode[$i]"], 
						$data["A_W_$rcode[$i]"], 
						$data["Production_$rcode[$i]"], 
						$data["Variance_$rcode[$i]"], 
						$data["Dev_$rcode[$i]"], 
						$ProductionDate, 
						$data["id_$rcode[$i]"]
					]);    
						
					if ($result === false) { 
						throw new Exception("Error executing query: " . $conn->error);
					} else {
						$updateSuccess = true;
					}
				}
			}
        }
        mysqli_commit($conn);
        
        if ($updateSuccess) 
        {
            $_SESSION["update_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();
    }
}
elseif (isset($_POST["SaveButton"]) && isset($_GET["p"]) && $_GET["p"] === "ipfd") 
{
    try
    {
        for ($i = 0; $i < count($rcode); $i++) 
        {
			$keys = [
				"BatchName_$rcode[$i]", 
				"BldgNo_$rcode[$i]", 
				"FCode_$rcode[$i]", 
				"AgeInWeeks_$rcode[$i]",
				"begin_inventory_$rcode[$i]",
				"delivery_$rcode[$i]",
				"converted_delivery_$rcode[$i]",
				"end_delivery_sack_$rcode[$i]",
				"end_delivery_kilo_$rcode[$i]",
				"end_delivery_$rcode[$i]",
				"Consumption_KG_$rcode[$i]",
				"Consumption_GRAMS_$rcode[$i]",
				"ProductionDate", 
				"id_$rcode[$i]"
			];
			
			$data = getDataFromPost($keys, $_POST); 
			$originalData = fetchOriginalData($conn, $data["id_$rcode[$i]"]);
			
			if (hasChanges($originalData, $data)) 
			{
				if ($dbTable === "feed_delivery")
				{
					$result = executeQuery($conn, "SELECT * FROM feed_delivery WHERE id = ? AND is_current = TRUE", "s", [$data["id_$rcode[$i]"]]);
					
					if ($result === false) { 
						throw new Exception("Error executing query: " . $conn->error);
					} 
					
					if ($result->num_rows > 0) {
						$currentRecord = $result->fetch_assoc();
						$id = $currentRecord["id"];
						$currentVersion = $currentRecord["version"];
						
						// Mark the current version as outdated
						$updateOldVersionQuery = "UPDATE feed_delivery SET is_current = FALSE WHERE id = ? AND is_current = TRUE";
						$updateOldResult = executeQuery($conn, $updateOldVersionQuery, "i", [$id]);
						
						if ($updateOldResult === false) { 
							throw new Exception("Error executing query: " . $conn->error);
						} 
						
						$current_ProductionDate = $currentRecord["ProductionDate"];
						
						// Insert the new version
						$newVersion = $currentVersion + 1;
						$insertNewVersionQuery = "INSERT INTO feed_delivery (addedby_user,ProductionDate,BatchName,BldgNo,AgeInWeeks,FCode,begin_inventory,delivery,converted_delivery,end_delivery_sack,end_delivery_kilo,end_delivery,Consumption_KG,Consumption_GRAMS,version,is_current) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, TRUE)";
						$updateResult = executeQuery($conn, $insertNewVersionQuery, "ssssisiiiiiiiii", [$userName, $current_ProductionDate, $data["BatchName_$rcode[$i]"], $data["BldgNo_$rcode[$i]"], $data["AgeInWeeks_$rcode[$i]"], $data["FCode_$rcode[$i]"], $data["begin_inventory_$rcode[$i]"], $data["delivery_$rcode[$i]"], $data["converted_delivery_$rcode[$i]"], $data["end_delivery_sack_$rcode[$i]"], $data["end_delivery_kilo_$rcode[$i]"], $data["end_delivery_$rcode[$i]"], $data["Consumption_KG_$rcode[$i]"], $data["Consumption_GRAMS_$rcode[$i]"], $newVersion]);
					
						if ($updateResult === false) { 
							throw new Exception("Error executing query: " . $conn->error);
						} else {
							$updateSuccess = true;
						}
					}
				}
				else
				{	
					$query = "UPDATE predata_fd SET addedby_user=?,BatchName=?,BldgNo=?,AgeInWeeks=?,FCode=?,begin_inventory=?,delivery=?,converted_delivery=?,end_delivery_sack=?,end_delivery_kilo=?,end_delivery=?,Consumption_KG=?,Consumption_GRAMS=? WHERE ProductionDate=? AND id=?";
					$result = executeQuery($conn, $query, "sssisiiiiiiiisi", [$userName, $data["BatchName_$rcode[$i]"], $data["BldgNo_$rcode[$i]"], $data["AgeInWeeks_$rcode[$i]"], $data["FCode_$rcode[$i]"], $data["begin_inventory_$rcode[$i]"], $data["delivery_$rcode[$i]"], $data["converted_delivery_$rcode[$i]"], $data["end_delivery_sack_$rcode[$i]"], $data["end_delivery_kilo_$rcode[$i]"], $data["end_delivery_$rcode[$i]"], $data["Consumption_KG_$rcode[$i]"], $data["Consumption_GRAMS_$rcode[$i]"], $ProductionDate, $data["id_$rcode[$i]"]]);
				
					if ($result === false) { 
						throw new Exception("Error executing query: " . $conn->error);
					} else {
						$updateSuccess = true;
					}
				}
			}
        }
        mysqli_commit($conn);
        
        if ($updateSuccess) 
        {
            $_SESSION["update_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();
    }
} 
elseif (isset($_POST["SaveButton"]) && isset($_GET["p"]) && $_GET["p"] === "iptemp") 
{
    try
    {
        for ($i = 0; $i < count($rcode); $i++) 
        {
			$keys = [
				"entry_time_$rcode[$i]", 
				"temp_$rcode[$i]",
				"humidity_$rcode[$i]",
				"heat_index_$rcode[$i]",
				"ProductionDate",
				"id_$rcode[$i]"
			];
			
			$data = getDataFromPost($keys, $_POST); 
			$originalData = fetchOriginalData($conn, $data["id_$rcode[$i]"]);

			if (hasChanges($originalData, $data)) 
			{
				if ($dbTable === "input_temp")
				{
					$result = executeQuery($conn, "SELECT * FROM input_temp WHERE id = ? AND is_current = TRUE", "s", [$data["id_$rcode[$i]"]]);
					
					if ($result === false) { 
						throw new Exception("Error executing query: " . $conn->error);
					} 
					
					if ($result->num_rows > 0) {
						$currentRecord = $result->fetch_assoc();
						$id = $currentRecord["id"];
						$currentVersion = $currentRecord["version"];
						
						// Mark the current version as outdated
						$updateOldVersionQuery = "UPDATE input_temp SET is_current = FALSE WHERE id = ? AND is_current = TRUE";
						$updateOldResult = executeQuery($conn, $updateOldVersionQuery, "i", [$id]);
						
						if ($updateOldResult === false) { 
							throw new Exception("Error executing query: " . $conn->error);
						} 
						
						$current_ProductionDate = $currentRecord["ProductionDate"];
						
						// Insert the new version
						$newVersion = $currentVersion + 1;
						$insertNewVersionQuery = "INSERT INTO input_temp (addedby_user,ProductionDate,entry_time,temp,humidity,heat_index,version,is_current) VALUES (?, ?, ?, ?, ?, ?, ?, TRUE)";
						$updateResult = executeQuery($conn, $insertNewVersionQuery, "ssssssi", [$userName, $current_ProductionDate, $data["entry_time_$rcode[$i]"], $data["temp_$rcode[$i]"], $data["humidity_$rcode[$i]"], $data["heat_index_$rcode[$i]"], $newVersion]);
					
						if ($updateResult === false) { 
							throw new Exception("Error executing query: " . $conn->error);
						} else {
							$updateSuccess = true;
						}
					}
				}
				else
				{	
					$query = "UPDATE predata_temp SET addedby_user=?,entry_time=?,temp=?,humidity=?,heat_index=? WHERE ProductionDate=? AND id=?";
					$result = executeQuery($conn, $query, "ssssssi", [$userName, $data["entry_time_$rcode[$i]"], $data["temp_$rcode[$i]"], $data["humidity_$rcode[$i]"], $data["heat_index_$rcode[$i]"], $ProductionDate, $data["id_$rcode[$i]"]]);
				
					if ($result === false) { 
						throw new Exception("Error executing query: " . $conn->error);
					} else {
						$updateSuccess = true;
					}
				}
			}
        }
        mysqli_commit($conn);
        
        if ($updateSuccess) 
        {
            $_SESSION["update_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();
    }
} 
elseif (isset($_POST["SaveButton"]) && isset($_GET["p"]) && $_GET["p"] === "es") 
{
    try
    {
        for ($i = 0; $i < count($rcode); $i++) 
        {
			$keys = [
				"BreedType_$rcode[$i]", 
				"AgeInWeeks_$rcode[$i]", 
				"Stnd_H_D_per_$rcode[$i]", 
				"Stnd_H_H_per_$rcode[$i]", 
				"EggWeight_g_$rcode[$i]", 
				"EggWeight_Weeks_$rcode[$i]", 
				"EggWeight_Cum_$rcode[$i]", 
				"EggMass_Weeks_$rcode[$i]", 
				"EggMass_Cum_$rcode[$i]",
				"id_$rcode[$i]"
			];
			
            $data = getDataFromPost($keys, $_POST); 
            $originalData = fetchOriginalData($conn, $data["id_$rcode[$i]"]);

            if (hasChanges($originalData, $data)) 
			{
				$query = "UPDATE egg_standards SET addedby_user=?,BreedType=?,AgeInWeeks=?,Stnd_H_D_per=?,Stnd_H_H_per=?,EggWeight_g=?,EggWeight_Weeks=?,EggWeight_Cum=?,EggMass_Weeks=?,EggMass_Cum=? WHERE id = ?";
                $result = executeQuery($conn, $query, "ssssssssssi", [$userName, $data["BreedType_$rcode[$i]"], $data["AgeInWeeks_$rcode[$i]"], $data["Stnd_H_D_per_$rcode[$i]"], $data["Stnd_H_H_per_$rcode[$i]"], $data["EggWeight_g_$rcode[$i]"], $data["EggWeight_Weeks_$rcode[$i]"], $data["EggWeight_Cum_$rcode[$i]"], $data["EggMass_Weeks_$rcode[$i]"], $data["EggMass_Cum_$rcode[$i]"], $data["id_$rcode[$i]"]]);
                
				if ($result === false) { 
					throw new Exception("Error executing query: " . $conn->error);
				}  else {
                    $updateSuccess = true;
                }
            }
        }
        mysqli_commit($conn);
        
        if ($updateSuccess) 
        {
            $_SESSION["update_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["update_success"])) 
{
	if ($userType !== 2 && $_GET["p"] === "ipep") {
    ?>
    <script>
        $( ".dispMessage" ).append( "<div class='alert alert-primary d-flex align-items-center shadow' role='alert'><h4>Changes saved successfully. Please click the refresh button</h4></div>" );
    </script>
    <?php
	} else {
    ?>
    <script>
        $( ".dispMessage" ).append( "<div class='alert alert-primary d-flex align-items-center shadow' role='alert'><h4>Saved!</h4></div>" );
    </script>
    <?php
	}
    unset($_SESSION["update_success"]);
}
?>