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

$ProductionDate = isset($_SESSION["ProductionDate"]) ? $_SESSION["ProductionDate"] : date("Y-m-d");
$PreviousDay = date("Y-m-d", strtotime($ProductionDate . " -1 day"));
mysqli_begin_transaction($conn);

if (isset($_POST["InsertButton"]) && isset($_GET["p"]) && $_GET["p"] === "ipep") {
    $checkEPQuery = "SELECT COUNT(*) FROM input_production WHERE ProductionDate = ?";
    $checkEPResult = executeQuery($conn, $checkEPQuery, "s", [$PreviousDay]);
	
	if ($checkEPResult === false) { 
		throw new Exception("Error executing query: " . $conn->error);
	} 
	
	$checkEPCount = mysqli_fetch_row($checkEPResult)[0];

    if ($checkEPCount == 0) {
		?>
		<script>
			alert( "No INPUT from the previous day. Please upload yesterday\'s INPUT first." );
		</script>
		<?php
    } else {
        try {
            $insertQuery = "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)
                         SELECT 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
                         FROM predata_ip WHERE addedby_user = ? AND ProductionDate = ? AND is_deleted = FALSE";
            $insertResult = executeQuery($conn, $insertQuery, "ss", [$userName, $ProductionDate]);
			
			if ($insertResult === false) { 
				throw new Exception("Error executing query: " . $conn->error);
			} else {
                $deleteQuery = "DELETE FROM predata_ip WHERE addedby_user = ? AND ProductionDate = ? AND is_deleted = FALSE";
                $deleteResult = executeQuery($conn, $deleteQuery, "ss", [$userName, $ProductionDate]);
				
				if ($deleteResult === false) { 
					throw new Exception("Error executing query: " . $conn->error);
				} 
                
				mysqli_commit($conn);
				
                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["InsertButton"]) && isset($_GET["p"]) && $_GET["p"] === "ipes") {
	$checkESQuery = "SELECT COUNT(*) FROM egg_weight WHERE ProductionDate = ?";
	$checkESResult = executeQuery($conn, $checkESQuery, "s", [$PreviousDay]);
	
	if ($checkESResult === false) { 
		throw new Exception("Error executing query: " . $conn->error);
	} 
	
	$checkESCount = mysqli_fetch_row($checkESResult)[0];

	if ($checkESCount == 0) {
		?>
		<script>
			alert( "No INPUT from the previous day. Please upload yesterday\'s INPUT first." );
		</script>
		<?php
	} else {
		try {
			$insertQuery = "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
			) 
			SELECT 
				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 
			FROM predata_ew 
			WHERE addedby_user = ? AND ProductionDate = ? AND is_deleted = FALSE";
			$insertResult = executeQuery($conn, $insertQuery, "ss", [$userName,$ProductionDate]);
		
			if ($insertResult === false) { 
				throw new Exception("Error executing query: " . $conn->error);
			} else {
				$deleteQuery = "DELETE FROM predata_ew WHERE addedby_user = ? AND ProductionDate = ? AND is_deleted = FALSE";
				$deleteResult = executeQuery($conn, $deleteQuery, "ss", [$userName,$ProductionDate]);
				
				if ($deleteResult === false) { 
					throw new Exception("Error executing query: " . $conn->error);
				} 
				
				mysqli_commit($conn);
			
				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["InsertButton"]) && isset($_GET["p"]) && $_GET["p"] === "ipfd") {
	$checkFDQuery = "SELECT COUNT(*) FROM feed_delivery WHERE ProductionDate = ?";
	$checkFDResult = executeQuery($conn, $checkFDQuery, "s", [$PreviousDay]);
	$checkFDCount = mysqli_fetch_row($checkFDResult)[0];

	if ($checkFDCount == 0) {
		?>
		<script>
			alert( "No INPUT from the previous day. Please upload yesterday\'s INPUT first." );
		</script>
		<?php
	} else {
		try {
			$insertQuery = "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
			) 
			SELECT 
				addedby_user, 
				ProductionDate, 
				BatchName, 
				BldgNo, 
				AgeInWeeks,
				FCode, 
				begin_inventory,
				delivery,
				converted_delivery,
				end_delivery_sack,
				end_delivery_kilo,
				end_delivery,
				Consumption_KG,
				Consumption_GRAMS
			FROM predata_fd
			WHERE addedby_user = ? AND ProductionDate = ? AND is_deleted = FALSE";
			$insertResult = executeQuery($conn, $insertQuery, "ss", [$userName,$ProductionDate]);
			
			if ($insertResult === false) { 
				throw new Exception("Error executing query: " . $conn->error);
			} else {
				$deleteQuery = "DELETE FROM predata_fd WHERE addedby_user = ? AND ProductionDate = ? AND is_deleted = FALSE";
				$deleteResult = executeQuery($conn, $deleteQuery, "ss", [$userName,$ProductionDate]);
				
				if ($deleteResult === false) { 
					throw new Exception("Error executing query: " . $conn->error);
				} 
				
				mysqli_commit($conn);
			
				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["InsertButton"]) && isset($_GET["p"]) && $_GET["p"] === "iptemp") {
	$checkFDQuery = "SELECT COUNT(*) FROM input_temp WHERE ProductionDate = ?";
	$checkFDResult = executeQuery($conn, $checkFDQuery, "s", [$PreviousDay]);
	$checkFDCount = mysqli_fetch_row($checkFDResult)[0];

	if ($checkFDCount == 0) {
		?>
		<script>
			alert( "No INPUT from the previous day. Please upload yesterday\'s INPUT first." );
		</script>
		<?php
	} else {
		try {
			$insertQuery = "INSERT INTO input_temp (
				addedby_user, 
				ProductionDate, 
				entry_time, 
				temp,
				humidity, 
				heat_index
			) 
			SELECT 
				addedby_user, 
				ProductionDate, 
				entry_time, 
				temp,
				humidity, 
				heat_index
			FROM predata_temp
			WHERE addedby_user = ? AND ProductionDate = ? AND is_deleted = FALSE";
			$insertResult = executeQuery($conn, $insertQuery, "ss", [$userName,$ProductionDate]);
			
			if ($insertResult === false) { 
				throw new Exception("Error executing query: " . $conn->error);
			} else {
				$deleteQuery = "DELETE FROM predata_temp WHERE addedby_user = ? AND ProductionDate = ? AND is_deleted = FALSE";
				$deleteResult = executeQuery($conn, $deleteQuery, "ss", [$userName,$ProductionDate]);
				
				if ($deleteResult === false) { 
					throw new Exception("Error executing query: " . $conn->error);
				} 
				
				mysqli_commit($conn);
			
				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();
		}
	}
}
?>