<?php
ini_set("session.gc_maxlifetime", 28800); // 8 hours in seconds
ini_set("session.cookie_lifetime", 28800); // 8 hours in seconds
session_start();
ob_start();

date_default_timezone_set("Asia/Manila");
setlocale(LC_NUMERIC, "en_US.UTF-8");

//echo "<pre>";
//var_dump($_SESSION);
//echo "</pre>";

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

$superUser = isset($_SESSION["superUser"]) ? $_SESSION["superUser"] : null;

if (!$superUser) {
    unset($_SESSION["superUser"]);
}

$userType = isset($_SESSION["type"]) ? $_SESSION["type"] : null;
$userName = isset($_SESSION["username"]) ? $_SESSION["username"] : "error-user";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST["ProductionDate"])) {
        $_SESSION["ProductionDate"] = $_POST["ProductionDate"];
    }
}

$ProductionDate = isset($_SESSION["ProductionDate"]) ? $_SESSION["ProductionDate"] : date("Y-m-d");

try {
    $date = new DateTime($ProductionDate);
} catch (Exception $e) {
    $date = new DateTime();
}

$dayOfWeek = $date->format("l");

require_once("predata_INSERT.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<!-- FAVICON -->
<link rel="apple-touch-icon" sizes="180x180" href="img/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png">
<link rel="manifest" href="img/site.webmanifest">
 
<!-- Bootstrap CSS -->
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://getbootstrap.com/docs/5.3/assets/css/docs.css">
<link rel="stylesheet" type="text/css" href="bootstrap-5.3.3-dist/css/styling.css">
<link rel="stylesheet" type="text/css" href="https://cdn.lineicons.com/5.0/lineicons.css" />

<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/fomantic-ui/2.9.2/semantic.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/2.1.7/css/dataTables.semanticui.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/2.2.2/css/buttons.dataTables.min.css">

<title>Input Production | PG 7</title>
</head>
<body class="bg-pg7-secondary">
<svg xmlns="http://www.w3.org/2000/svg" class="d-none">
	<symbol id="check-circle-fill" viewBox="0 0 16 16">
		<path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-3.97-3.03a.75.75 0 0 0-1.08.022L7.477 9.417 5.384 7.323a.75.75 0 0 0-1.06 1.06L6.97 11.03a.75.75 0 0 0 1.079-.02l3.992-4.99a.75.75 0 0 0-.01-1.05z"/>
	</symbol>
	<symbol id="info-fill" viewBox="0 0 16 16">
		<path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16zm.93-9.412-1 4.705c-.07.34.029.533.304.533.194 0 .487-.07.686-.246l-.088.416c-.287.346-.92.598-1.465.598-.703 0-1.002-.422-.808-1.319l.738-3.468c.064-.293.006-.399-.287-.47l-.451-.081.082-.381 2.29-.287zM8 5.5a1 1 0 1 1 0-2 1 1 0 0 1 0 2z"/>
	</symbol>
	<symbol id="exclamation-triangle-fill" viewBox="0 0 16 16">
		<path d="M8.982 1.566a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566zM8 5c.535 0 .954.462.9.995l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995A.905.905 0 0 1 8 5zm.002 6a1 1 0 1 1 0 2 1 1 0 0 1 0-2z"/>
	</symbol>
</svg>
<!-- START Modal -->
<div class="modal fade modal-login modal-sm" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header bg-light">
				<h6 class="modal-title fw-bold">System Login</h6>
				<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
			<form id="loginForm" method="POST" class="needs-validation" novalidate>
				<div class="modal-body">
						<div class="form-group mb-2">
							<input type="text" name="username" class="form-control shadow-sm" placeholder="Username" autocomplete="off" required>
						</div>
						<div class="form-group mb-3">
							<input type="password" name="password" class="form-control shadow-sm" placeholder="Password" autocomplete="off" required>
						</div>
						<div class="mb-3">
							<div class="formMessage"></div>
						</div>
				</div>
				<div class="modal-footer">
					<button type="submit" class="btn btn-light btn-wo-border shadow-sm">Login</button>
					<button type="button" class="btn btn-dark btn-wo-border shadow-sm" data-bs-dismiss="modal">Close</button>
				</div>
			</form>
		</div>
	</div>
</div>

<div class="modal fade modal-ipdelete modal-sm" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<form method="POST">
				<div class="modal-body">
					<div class="input-group mb-2">
						<input type="hidden" name="ip_id" class="form-control inputDisabled" readonly>
					</div>
					 <p class="pt-3 pb-3">Are you sure you want to delete this?</p>
				</div>
				<div class="modal-footer">
					<button type="submit" name="ipDelete" class="btn btn-light shadow-sm">Proceed</button>
					<button type="button" class="btn btn-dark shadow-sm" data-bs-dismiss="modal">Cancel</button>
				</div>
			</form>
		</div>
	</div>
</div>
<!-- END Modal -->
<nav class="navbar navbar-expand bg-pg7-main">
	<div class="container-fluid">
		<div class="collapse navbar-collapse">
			<ul class="navbar-nav me-auto mb-lg-0">
				<li class="nav-item">
					<a href="dashboard.php?p=home" class="nav-link" title="Go to dashboard"><i class="lni lni-dashboard-square-1 fs-2"></i></a>
				</li>
				<li class="nav-item dropdown py-1">
					<a class="nav-link dropdown-toggle text-white" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
						Input Production
					</a>
					<ul class="dropdown-menu" id="myDropdownMenu">
						<li><a href="inputprod.php?u=<?php echo isset($userType) && !empty($userType) ? $userType : ""; ?>&p=ipep" class="dropdown-item">Egg Production</a></li>
						<li><a href="inputprod.php?u=<?php echo isset($userType) && !empty($userType) ? $userType : ""; ?>&p=ipes" class="dropdown-item">Egg Size</a></li>
						<li><a href="inputprod.php?u=<?php echo isset($userType) && !empty($userType) ? $userType : ""; ?>&p=ipfd" class="dropdown-item">Feed Delivery</a></li>
						<li><a href="inputprod.php?u=<?php echo isset($userType) && !empty($userType) ? $userType : ""; ?>&p=iptemp" class="dropdown-item"><i class="lni lni-cloud-sun"></i>Temperature</a></li>
						<li><hr class="dropdown-divider"></li>
						<li class="print-btn-placeholder">
							<!-- Print Button Insert Here -->
						</li>
					</ul>
				</li>
				<div class="vr border border-dark border-2 mx-2"></div>
				<li class="nav-item py-2">
					<i class="lni lni-user-4 text-white fs-2"></i> 
				</li>
				<li class="nav-item py-1">
					<a class="nav-link text-dark">
						<?php echo isset($userName) && !empty($userName) ? $userName : ""; ?>
					</a>
				</li>
				<li class="nav-item py-1">
					<?php if (isset($userType) && $userType === 2 && !isset($superUser)) { ?>
					<button type="button" name="login" class="btn btn-dark shadow-sm">Log in as Admin</button>
					<?php } ?>
					
					<?php if (isset($superUser)) { ?>
					<button type="button" name="logout" class="btn btn-dark shadow-sm" onclick="logoutSuperUser()">Return to Previous User</button>
					<?php } ?>
				</li>
			</ul>
			<ul class="navbar-nav ms-auto mb-lg-0">
				<li class="nav-item">
					<h1 class="display-8 opacity-50 px-2">PG 7</h1>
				</li>
			</ul>
		</div>
	</div>
</nav>

<div class="container-fluid mt-3">
	<?php if (isset($userType) && $userType === 2) { ?>
	<div class="row px-1">
		<div class="col-auto">	
			<div class="alert alert-warning d-flex align-items-center shadow" role="alert">
				<svg class="bi flex-shrink-0 me-2" role="img" aria-label="Info:"><use xlink:href="#info-fill"/></svg>
				<div>
					<h4>Data entry is restricted between 9PM and 6AM. To ensure that data is entered accurately during designated hours only.</h4>
				</div>
			</div>
		</div>
	</div>
	<?php } ?>
	
	<form method="POST" class="InputProduction">
		<div class="row px-1">
			<div class="col">
				<div class="row">
					<div class="col-auto">
						<div class="input-group">
							<label for="ProductionDate" class="input-group-text shadow-sm"><?php echo $dayOfWeek; ?></label>
							<input type="date" class="form-control shadow-sm" id="ProductionDate" name="ProductionDate" max="<?php echo date("Y-m-d"); ?>" value="<?php echo $ProductionDate; ?>">
							<div class="input-group-append">
								<button type="submit" name="buttonProductionDate" class="btn btn-dark shadow-sm rounded-0 btnProductionDate">Confirm</button>
							</div>
							<div class="btn-group px-3" role="group">
								<button type="submit" name="SaveButton" class="btn btn-light btn-wo-border shadow-sm fs-4 d-flex align-items-center justify-content-center" title="Save"><i class="lni lni-floppy-disk-1"></i></button>
								<?php if (isset($userType) && $userType !== 2 && !isset($superUser) && isset($_GET["p"]) && $_GET["p"] === "ipep") { ?>
								<button type="submit" name="RefreshButton" class="btn btn-light btn-wo-border shadow-sm fs-4 d-flex align-items-center justify-content-center" title="Refresh Input Production Table"><i class="lni lni-refresh-circle-1-clockwise"></i></button>
								<?php } ?>
								
								<?php if ((isset($superUser) && (isset($userType) && $userType === 2)) || (isset($userType) && $userType !== 2)) { ?>
									<button type="submit" name="NewRowButton" class="btn btn-wo-border btn-light shadow-sm fs-4 d-flex align-items-center justify-content-center" title="Add New Row"><i class="lni lni-plus"></i></button>
								<?php } ?>
								
								<?php if (isset($userType) && $userType === 2) { ?>
								<button type="submit" name="InsertButton" class="btn btn-light btn-wo-border shadow-sm fs-4 d-flex align-items-center justify-content-center" onclick="return confirm( 'Once you click OK, you will not be able to update it. Are you sure you want to commit this action?' )" title="Upload"><i class="lni lni-upload-1"></i></button>
								<?php } ?>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	
		<div class="row px-1 mt-1 mb-1">
			<div class="col-auto">
				<div class="dispMessage"></div>
			</div>
		</div>
		
		<div class="row px-1 mt-3">
			<div class="col-auto">
				<div id="spinner" style="display:none;">
					<div class="loader"></div>
				</div>
				<?php
				if (isset($_GET["p"]) && $_GET["p"] === "ipep")
				{
					require_once("ipepTable.php");
				}
				else if (isset($_GET["p"]) && $_GET["p"] === "ipes")
				{
					require_once("ipesTable.php");
				}
				else if (isset($_GET["p"]) && $_GET["p"] === "ipfd")
				{
					require_once("ipfdTable.php");
				}
				else if (isset($_GET["p"]) && $_GET["p"] === "iptemp")
				{
					require_once("iptempTable.php");
				}
				?>
			</div>
		</div>
	</form>
</div>

<!-- JavaScript Libraries -->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.7.1.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/2.1.7/js/dataTables.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/2.1.7/js/dataTables.semanticui.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fomantic-ui/2.9.2/semantic.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.11.8/umd/popper.min.js" integrity="sha512-TPh2Oxlg1zp+kz3nFA0C5vVC6leG/6mm1z9+mA81MI5eaUVqasPLO8Cuk4gMF4gUfP5etR73rgU/8PNMsSesoQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/3.0.2/js/dataTables.buttons.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/3.0.2/js/buttons.print.min.js"></script>

<!-- Custom JavaScript -->
<script type="text/javascript" src="bootstrap-5.3.3-dist/js/custom.js"></script>
<script type="text/javascript" src="bootstrap-5.3.3-dist/js/DataTables_ipep_2.js"></script>
<script type="text/javascript" src="bootstrap-5.3.3-dist/js/DataTables_ipes_2.js"></script>
<script type="text/javascript" src="bootstrap-5.3.3-dist/js/DataTables_ipfd_2.js"></script>
<script type="text/javascript" src="bootstrap-5.3.3-dist/js/DataTables_iptemp_2.js"></script>

<script type="text/javascript">
$( document ).ready( function() {
    const $table = $( ".table" );
    const $inputs = $table.find( "input" );

    $inputs.on( "keydown", function ( event ) {
        const currentCell = $( this ).closest( "td" );
        const currentRow = currentCell.closest( "tr" );

        if ( event.key === "Enter" ) {
            event.preventDefault();

            const $nextRow = currentRow.next();
            const $nextCell = $nextRow.length ? $nextRow.find( "td" ).eq( currentCell.index() ) : null;
            const $nextInput = $nextCell ? $nextCell.find( "input" ) : null;

            if ( $nextInput ) {
                $nextInput.focus();
            }
        }
    } );

	$( "button[name='login']" ).on( "click", function() {
		$( ".modal-login" ).find( "form" ).trigger( "reset" );
		$( ".modal-login" ).modal( "show" );
	} );
	
	$( ".modal-login" ).on( "hidden.bs.modal", function () {
        $( this ).find( "form" ).trigger( "reset" );
		$( this ).find( ".formMessage" ).html( "" );
    } );
	
	$( ".modal-ipdelete" ).on( "hidden.bs.modal", function () {
        $( this ).find( "form" ).trigger( "reset" );
    } );
	
    $( ".calculateGroup1" ).on( "change", function() {
        const $currentInput = $( this ); 

        const inputValues = [
            parseInt( $currentInput.closest( "tr" ).find( "input[name*='H1_T']" ).val() ) || 0,
            parseInt( $currentInput.closest( "tr" ).find( "input[name*='H2_T']" ).val() ) || 0,
            parseInt( $currentInput.closest( "tr" ).find( "input[name*='H3_T']" ).val() ) || 0,
            parseInt( $currentInput.closest( "tr" ).find( "input[name*='H4_T']" ).val() ) || 0,
            parseInt( $currentInput.closest( "tr" ).find( "input[name*='H5_T']" ).val() ) || 0,
            parseInt( $currentInput.closest( "tr" ).find( "input[name*='H6_T']" ).val() ) || 0
        ];

        const input7 = parseFloat( $currentInput.closest( "tr" ).find( "input[name*='H6_PCS']" ).val() ) || 0;

        const sumOfFirstSix = calculateSum( inputValues );
        const multipliedValue = sumOfFirstSix * 30;
        const finalResult = multipliedValue + input7;

        $currentInput.closest( "tr" ).find( "input[name*='H_TOTAL']" ).val( `${finalResult}` );
    } );
	
	$( ".calculateGroup1" ).on( "change", function() {
		const $currentInput = $( this ); 
		
		const inputValues = [
			parseInt( $currentInput.closest( "tr" ).find( "input[name*='Mortality']" ).val() ) || 0,
			parseInt( $currentInput.closest( "tr" ).find( "input[name*='Cull']" ).val() ) || 0,
			parseInt( $currentInput.closest( "tr" ).find( "input[name*='Reject']" ).val() ) || 0
		];
		
		const finalResult = calculateSum( inputValues );

		$currentInput.closest( "tr" ).find( "input[name*='Depletion']" ).val( `${finalResult}` );
	} );
	
	$( ".calculateGroup2" ).on( "change", function() {
		const $currentInput = $( this ); 
		const $row = $currentInput.closest( "tr" );

		function calculateTotal( dataType, param ) {
			let total = 0;
			
			$row.find( `input[data-type="${dataType}"]` ).each( function() {
				let value = parseFloat( $( this ).val() ) || 0;
				if ( param === "trays" ) {
					value *= 30;
				}
				total += value;
			} );
			
			return isNaN( total ) ? 0 : total;
		}
		
		const jmb_trays = calculateTotal( "JMB", "trays" );
		const jmb_pcs = calculateTotal( "JMB_PCS", "pcs" );
		const jmbTotal = jmb_trays + jmb_pcs;
		$row.find( "input[data-type='JMB_total']" ).val( `${jmbTotal}` );

		const xlr_trays = calculateTotal( "XLR", "trays" );
		const xlr_pcs = calculateTotal( "XLR_PCS", "pcs" );
		const xlrTotal = xlr_trays + xlr_pcs;
		$row.find( "input[data-type='XLR_total']" ).val( `${xlrTotal}` );
		
		const lrg_trays = calculateTotal( "LRG", "trays" );
		const lrg_pcs = calculateTotal( "LRG_PCS", "pcs" );
		const lrgTotal = lrg_trays + lrg_pcs;
		$row.find( "input[data-type='LRG_total']" ).val( `${lrgTotal}` );
		
		const med_trays = calculateTotal( "MED", "trays" );
		const med_pcs = calculateTotal( "MED_PCS", "pcs" );
		const medTotal = med_trays + med_pcs;
		$row.find( "input[data-type='MED_total']" ).val( `${medTotal}` );
		
		const sml_trays = calculateTotal( "SML", "trays" );
		const sml_pcs = calculateTotal( "SML_PCS", "pcs" );
		const smlTotal = sml_trays + sml_pcs;
		$row.find( "input[data-type='SML_total']" ).val( `${smlTotal}` );
		
		const pul_trays = calculateTotal( "PUL", "trays" );
		const pul_pcs = calculateTotal( "PUL_PCS", "pcs" );
		const pulTotal = pul_trays + pul_pcs;
		$row.find( "input[data-type='PUL_total']" ).val( `${pulTotal}` );
		
		const pwe_trays = calculateTotal( "PWE", "trays" );
		const pwe_pcs = calculateTotal( "PWE_PCS", "pcs" );
		const pweTotal = pwe_trays + pwe_pcs;
		$row.find( "input[data-type='PWE_total']" ).val( `${pweTotal}` );
		
		const spw_trays = calculateTotal( "SPW", "trays" );
		const spw_pcs = calculateTotal( "SPW_PCS", "pcs" );
		const spwTotal = spw_trays + spw_pcs;
		$row.find( "input[data-type='SPW_total']" ).val( `${spwTotal}` );
	} );
	
	$( ".calculateGroup2" ).on( "change", function() {
		const $currentInput = $( this ); 
	
		const m_dirty = parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='M_Dirty']" ).val() ) || 0;
		const b_dirty = parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='B_Dirty']" ).val() ) || 0;

		const sumOf = ( m_dirty + b_dirty );
		const finalResult = isNaN( sumOf ) ? 0 : sumOf;

		$currentInput.closest( "tr" ).find( "input[data-type='Dirty_total']" ).val( `${finalResult}` );
	} );
	
	$( ".calculateGroup2" ).on( "change", function() {
		const $currentInput = $( this ); 
		
		const inputValues = [
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='JMB_total']" ).val() ) || 0,
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='XLR_total']" ).val() ) || 0,
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='LRG_total']" ).val() ) || 0,
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='MED_total']" ).val() ) || 0,
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='SML_total']" ).val() ) || 0,
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='PUL_total']" ).val() ) || 0,
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='PWE_total']" ).val() ) || 0,
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='SPW_total']" ).val() ) || 0,
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='B1']" ).val() ) || 0,
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='B2']" ).val() ) || 0,
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='B3']" ).val() ) || 0,
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='Dirty_total']" ).val() ) || 0
		];

		const sumOf = calculateSum( inputValues );
		const finalResult = sumOf;

		$currentInput.closest( "tr" ).find( "input[data-type='Total']" ).val( `${finalResult}` );
	} );
	
	$( ".calculateGroup2" ).on( "change", function() {
		const $currentInput = $( this ); 
		
		const inputValues = [
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='JMB_total']").val() ) || 0,
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='XLR_total']").val() ) || 0,
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='LRG_total']").val() ) || 0,
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='MED_total']").val() ) || 0,
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='SML_total']").val() ) || 0,
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='PUL_total']").val() ) || 0,
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='PWE_total']").val() ) || 0,
			parseFloat( $currentInput.closest( "tr" ).find( "input[data-type='SPW_total']").val() ) || 0
		];

		const multiplier = [72.10, 69.50, 65.90, 62.15, 57.70, 52.80, 47.70, 43.00];

		const products = inputValues.map( (value, index) => value * multiplier[index] );
		const sumOfProducts = products.reduce( (acc, curr) => acc + curr, 0 );
		const sumOfInputValues = inputValues.reduce( (acc, curr) => acc + curr, 0 );
		const result = sumOfProducts / sumOfInputValues;
		const finalResult = isNaN( result ) ? 0 : result;
		
		$currentInput.closest( "tr" ).find( "input[data-type='A_W']" ).val( `${finalResult.toFixed(2)}` );
	} );
	
    $( "input[name*='BatchName'], input[name*='BldgNo'], input[name='ProductionDate']" ).on( "change", function() {
		var $currentRow = $( this ).closest( "tr" );

		var pValue = new URLSearchParams( window.location.search ).get( "p" );
		if ( pValue === "ipep" ) {
			$.ajax( {
				url: "ipepQuery.php",
				type: "POST",
				data: {
					ProductionDate: $( "input[name='ProductionDate']" ).val(),
					BatchName: $currentRow.find( "input[name*='BatchName']" ).val(),
					BldgNo: $currentRow.find( "input[name*='BldgNo']" ).val()
				},
				success: function( data ) {
					try {
						var parsedData = JSON.parse( data );
						if ( parsedData.error ) {
							return;
						} else {
							$currentRow.find( "input[name*='BatchCode']" ).val( parsedData.BatchCode ).attr( "value", parsedData.BatchCode );
							$currentRow.find( "input[name*='AgeInWeeks']" ).val( parsedData.AgeInWeeks ).attr( "value", parsedData.AgeInWeeks );
							$currentRow.find( "input[name*='Hen_Day']" ).val( parsedData.Hen_Day ).attr( "value", parsedData.Hen_Day );
						}
					} catch ( e ) {
						return;
					}
				},
				error: function() {
					$( ".dispMessage" ).html( "<div class='alert alert-danger'>" + response.message + "</div>" );
				}
			} );
		}
	} );
	
	$( "input[name*='BatchName'], input[name='ProductionDate'], .calculateGroup2" ).on( "change", function() {
		var $currentRow = $( this ).closest( "tr" );
		
		var pValue = new URLSearchParams( window.location.search ).get( "p" );
		if ( pValue === "ipes" ) 
		{
			$.ajax( {
				url: "ipesQuery.php",
				type: "POST",
				data: {
					ProductionDate: $( "input[name='ProductionDate']" ).val(),
					BatchName: $currentRow.find( "input[name*='BatchName']" ).val(),
					Total: $currentRow.find( "input[data-type='Total']" ).val(),
				},
				success: function( data ) {
					try {
						var parsedData = JSON.parse( data );
						if ( parsedData.error ) {
							return;
						} else {
							$currentRow.find( "input[name*='BatchCode']" ).val( parsedData.BatchCode ).attr( "value", parsedData.BatchCode );
							$currentRow.find( "input[name*='AgeInWeeks']" ).val( parsedData.AgeInWeeks ).attr( "value", parsedData.AgeInWeeks );
							$currentRow.find( "input[name*='Production']" ).val( parsedData.Production ).attr( "value", parsedData.Production );
							$currentRow.find( "input[name*='Variance']" ).val( parsedData.Variance ).attr( "value", parsedData.Variance );
							$currentRow.find( "input[name*='Dev']" ).val( parsedData.Dev ).attr( "value", parsedData.Dev );
						}
					} catch ( e ) {
						return;
					}
				},
				error: function() {
					$( ".dispMessage" ).html( "<div class='alert alert-danger'>" + response.message + "</div>" );
				}
			} );
		}
	} );
	
	$( "input[name*='BatchName'], input[name*='BldgNo'], input[name='ProductionDate']" ).on( "change", function() {
		var $currentRow = $( this ).closest( "tr" );
		
		var pValue = new URLSearchParams( window.location.search ).get( "p" );
		if ( pValue === "ipfd" ) 
		{
			$.ajax( {
				url: "ipfdQuery.php",
				type: "POST",
				data: {
					ProductionDate: $( "input[name='ProductionDate']" ).val(),
					BatchName: $currentRow.find( "input[name*='BatchName']" ).val(),
					BldgNo: $currentRow.find( "input[name*='BldgNo']" ).val()
				},
				success: function( data ) {
					try {
						var parsedData = JSON.parse( data );
						if ( parsedData.error ) {
							return;
						} else {
							$currentRow.find( "input[name*='begin_inventory']" ).val( parsedData.begin_inventory ).attr( "value", parsedData.begin_inventory );
						}
					} catch ( e ) {
						return;
					}
				},
				error: function() {
					$( ".dispMessage" ).html("<div class='alert alert-danger'>" + response.message + "</div>");
				}
			} );
		}
	} );

	$( ".calculateGroup3" ).on( "change", function() {
		const $currentInput = $( this ); 
		const $row = $currentInput.closest( "tr" );

		function convertSack( dataType, param ) {
			let total = 0;
			
			$row.find( `input[data-type="${dataType}"]` ).each( function() {
				let value = parseFloat( $( this ).val() ) || 0;
				if (param === "sack") {
					value *= 50;
				}
				total += value;
			} );
			
			return isNaN( total ) ? 0 : total;
		}
		
		const delivery_sack = convertSack( "delivery", "sack" );
		$row.find( "input[data-type='converted_delivery']" ).val( `${delivery_sack}` );
		
		const end_delivery_sack = convertSack( "end_delivery_sack", "sack" );
		const end_delivery_kilo = parseFloat( $row.find( "input[data-type='end_delivery_kilo']" ).val() ) || 0;
		const end_delivery_total = end_delivery_sack + end_delivery_kilo;
		$row.find( "input[data-type='end_delivery']" ).val( `${end_delivery_total}` );
	} );
	
	$( ".calculateGroup3" ).on( "change", function() {
		const $currentInput = $( this ); 
		const $row = $currentInput.closest( "tr" );
		
		const begin_delivery = parseFloat( $row.find( "input[data-type='begin_inventory']" ).val() ) || 0;
		const delivery = parseFloat( $row.find( "input[data-type='converted_delivery']" ).val() ) || 0;
		const end_delivery = parseFloat( $row.find( "input[data-type='end_delivery']" ).val() ) || 0;
		
		const result = ( begin_delivery + delivery ) - end_delivery;
		const finalResult = isNaN( result ) ? 0 : result;
		
		$row.find( "input[data-type='Consumption_KG']" ).val( `${finalResult}` );
		$row.find( "input[data-type='Consumption_GRAMS']" ).val( `${finalResult * 1000}` );
	} );

    //Trigger Inputs if page refreshed
	$( "input[name*='BatchName'], input[name*='BldgNo'], input[name='ProductionDate']" ).trigger( "change" );
	$( "input.calculateGroup1, input.calculateGroup2, input.calculateGroup3" ).trigger( "change" );

	$( ".ip-clickable" ).on( "click", function() {
		var data_id = $( this ).data( "id" );
		var data_table = $( this ).data( "table" );

		$.ajax( {
			url: "ipRowData.php",
			type: "GET",
			data: { 
				"data_id": data_id,
				"data_table": data_table
			},
			success: function( data ) {
				try {
					var parsedData = JSON.parse( data );
					if ( parsedData.error ) {
						return;
					} else {
						$( ".modal-ipdelete input[name='ip_id']" ).val( parsedData.id );
						$( ".modal-ipdelete" ).modal( "show" );
					}
				} catch ( e ) {
					return;
				}
			},
			error: function() {
				$( ".dispMessage" ).html( "<div class='alert alert-danger'>" + response.message + "</div>" );
			}
		} );
	} );
	
	$( "#loginForm" ).on( "submit", function(e) {
		e.preventDefault();

		var currentPage = window.location.href.replace( /#login_superuser/g, "" );

		$.ajax( {
			type: "POST",
			url: "login_as.php", 
			data: $( this ).serialize() + "&currentPage=" + encodeURIComponent( currentPage ),
			dataType: "json", 
			success: function( response ) {
				if ( response.status === "success" ) {
					window.location.replace(response.redirect);
				} else {
					$( ".formMessage" ).html( "<div class='alert alert-danger d-flex align-items-center shadow' role='alert'><h5>" + response.message + "</h5></div>" );
				}
			}
		} );
	} );
} );
</script>
</body>
<?php
require_once("RefreshData.php");
require_once("Save.php");
require_once("NewRow.php");
require_once("InputProduction_InsertQuery.php");
require_once("InputProduction_DeleteQuery.php");

if (!isset($_SESSION["logged_in"]) || $_SESSION["logged_in"] === FALSE) 
{
	header("Location: logout.php");
	exit();
}

if (isset($conn)) { $conn->close(); }
ob_end_flush();
?>
</html>