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

$refreshSuccess = false;
mysqli_begin_transaction($conn);

if (isset($_POST["RefreshButton"]))
{
	try 
	{
		$batchDetailsResult = executeQuery($conn, "SELECT * FROM batch_details WHERE Status = 1 AND is_deleted = FALSE AND is_current = TRUE");
		
		if ($batchDetailsResult === false) { 
			throw new Exception("Error executing query: " . $conn->error);
		} 
		
		$bldgNoDetails = [];

		if ($batchDetailsResult->num_rows > 0) {
			while($brow = $batchDetailsResult->fetch_assoc()) {
				$bldgNoDetails[] = $brow;
			}
		} 

		$per_balance = 0;
		$allBldgNos = [];

		if (!empty($bldgNoDetails)) {
			foreach ($bldgNoDetails as $detail) {
				$bldgNos = explode(',', $detail['BldgNo']);
				$allBldgNos = array_merge($allBldgNos, $bldgNos);
			}
		}

		// Check for matches in input_prod table using executeQuery() and update Hen_Day
		if (!empty($allBldgNos)) {
			foreach ($allBldgNos as $bldgNo) {
				// Extract the balance from BldgNo
				preg_match('/\[(.*?)\]/', $bldgNo, $matches);
				$initialHenDay = $matches[1] ?? 0; // Extract the initial Hen_Day value

				// Remove the balance part from BldgNo
				$cleanBldgNo = preg_replace('/\[\d+\]/', '', $bldgNo);

				// Select all records for the BldgNo ordered by ProductionDate
				$query = "SELECT * FROM input_production WHERE BldgNo = ? ORDER BY ProductionDate ASC";
				$result = executeQuery($conn, $query, "s", [$cleanBldgNo]);
				
				if ($result === false) { 
					throw new Exception("Error executing query: " . $conn->error);
				} 
				
				$previousHenDay = $initialHenDay;
				if ($result->num_rows > 0) {
					while ($row = $result->fetch_assoc()) {
						$id = $row["id"]; // Assuming there's an 'id' column to uniquely identify the row
						$depletion = $row["Depletion"]; // Assuming there's a 'Depletion' column
						
						// Update the Hen_Day column
						$updateQuery = "UPDATE input_production SET Hen_Day = ? WHERE id = ?";
						$updateResult = executeQuery($conn, $updateQuery, "si", [$previousHenDay, $id]);

						// Calculate the Hen_Day for the next day
						$previousHenDay -= $depletion;
						
						if ($updateResult === false) { 
							throw new Exception("Error executing query: " . $conn->error);
						} else {
							$refreshSuccess = true;
						}
						
						mysqli_commit($conn);

						if ($refreshSuccess) {
							$_SESSION["refreshSuccess"] = true;

							header("Location: " . $_SERVER["REQUEST_URI"]);
							exit();
						}
					}
				}
			}
		}
	}
	catch (Exception $e) {
        mysqli_rollback($conn);
		// Log the error message
        error_log($e->getMessage());
		// Redirect to an error page or display an error message
        //header("Location: error_page.php");
        //exit();
    }
}

if (isset($_SESSION["refreshSuccess"])) 
{
    ?>
    <script>
        $( ".dispMessage" ).append( "<div class='alert alert-primary d-flex align-items-center shadow' role='alert'><h4>All reports has been recalculated successfully.</h4></div>" );
    </script>
    <?php
    unset($_SESSION["refreshSuccess"]);
}
?>