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

$insertSuccess = false;
$currentVersion = 1;

mysqli_begin_transaction($conn);

if (isset($_POST["bdInsertData"])) 
{
	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, "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,is_deleted,version,is_current) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, FALSE, ?, TRUE)", "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"],$currentVersion]);
		
		if ($result === false) { 
			throw new Exception("Error executing query: " . $conn->error);
		} else {
			$insertSuccess = true;
		}
	
		mysqli_commit($conn);
		
		if ($insertSuccess) 
		{
				$_SESSION["insertSuccess"] = 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["insertSuccess"])) 
{
    ?>
    <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["insertSuccess"]);
}
?>