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

$ProductionDate = isset($_SESSION["ProductionDate"]) ? $_SESSION["ProductionDate"] : date("Y-m-d");
$headers = [
	"Batch Name", 
	"id", 
	"Batch Code", 
	"Bldg. No.", 
	"Age In Weeks", 
	"Hen Day", 
	"8:30 AM", 
	"10:00 AM", 
	"11:45 AM", 
	"1:30 PM", 
	"3:00 PM", 
	"TRAYS", 
	"PCS", 
	"H-TOTAL", 
	"Mortality", 
	"Reject", 
	"Cull", 
	"Depletion", 
	"Adjustment", 
	"F. CODE"
];
$inputNames = [
	"BatchName", 
	"id", 
	"BatchCode", 
	"BldgNo", 
	"AgeInWeeks", 
	"Hen_Day", 
	"H1_T", 
	"H2_T", 
	"H3_T", 
	"H4_T", 
	"H5_T", 
	"H6_T", 
	"H6_PCS", 
	"H_TOTAL", 
	"Mortality", 
	"Reject", 
	"Cull", 
	"Depletion", 
	"Inv_Adj", 
	"F_CODE"
];
$dbTable = (isset($userType) && !empty($userType) && $userType === 2 || isset($superUser) && !empty($superUser)) ? "predata_ip" : "input_production";

$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 input_production 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_ipep' class='ui display ipep' style='display: none;'>";
	echo "<thead><tr>";
	
	foreach ($headers as $index => $headerText) 
	{
		if ($index >= 6 && $index <= 10) 
		{
			if ($userType === 3) 
			{
				echo "<th class='bg-light text-uppercase align-baseline'>{$headerText}({$index}) <BR>TRAYS</th>";
			} 
			else
			{
				echo "<th class='bg-light text-uppercase align-baseline'>{$headerText} <BR>TRAYS</th>";
			}
		}
		else if ($index == 11 || $index == 12) 
		{
			if ($userType === 3) 
			{
				echo "<th class='bg-light text-uppercase align-baseline'>4:45 PM <BR>{$headerText}({$index})</th>";
			}
			else
			{
				echo "<th class='bg-light text-uppercase align-baseline'>4:45 PM <BR>{$headerText}</th>";
			}
		}
		else
		{
			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>";
	
	$inputDisabled = [1,2,3,4,13,17];
	$calculateGroup1 = [6,7,8,9,10,11,12,13,14,15,16];
	$otherGroup = [18];
	
	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, $inputDisabled)) 
			{
				if ($input_index == 3 && isset($superUser) || $userType !== 2)
				{
					echo "<td><input type='text' class='form-control' name='{$inputName}_{$row["id"]}' value='" . $row[$inputName] . "'></td>";
				}
				elseif ($input_index == 13 || $input_index == 17) 
				{
					echo "<td><input type='text' class='form-control inputDisabled' name='{$inputName}_{$row["id"]}' value='" .($row[$inputName] == 0 ? '' : $row[$inputName]). "' readonly></td>";
				}
				else
				{
					echo "<td><input type='text' class='form-control inputDisabled' name='{$inputName}_{$row["id"]}' value='" . $row[$inputName]. "' readonly></td>";
				}
			}
			elseif ($input_index == 5) {
				echo "<td><input type='text' class='form-control inputDisabled' name='{$inputName}_{$row["id"]}' value='" . ($row[$inputName] == 0 ? '' : $row[$inputName]) . "' readonly></td>";
			} 
			elseif (in_array($input_index, $calculateGroup1)) 
			{
				echo "<td><input type='text' class='form-control calculateGroup1' name='{$inputName}_{$row["id"]}' value='" . ($row[$inputName] == 0 ? '' : $row[$inputName]) . "' pattern='[0-9]+(\.[0-9]+)?' title='Please enter a valid number' autocomplete='off'></td>";
			}
			elseif ($input_index == 18) {
				echo "<td><input type='number' class='form-control' name='{$inputName}_{$row["id"]}' value='" . ($row[$inputName] == 0 ? '' : $row[$inputName]) . "' min='-Infinity' autocomplete='off'></td>";
			}
			else
			{
				echo "<td><input type='text' class='form-control' name='{$inputName}_{$row["id"]}' value='" . $row[$inputName] . "'></td>";
			}
		}
		echo "</tr>";
	}
	echo "</tbody><tfoot class='print-footer'><tr>";
	echo "<td></td>
	<td></td>
	<td></td>
	<td></td>
	<td></td>
	<td></td>
	<td>0</td>
	<td>0</td>
	<td>0</td>
	<td>0</td>
	<td>0</td>
	<td>0</td>
	<td>0</td>
	<td>0</td>
	<td>0</td>
	<td>0</td>
	<td>0</td>
	<td>0</td>
	<td></td>
	<td></td>";
	echo "</tr></tfoot></table>";
}
else
{
	if ($existingPOSTCount == 0 && (isset($userType) && !empty($userType) && ($userType === 1 || $userType === 3)))
	{
		?>
		<script>
			var saveButton = document.querySelector("button[name='SaveButton']");
			var refreshButton = document.querySelector("button[name='RefreshButton']");
			var newRowButton = document.querySelector("button[name='NewRowButton']");
			
			if (saveButton) saveButton.disabled = true;
			if (refreshButton) refreshButton.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 refreshButton = document.querySelector("button[name='RefreshButton']");
			var newRowButton = document.querySelector("button[name='NewRowButton']");
			var insertButton = document.querySelector("button[name='InsertButton']");

			if (saveButton) saveButton.disabled = true;
			if (refreshButton) refreshButton.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>";
	}
}
?>