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

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

$response = array(); 

// First query to check data from the previous day
$previousDayResult = executeQuery($conn, "SELECT COUNT(*) as count FROM feed_delivery WHERE is_deleted = FALSE AND is_current = TRUE AND BatchName = ? AND BldgNo = ? AND ProductionDate = ? - INTERVAL 1 DAY", "sss", [$BatchName, $BldgNo, $ProductionDate]);

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

$row = $previousDayResult->fetch_assoc();
$count = $row["count"];

if ($count > 0) {
    $result = executeQuery($conn, "SELECT end_delivery as begin_inventory FROM feed_delivery WHERE is_deleted = FALSE AND is_current = TRUE AND BatchName = ? AND BldgNo = ? AND ProductionDate = DATE_SUB(?, INTERVAL 1 DAY)", "sss", [$BatchName, $BldgNo, $ProductionDate]);
} else {
    $result = executeQuery($conn, "SELECT begin_inventory FROM feed_delivery WHERE is_deleted = FALSE AND is_current = TRUE AND BatchName = ? AND BldgNo = ? ORDER BY ProductionDate ASC LIMIT 1", "ss", [$BatchName, $BldgNo]);
}

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

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

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