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

$ProductionDate = isset($_SESSION["ProductionDate"]) ? $_SESSION["ProductionDate"] : date("Y-m-d");
$headers = [
	"BatchName", 
	"id", 
	"Bldg. No.", 
	"AgeInWeeks", 
	"F.Code", 
	"Begin<BR>Inventory Kilo", 
	"Delivery<BR>Sack", 
	"Converted_Delivery", 
	"End Delivery<BR>Sack", 
	"End Delivery<BR>Kilo", 
	"End Delivery", 
	"Consumption<BR>/KG", 
	"Consumption<BR>/G"
];
$inputNames = [
	"BatchName", 
	"id", 
	"BldgNo", 
	"AgeInWeeks", 
	"FCode", 
	"begin_inventory", 
	"delivery", 
	"converted_delivery", 
	"end_delivery_sack", 
	"end_delivery_kilo", 
	"end_delivery", 
	"Consumption_KG", 
	"Consumption_GRAMS"
];
$dbTable = (isset($userType) && !empty($userType) && $userType === 2 || isset($superUser) && !empty($superUser)) ? "predata_fd" : "feed_delivery";

$result = executeQuery($conn, "SELECT * FROM {$dbTable} WHERE ProductionDate = ? AND is_deleted = FALSE AND is_current = TRUE ORDER BY AgeInWeeks DESC", "s", [$ProductionDate]);

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

$existingPOSTQuery = "SELECT COUNT(*) FROM feed_delivery WHERE ProductionDate = ? AND is_deleted = FALSE AND is_current = TRUE";
$existingPOSTResult = executeQuery($conn, $existingPOSTQuery, "s", [$ProductionDate]);

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

$existingPOSTCount = mysqli_fetch_row($existingPOSTResult)[0];

if (
($existingPOSTCount == 0 && (isset($userType) && !empty($userType) && $userType === 2))
||
($existingPOSTCount > 0 && (isset($userType) && !empty($userType) && ($userType === 1 || $userType === 3)))
) {
	echo "<table id='MyTable_ipfd' class='ui display ipfd' style='display: none;'>";
	echo "<thead><tr>";
	
	foreach ($headers as $index => $headerText) 
	{
		if ($userType === 3) 
		{
			echo "<th class='bg-light text-uppercase align-baseline'>{$headerText}({$index})</th>";
		}
		else
		{
			echo "<th class='bg-light text-uppercase align-baseline'>{$headerText}</th>";
		}	
	}
	echo "</tr></thead><tbody>";
	
	$number = [6,8,9];
	$disabled_number = [1,2,3,5,7,10,11,12];
	
	while ($row = mysqli_fetch_assoc($result)) 
	{
		echo "<tr>";
		
		foreach ($inputNames as $input_index => $inputName) 
		{
			if ($input_index == 0) 
			{
				if (!isset($superUser) && $userType === 2) 
				{
					echo "<td style='display: flex; align-items: center;'><input type='text' class='form-control fw-bold' name='{$inputName}_{$row["id"]}' value='" . $row[$inputName] . "' readonly></td>";
				}
				else 
				{
					echo "<td style='display: flex; align-items: center;'><button type='button' class='btn btn-light text-danger btn-wo-border shadow-sm fs-4 d-flex align-items-center justify-content-center ip-clickable" . (isset($superUser) || $userType !== 2 ? "" : " hidden") . "' data-id='". $row['id'] . "' data-table='{$dbTable}' title='Delete'><i class='lni lni-minus-circle'></i></button><input type='text' class='form-control fw-bold' name='{$inputName}_{$row["id"]}' value='" . $row[$inputName] . "'></td>";
				}
			}
			elseif (in_array($input_index, $disabled_number)) 
			{
				if ($input_index == 2 && isset($superUser) || $userType !== 2) 
				{
					echo "<td><input type='text' class='form-control' data-type='{$inputName}' name='{$inputName}_{$row["id"]}' value='" . ($row[$inputName] == 0 ? '' : $row[$inputName]) . "'></td>";
				}
				else 
				{
					echo "<td><input type='text' class='form-control inputDisabled' data-type='{$inputName}' name='{$inputName}_{$row["id"]}' value='" . ($row[$inputName] == 0 ? '' : $row[$inputName]) . "' readonly></td>";
				}
			}
			elseif (in_array($input_index, $number))
			{
				echo "<td><input type='text' class='form-control calculateGroup3' data-type='{$inputName}' name='{$inputName}_{$row["id"]}' value='" . ($row[$inputName] == 0 ? '' : $row[$inputName]) . "' pattern='[0-9]+(\.[0-9]+)?' title='Please enter a valid number' autocomplete='off'></td>";
			}
			else 
			{
				echo "<td><input type='text' class='form-control' name='{$inputName}_{$row["id"]}' value='" . $row[$inputName] . "'></td>";
			}
		}
		echo "</tr>";
	}
	echo "</tbody></table>";
}
else
{
	if ($existingPOSTCount == 0 && (isset($userType) && !empty($userType) && ($userType === 1 || $userType === 3)))
	{
		?>
		<script>
			var saveButton = document.querySelector("button[name='SaveButton']");
			var newRowButton = document.querySelector("button[name='NewRowButton']");
			
			if (saveButton) saveButton.disabled = true;
			if (newRowButton) newRowButton.disabled = true;
		</script>
		<?php
		echo "<div class='alert alert-primary d-flex align-items-center shadow' role='alert'><svg class='bi flex-shrink-0 me-2' role='img' aria-label='Info:'><use xlink:href='#exclamation-triangle-fill'/></svg><div><h4>Today’s report has not yet been posted. You may change the Production Date to view another report.</h4></div></div>";
	}
	else
	{
		?>
		<script>
			var saveButton = document.querySelector("button[name='SaveButton']");
			var newRowButton = document.querySelector("button[name='NewRowButton']");
			var insertButton = document.querySelector("button[name='InsertButton']");

			if (saveButton) saveButton.disabled = true;
			if (newRowButton) newRowButton.disabled = true;
			if (insertButton) insertButton.disabled = true;
		</script>
		<?php
		echo "<div class='alert alert-primary d-flex align-items-center shadow' role='alert'><svg class='bi flex-shrink-0 me-2' role='img' aria-label='Info:'><use xlink:href='#exclamation-triangle-fill'/></svg><div><h4>Today’s report has already been posted. To update or delete a report, please log in again with admin access.</h4></div></div>";
	}
}
?>