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

$updateSuccess = false;

mysqli_begin_transaction($conn);

if (isset($_POST["bdUpdate"]) && isset($_POST["bd_id"]) && !empty($_POST["bd_id"])) {
	try {
		$keys = [
			"bd_BatchCode", 
			"bd_BatchName", 
			"bd_BldgNo",
			"bd_CheckInDate", 
			"bd_Breed", 
			"bd_HenHoused", 
			"bd_Prod_Previous",
			"bd_prev_JMB",
			"bd_prev_XLR",
			"bd_prev_LRG",
			"bd_prev_MED",
			"bd_prev_SML",
			"bd_prev_PUL",
			"bd_prev_PWE",
			"bd_prev_SPW",
			"bd_prev_B1",
			"bd_prev_B2",
			"bd_prev_B3",
			"bd_prev_M_Dirty",
			"bd_prev_B_Dirty",
			"bd_Status"
		];
		
		$data = getDataFromPost($keys, $_POST);	
		$BatchName_switch = isset($_POST["bd_BatchName_switch"]) ? 1 : 0;
		
		$result = executeQuery($conn, "SELECT * FROM batch_details WHERE id = ? AND is_current = TRUE", "s", [$_POST["bd_id"]]);
		
		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"];
			
            $updateOldVersionQuery = "UPDATE batch_details SET Status = FALSE, is_current = FALSE WHERE id = ? AND is_current = TRUE";
            $updateOldVersionResult = executeQuery($conn, $updateOldVersionQuery, "i", [$id]);
			
			if ($updateOldVersionResult === false) { 
				throw new Exception("Error executing query: " . $conn->error);
			}
			
            $newVersion = $currentVersion + 1;
			$insertNewVersionQuery = "INSERT INTO batch_details (addedby_user,BatchCode,BatchName,BatchName_switch,BldgNo,CheckInDate,Breed,HenHoused,Prod_Previous,prev_JMB,prev_XLR,prev_LRG,prev_MED,prev_SML,prev_PUL,prev_PWE,prev_SPW,prev_B1,prev_B2,prev_B3,prev_M_Dirty,prev_B_Dirty,Status,version,is_current) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, TRUE)";
            $updateResult = executeQuery($conn, $insertNewVersionQuery, "sssssssssssssssssssssssi", [$userName, $data["bd_BatchCode"], $data["bd_BatchName"], $BatchName_switch, $data["bd_BldgNo"], $data["bd_CheckInDate"], $data["bd_Breed"], $data["bd_HenHoused"], $data["bd_Prod_Previous"], $data["bd_prev_JMB"], $data["bd_prev_XLR"], $data["bd_prev_LRG"], $data["bd_prev_MED"], $data["bd_prev_SML"], $data["bd_prev_PUL"], $data["bd_prev_PWE"], $data["bd_prev_SPW"], $data["bd_prev_B1"], $data["bd_prev_B2"], $data["bd_prev_B3"], $data["bd_prev_M_Dirty"], $data["bd_prev_B_Dirty"], $data["bd_Status"], $newVersion]);
			
			if ($updateResult === false) { 
				throw new Exception("Error executing query: " . $conn->error);
			} else {
				$updateSuccess = true;
			}

			mysqli_commit($conn);

			if ($updateSuccess) {
				$_SESSION["updateSuccess"] = 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["updateSuccess"])) 
{
    ?>
    <script>
        $( ".dispMessage" ).append( "<div class='alert alert-primary d-flex align-items-center shadow' role='alert'><h4>Successfully Updated!</h4></div>" );
    </script>
    <?php
    unset($_SESSION["updateSuccess"]);
}
?>