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

$ProductionDate = isset($_SESSION["ProductionDate"]) ? $_SESSION["ProductionDate"] : date("Y-m-d");
$headers = [
	"Entry Time",
	"id",
	"Temperature<br>(&deg;C)", 
	"Humidity<br>%", 
	"Heat Index<br>(&deg;C)", 
];
$inputNames = [
	"entry_time",
	"id", 
	"temp", 
	"humidity", 
	"heat_index", 
];
$dbTable = (isset($userType) && !empty($userType) && $userType === 2 || isset($superUser) && !empty($superUser)) ? "predata_temp" : "input_temp";

//$result = executeQuery($conn, "SELECT * FROM {$dbTable} WHERE ProductionDate = ? AND is_deleted = FALSE AND is_current = TRUE ORDER BY entry_time ASC", "s", [$ProductionDate]);
$result = executeQuery($conn, "SELECT * FROM {$dbTable} WHERE ProductionDate = ? AND is_deleted = FALSE AND is_current = TRUE ORDER BY STR_TO_DATE(entry_time, '%l:%i %p') ASC", "s", [$ProductionDate]);

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

$existingPOSTQuery = "SELECT COUNT(*) FROM input_temp 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_iptemp' class='ui display iptemp' style='display: none;'>";
	echo "<thead><tr>";
	
	foreach ($headers as $index => $headerText) 
	{
		echo "<th class='bg-light text-uppercase align-baseline'>{$headerText}</th>";
	}
	echo "</tr></thead><tbody>";
	
	$inputDisabled = [1];
	
	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>";
					//echo "<td style='display: flex; align-items: center;'><select class='form-select' name='{$inputName}_{$row["id"]}' id='select_{$row["id"]}'>";
					//$options = ["6:00 AM", "8:00 AM", "10:00 AM", "2:00 PM", "4:30 PM", "6:00 PM"];
					//echo "<option value=''>SELECT</option>";
					//foreach ($options as $option) {
					//	$selected = ($row[$inputName] == $option) ? "selected" : "";
					//	echo "<option value='$option' $selected>$option</option>";
					//}
					//echo "</select>
					//<script>
					//	document.getElementById('select_{$row["id"]}').disabled = true;
					//</script>
					//</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>";
					//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>
					//<select class='form-select' name='{$inputName}_{$row["id"]}' id='select_{$row["id"]}'>";
					//$options = ["6:00 AM", "8:00 AM", "10:00 AM", "2:00 PM", "4:30 PM", "6:00 PM"];
					//echo "<option value=''>SELECT</option>";
					//foreach ($options as $option) {
					//	$selected = ($row[$inputName] == $option) ? "selected" : "";
					//	echo "<option value='$option' $selected>$option</option>";
					//}
					//echo "</select>
					//<script>
					//	document.getElementById('select_{$row["id"]}').disabled = false;
					//</script>
					//</td>";
				}
			}
			elseif (in_array($input_index, $inputDisabled)) 
			{
				echo "<td><input type='text' class='form-control' name='{$inputName}_{$row["id"]}' value='" . $row[$inputName] . "' readonly></td>";
			}
			else 
			{
				echo "<td><input type='text' class='form-control' name='{$inputName}_{$row["id"]}' value='" . ($row[$inputName] == 0 ? '' : $row[$inputName]) . "' autocomplete='off'></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>";
	}
}
?>