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

$BatchName = isset($_POST["BatchName"]) ? $_POST["BatchName"] : null;
$ProductionDate = isset($_POST["ProductionDate"]) ? $_POST["ProductionDate"] : date("Y-m-d");
$Total = isset($_POST["Total"]) ? $_POST["Total"] : 0;

$response = array(); 

$result = executeQuery($conn, "SELECT BatchCode FROM batch_details WHERE Status = 1 AND is_deleted = FALSE AND is_current = TRUE AND BatchName = ?", "s", [$BatchName]);

if ($result === false) { 
	throw new Exception("Error executing query: " . $conn->error);
} 

if ($result->num_rows > 0) 
{
	while($row = $result->fetch_assoc()) 
	{
		$response["BatchCode"] = $row["BatchCode"];
	}
} 
else 
{
	$response["BatchCode"] = "";
}

$result = executeQuery($conn, "SELECT FLOOR(DATEDIFF(?, CheckInDate) / 7) as AgeInWeeks FROM batch_details WHERE Status = 1 AND is_deleted = FALSE AND is_current = TRUE AND BatchName = ?", "ss", [$ProductionDate,$BatchName]);

if ($result === false) { 
	throw new Exception("Error executing query: " . $conn->error);
} 

if ($result->num_rows > 0) 
{
	while($row = $result->fetch_assoc()) 
	{
		if (empty($row["AgeInWeeks"]) || $row["AgeInWeeks"] == 0) 
		{
			$response["AgeInWeeks"] = 0;
		}
		else
		{
			$response["AgeInWeeks"] = number_format($row["AgeInWeeks"], 0);
		}		
	}
}
else
{
	$response["AgeInWeeks"] = 0;
}

$Production = 0;
$Variance = 0;
$Dev = 0;

$result = executeQuery($conn, "SELECT SUM(H_TOTAL) as HenDayTotal FROM input_production WHERE ProductionDate = ? AND BatchName = ? AND is_deleted = FALSE AND is_current = TRUE", "ss", [$ProductionDate,$BatchName]);

if ($result === false) { 
	throw new Exception("Error executing query: " . $conn->error);
} 

if ($result->num_rows > 0) 
{
	while($row = $result->fetch_assoc()) 
	{
		if (empty($row["HenDayTotal"]) || $row["HenDayTotal"] == 0) 
		{
			$Production = 0;
		}
		else
		{
			$Production = $row["HenDayTotal"];
		}
	}
}
else
{
	$Production = 0;
}

$Variance = $Production - $Total;

if ($Variance != 0 && $Production != 0) {
	$Dev = number_format(($Variance / $Production) * 100, 1);
}

$response["Production"] = $Production;
$response["Variance"] = $Variance;
$response["Dev"] = $Dev;

if (empty($response)) {
    echo json_encode(["status" => "error", "message" => "ipesQuery - An error occurred while processing your request."]);
} else {
    echo json_encode($response);
}
?>