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

$ProductionDate = isset($_SESSION["ProductionDate"]) ? $_SESSION["ProductionDate"] : date("Y-m-d");
$headers = [
	"Batch Name", 
	"id", 
	"Batch Code",
	"Age In Weeks", 
	"1:00 PM", 
	"4:00 PM", 
	"4:45 PM", 
	"JMB", 
	"JMB", 
	"1:00 PM", 
	"4:00 PM",
	"4:45 PM", 
	"XLR", 
	"XLR", 
	"1:00 PM", 
	"4:00 PM", 
	"4:45 PM", 
	"LRG", 
	"LRG", 
	"1:00 PM", 
	"4:00 PM", 
	"4:45 PM", 
	"MED", 
	"MED", 
	"1:00 PM", 
	"4:00 PM", 
	"4:45 PM", 
	"SML", 
	"SML", 
	"1:00 PM", 
	"4:00 PM", 
	"4:45 PM", 
	"PUL", 
	"PUL", 
	"1:00 PM", 
	"4:00 PM", 
	"4:45 PM", 
	"PWE", 
	"PWE", 
	"1:00 PM", 
	"4:00 PM", 
	"4:45 PM", 
	"SPW", 
	"SPW", 
	"B1<BR>PCS", 
	"B2<BR>PCS", 
	"B3<BR>PCS", 
	"M-Dirty<BR>PCS", 
	"B-Dirty<BR>PCS", 
	"Dirty", 
	"Total", 
	"A-W", 
	"Production", 
	"Variance", 
	"Dev %"
];
$inputNames = [
	"BatchName", 
	"id", 
	"BatchCode", 
	"AgeInWeeks", 
	"JMB_1", "JMB_2", "JMB_3", "JMB_PCS", "JMB", 
	"XLR_1", "XLR_2", "XLR_3", "XLR_PCS", "XLR", 
	"LRG_1", "LRG_2", "LRG_3", "LRG_PCS", "LRG", 
	"MED_1", "MED_2", "MED_3", "MED_PCS", "MED", 
	"SML_1", "SML_2", "SML_3", "SML_PCS", "SML", 
	"PUL_1", "PUL_2", "PUL_3", "PUL_PCS", "PUL", 
	"PWE_1", "PWE_2", "PWE_3", "PWE_PCS", "PWE", 
	"SPW_1", "SPW_2", "SPW_3", "SPW_PCS", "SPW", 
	"B1", 
	"B2", 
	"B3", 
	"M_Dirty", 
	"B_Dirty", 
	"Dirty",
	"Total", 
	"A_W", 
	"Production", 
	"Variance", 
	"Dev"
];

$dbTable = (isset($userType) && !empty($userType) && $userType === 2 || isset($superUser) && !empty($superUser)) ? "predata_ew" : "egg_weight";

$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 egg_weight 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];

$pcs = [7,12,17,22,27,32,37,42];
$trays = [4,5,6,9,10,11,14,15,16,19,20,21,24,25,26,29,30,31,34,35,36,39,40,41];
$total = [8,13,18,23,28,33,38,43];
$disabledIndices = [1,2,3,50,51,52,53,54];
$jmb = [4,5,6,7];
$xlr = [9,10,11,12];
$lrg = [14,15,16,17];
$med = [19,20,21,22];
$sml = [24,25,26,27];
$pul = [29,30,31,32];
$pwe = [34,35,36,37];
$spw = [39,40,41,42];
$group3 = [44,45,46,49];
$group3_4 = [8,13,18,23,28,33,38,43];
$group5 = [47,48];

$opacity = 0.8; //SET Opacity

if (
($existingPOSTCount == 0 && (isset($userType) && !empty($userType) && $userType === 2))
||
($existingPOSTCount > 0 && (isset($userType) && !empty($userType) && ($userType === 1 || $userType === 3)))
) {
	echo "<table id='MyTable_ipes' class='ui display ipes' style='display: none;'>";
	echo "<thead><tr>";
	
	foreach ($headers as $index => $headerText) 
	{
		if (in_array($index, $pcs)) {
			if ($userType === 3) 
			{
				echo "<th class='bg-dark text-white text-uppercase align-baseline' style='--bs-bg-opacity:{$opacity};'>4:45PM<BR>PCS({$index})</th>";
			}
			else
			{
				echo "<th class='bg-dark text-white text-uppercase align-baseline' style='--bs-bg-opacity:{$opacity};'>4:45PM<BR>PCS</th>";
			}
			//$opacity -= 0.1;
		}
		else if (in_array($index, $trays)) 
		{
			if ($userType === 3) 
			{
				echo "<th class='bg-secondary text-white text-uppercase align-baseline' style='--bs-bg-opacity:{$opacity};'>{$headerText}<BR>TRAYS({$index})</th>";
			}
			else
			{
				echo "<th class='bg-secondary text-white text-uppercase align-baseline' style='--bs-bg-opacity:{$opacity};'>{$headerText}<BR>TRAYS</th>";
			}
		}
		else if (in_array($index, $total)) 
		{
			if ($userType === 3) 
			{
				echo "<th class='bg-dark text-white text-uppercase align-baseline'>{$headerText}({$index})</th>";
			}
			else
			{
				echo "<th class='bg-dark text-white text-uppercase align-baseline'>{$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>";
	
	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>";
				}
			}
			else if (in_array($input_index, $pcs)) 
			{
				echo "<td><input type='text' class='form-control calculateGroup2' 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 if (in_array($input_index, $disabledIndices)) 
			{
				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]."'></td>";
				}
				else 
				{
					echo "<td><input type='text' class='form-control inputDisabled' data-type='{$inputName}' name='{$inputName}_{$row["id"]}' value='".$row[$inputName]."' readonly></td>";
				}
			}
			else if (in_array($input_index, $jmb)) 
			{
				echo "<td><input type='text' class='form-control calculateGroup2' data-type='JMB' 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 if (in_array($input_index, $xlr)) 
			{
				echo "<td><input type='text' class='form-control calculateGroup2' data-type='XLR' 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 if (in_array($input_index, $lrg)) 
			{
				echo "<td><input type='text' class='form-control calculateGroup2' data-type='LRG' 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 if (in_array($input_index, $med)) 
			{
				echo "<td><input type='text' class='form-control calculateGroup2' data-type='MED' 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 if (in_array($input_index, $sml)) 
			{
				echo "<td><input type='text' class='form-control calculateGroup2' data-type='SML' 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 if (in_array($input_index, $pul)) 
			{
				echo "<td><input type='text' class='form-control calculateGroup2' data-type='PUL' 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 if (in_array($input_index, $pwe)) 
			{
				echo "<td><input type='text' class='form-control calculateGroup2' data-type='PWE' 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 if (in_array($input_index, $spw)) 
			{
				echo "<td><input type='text' class='form-control calculateGroup2' data-type='SPW' 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 if (in_array($input_index, $group3)) 
			{
				if($input_index == 49) {
					echo "<td><input type='text' class='form-control calculateGroup2 inputDisabled' data-type='{$inputName}_total' name='{$inputName}_{$row["id"]}' value='".($row[$inputName] == 0 ? '' : $row[$inputName])."' readonly></td>";
				} else {
					echo "<td><input type='text' class='form-control calculateGroup2' 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 if (in_array($input_index, $group3_4)) 
			{
				echo "<td><input type='text' class='form-control calculateGroup2 inputDisabled' data-type='{$inputName}_total' name='{$inputName}_{$row["id"]}' value='".($row[$inputName] == 0 ? '' : $row[$inputName])."' readonly></td>";
			}
			else if (in_array($input_index, $group5)) 
			{
				if ($input_index == 47) {
					echo "<td><input type='text' class='form-control calculateGroup2' data-type='M_Dirty' 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 if ($input_index == 48) {
					echo "<td><input type='text' class='form-control calculateGroup2' data-type='B_Dirty' 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>";
	}
}
?>