<?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");

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

$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"];
    }
	if (isset($_POST["selectBatchName"])) {
        $_SESSION["selectBatchName"] = $_POST["selectBatchName"];
    }
}

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

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

$dayOfWeek = $date->format("l");
$dr_number = generateDRNumber($conn);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<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>Dashboard | PG 7</title>
</head>
<body class="bg-pg7-secondary">
<!-- MODAL START -->
<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-2">
						<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-register 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">Register</h6>
				<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
			<form id="regForm" method="POST" class="needs-validation" novalidate>
				<div class="modal-body">
					<div class="form-group mb-2">
						<input type="text" name="reg_username" class="form-control shadow-sm" placeholder="Please enter your username" autocomplete="off" required>
					</div>
					<div class="form-group mb-2">
						<input type="password" name="reg_password" class="form-control shadow-sm" placeholder="Please enter your password" autocomplete="off" required>
					</div>
					<div class="form-group mb-2">
						<select class="form-select shadow-sm" name="reg_type" id="reg_type" required>			
							<option value="2">PG 7 - User</option>
							<option value="3">PG 7 - Accounting</option>
							<option value="1">System Admin</option>
						</select>
					</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">Register</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-changepassword 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">Change Password</h6>
				<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
			<form id="cpForm" method="POST" class="needs-validation" novalidate>
				<div class="modal-body">
					<div class="form-group mb-2">
						<input type="text" name="cp_username" class="form-control shadow-sm" placeholder="Please enter your username" autocomplete="off" required>
					</div>
					<div class="form-group mb-2">
						<input type="password" name="cp_old_password" class="form-control shadow-sm" placeholder="Please enter your old password" autocomplete="off" required>
					</div>
					<div class="form-group mb-2">
						<input type="password" name="cp_new_password" class="form-control shadow-sm" placeholder="Please enter your new 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">Update</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-drsi" 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">
				<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
			<form method="POST" class="needs-validation" id="confirmationForm" novalidate>
				<div class="modal-body">
					<input type="hidden" name="drsi_id" class="form-control form-control-sm inputDisabled" readonly>
					<div class="row bg-white gx-0">
						<div class="col-auto" style="margin-top: -10px !important;">
							<table id="MyTable_drsi" class="ui display drsi_Table rounded-0">
								<thead>
									<tr>
										<th colspan="2">
											<img src="/img/original-logo-pg7.jpeg" class="" alt="PG7" style="width: 150px;" />
										</th>
										<th></th>
										<th colspan="2">
											<span class="text-decoration-underline fs-6 px-4">Delivery Receipt</span>
											<div class="row">
												<div class="col">
													<span>Date</span>
												</div>
												<div class="col">
													<input type="date" name="drsi_date_created" class="form-control form-control-sm receipt-header" value="<?php echo date("Y-m-d"); ?>" max="<?php echo date("Y-m-d"); ?>" required>
												</div>
											</div>
											<div class="row">
												<div class="col">
													<span>Customer</span>
												</div>
												<div class="col">
													<select class="form-select form-select-sm receipt-header" name="drsi_customer_name" required>
														<?php 
															echo getCustomerNames($conn);
														?>
													</select>
												</div>
											</div>
											<div class="row">
												<div class="col">
													<span>Price Eff</span>
												</div>
												<div class="col">
													<select class="form-select form-select-sm receipt-header" name="drsi_effectivity_date" required>
														<?php 
															require_once("get_effectivity_date.php");
														?>
													</select>	
												</div>
											</div>
											<div class="row">
												<div class="col">
													<span>DR No.</span>
												</div>
												<div class="col">
													<input type="text" name="drsi_number" class="form-control form-control-sm receipt-header" readonly>
												</div>
											</div>
										</th>
									</tr>
									<tr>
										<th>Item Name</th>
										<th>Crates</th>
										<th>Trays</th>
										<th>Price</th>
										<th>Amount</th>
									</tr>
								</thead>
								<tbody>
									<?php
									$field_names1 = [
										"Jumbo|drsi_jmb_crates|drsi_jmb_trays|si_jmb_price|si_jmb_amount", 
										"Extra Large|drsi_xlr_crates|drsi_xlr_trays|si_xlr_price|si_xlr_amount", 
										"Large|drsi_lrg_crates|drsi_lrg_trays|si_lrg_price|si_lrg_amount", 
										"Medium|drsi_med_crates|drsi_med_trays|si_med_price|si_med_amount", 
										"Small|drsi_sml_crates|drsi_sml_trays|si_sml_price|si_sml_amount", 
										"Pullet|drsi_pul_crates|drsi_pul_trays|si_pul_price|si_pul_amount", 
										"Pewee|drsi_pwe_crates|drsi_pwe_trays|si_pwe_price|si_pwe_amount", 
										"Super Pewee|drsi_spw_crates|drsi_spw_trays|si_spw_price|si_spw_amount", 
										"B1|drsi_b1_crates|drsi_b1_trays|si_b1_price|si_b1_amount", 
										"B2|drsi_b2_crates|drsi_b2_trays|si_b2_price|si_b2_amount", 
										"B3|drsi_b3_crates|drsi_b3_trays|si_b3_price|si_b3_amount", 
										"Dirty|drsi_dirty_crates|drsi_dirty_trays|si_dirty_price|si_dirty_amount"
									];

									foreach ($field_names1 as $field_name1) {
										$splitNames1 = explode("|", $field_name1);

										echo '<tr>';
										echo '<td>' . $splitNames1[0] . '</td>';
										echo '<td><input type="text" name="' . $splitNames1[1] . '" class="form-control form-control-sm" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off" readonly></td>';
										echo '<td><input type="text" name="' . $splitNames1[2] . '" class="form-control form-control-sm round-down-input" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off"></td>';
										echo '<td><div class="price-container"><span class="peso-sign">&#8369;</span><input type="text" name="' . $splitNames1[3] . '" class="form-control form-control-sm value" readonly></div></td>';
										echo '<td class="result"><div class="price-container"><span class="peso-sign">&#8369;</span><input type="text" name="' . $splitNames1[4] . '" class="form-control form-control-sm value" readonly></div></td>';
										echo '</tr>';
									}
									?>

									<tr>
										<td>Assorted*</td>
										<td><input type="text" name="drsi_assorted" class="form-control form-control-sm" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off"></td>
										<td colspan="3"><i class="px-2">see below breakdown</i></td>
										<td></td>
										<td></td>
									</tr>
									<tr>
										<td>Others**</td>
										<td><input type="text" name="drsi_others" class="form-control form-control-sm" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off"></td>
										<td colspan="3"><i class="px-2">see below breakdown</i></td>
										<td></td>
										<td></td>
									</tr>
									
									<tr>
										<td></td><td></td><td></td><td></td><td><div class="price-container"><span class="peso-sign">&#8369;</span><input type="text" id="eggtally_result" class="form-control form-control-sm value tally" readonly></div></td>
									</tr>

									<tr>
										<td colspan="2">EGGTRAY CHARGE</td><td></td><td><input type="text" name="drsi_eggtray_pcs" class="form-control form-control-sm" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off"></td><td><div class="price-container"><span class="peso-sign">&#8369;</span><input type="text" name="drsi_eggtray_charge" class="form-control form-control-sm value" readonly></div></td><td><div class="price-container"><span class="peso-sign">&#8369;</span><input type="text" id="eggtraytally_result" class="form-control form-control-sm value tally" readonly></div></td>
									</tr>

									<tr>
										<td></td><td></td><td></td><td>SHIPPING FEE</td><td><div class="price-container"><span class="peso-sign">&#8369;</span><input type="text" name="drsi_shipping_charge" id="shippingcharge_result" class="form-control form-control-sm value tally" readonly></div></td>
									</tr>	

									<tr>
										<td></td><td></td><td></td><td>OTHER CHARGES</td><td><div class="price-container"><span class="peso-sign">&#8369;</span><input type="text" name="drsi_other_charges" id="othercharges_result" class="form-control form-control-sm value tally" readonly></div></td>
									</tr>	

									<tr>
										<td></td><td></td><td></td><td>GRANDTOTAL</td><td><div class="price-container"><span class="peso-sign">&#8369;</span><input type="text" id="grandtotal_result" class="form-control form-control-sm value tally" readonly></div></td>
									</tr>		

									<tr>
										<td colspan="5">** Assorted Trays Breakdown:</td>
										<td></td>
										<td></td>
										<td></td>
										<td></td>
									</tr>
						
									<?php
									$field_names2 = [
										"Jumbo|drsi_ass_jmb_bd|Pewee|drsi_ass_pwe_bd",
										"Extra Large|drsi_ass_xlr_bd|S. Pewee|drsi_ass_spw_bd",
										"Large|drsi_ass_lrg_bd|B1|drsi_ass_b1_bd",
										"Medium|drsi_ass_med_bd|B2|drsi_ass_b2_bd",
										"Small|drsi_ass_sml_bd|B3|drsi_ass_b3_bd",
										"Pullet|drsi_ass_pul_bd|Dirty|drsi_ass_dirty_bd"
									];

									foreach ($field_names2 as $field_name2) {
										$splitNames2 = explode("|", $field_name2);

										echo '<tr class="footer2">';
										echo '<td>' . $splitNames2[0] . '</td>';
										echo '<td><input type="text" name="' . $splitNames2[1] . '" class="form-control form-control-sm" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off"></td>';
										echo '<td></td>';
										echo '<td>' . $splitNames2[2] . '</td>';
										echo '<td><input type="text" name="' . $splitNames2[3] . '" class="form-control form-control-sm" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off"></td>';
										echo '</tr>';
									}
									?>
									
									<tr>
										<td colspan="5">** Others Breakdown:</td>
										<td></td>
										<td></td>
										<td></td>
										<td></td>
									</tr>
									
									<?php
									$field_names3 = [
										"Jumbo|drsi_oth_jmb_bd|Pewee|drsi_oth_pwe_bd",
										"Extra Large|drsi_oth_xlr_bd|S. Pewee|drsi_oth_spw_bd",
										"Large|drsi_oth_lrg_bd|B1|drsi_oth_b1_bd",
										"Medium|drsi_oth_med_bd|B2|drsi_oth_b2_bd",
										"Small|drsi_oth_sml_bd|B3|drsi_oth_b3_bd",
										"Pullet|drsi_oth_pul_bd|Dirty|drsi_oth_dirty_bd"
									];

									foreach ($field_names3 as $field_name3) {
										$splitNames3 = explode("|", $field_name3);

										echo '<tr class="footer2">';
										echo '<td>' . $splitNames3[0] . '</td>';
										echo '<td><input type="text" name="' . $splitNames3[1] . '" class="form-control form-control-sm" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off"></td>';
										echo '<td></td>';
										echo '<td>' . $splitNames3[2] . '</td>';
										echo '<td><input type="text" name="' . $splitNames3[3] . '" class="form-control form-control-sm" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off"></td>';
										echo '</tr>';
									}
									?>
								</tbody>
								<tfoot style="display: none;">
									<tr>
										<td colspan="2"><input type="text" name="drsi_receiver" class="form-control form-control-sm fw-bold mt-3" autocomplete="off"></td>
										<td></td>
										<td colspan="2"><input type="text" name="drsi_received_date" class="form-control form-control-sm fw-bold mt-3" autocomplete="off"></td>
									</tr>
									<tr>
										<td colspan="2"><span class="px-5" style="border-top: solid 1px #000;">Receiver</span></td>
										<td></td>
										<td colspan="2"><span class="px-4" style="border-top: solid 1px #000;">Date Received</span></td>
									</tr>
								</tfoot>
							</table>
						</div>
					</div>				
				</div>
				<div class="modal-footer">
					<button type="submit" name="AddNew_<?php echo isset($_GET["p"]) ? strtoupper($_GET["p"]) : ""; ?>" class="btn btn-light btn-wo-border shadow-sm">Save</button>
					
					<button type="submit" name="Confirm_<?php echo isset($_GET["p"]) ? strtoupper($_GET["p"]) : ""; ?>" class="btn btn-light btn-wo-border shadow-sm" onclick="
						var receivedBy = prompt( 'Received by:' );
						if ( receivedBy !== null && receivedBy.trim() !== '' ) {
							receivedBy = receivedBy.charAt(0).toUpperCase() + receivedBy.slice(1);

							var receivedByInput = document.createElement( 'input' );
							receivedByInput.type = 'hidden';
							receivedByInput.name = 'receiver';
							receivedByInput.value = receivedBy;

							var remarks = prompt( 'Remarks (optional):' );
							if ( remarks !== null && remarks.trim() !== '' ) {
								remarks = remarks.charAt(0).toUpperCase() + remarks.slice(1);

								var remarksInput = document.createElement( 'input' );
								remarksInput.type = 'hidden';
								remarksInput.name = 'remarks';
								remarksInput.value = remarks;
								document.getElementById( 'confirmationForm' ).appendChild( remarksInput );
							}

							document.getElementById( 'confirmationForm' ).appendChild( receivedByInput );
						} else {
							alert( 'Receiver name should not be blank.' );
							event.preventDefault();
						}
					">Confirm</button>

					<button type="submit" name="Update_<?php echo isset($_GET["p"]) ? strtoupper($_GET["p"]): ""; ?>" class="btn btn-light btn-wo-border shadow-sm">Update</button>
					<button type="submit" name="Delete_<?php echo isset($_GET["p"]) ? strtoupper($_GET["p"]) : ""; ?>" class="btn btn-light btn-wo-border shadow-sm" onclick="return confirm( 'Are you sure you want to delete this?' )">Delete</button>
					<button type="button" class="btn btn-dark shadow-sm" data-bs-dismiss="modal">Close</button>
				</div>
			</form>
		</div>
	</div>
</div>

<div class="modal fade modal-pl modal-md" 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">New Pricelist</h6>
				<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
			<form id="plForm" method="POST" class="needs-validation" novalidate>
				<div class="modal-body">
					<input type="hidden" name="pl_id" class="form-control form-control-sm inputDisabled" readonly>
					<div class="input-group input-group-sm mb-1 has-validation">
						<span class="input-group-text">Effectivity Date</span>
						<input type="date" name="pl_effectivity_date" class="form-control" max="<?php echo date("Y-m-d"); ?>" value="<?php echo date("Y-m-d"); ?>" required>
						<div class="invalid-feedback" style="margin-left: 140px;">
							Please select a date.
						</div>
					</div>
					
					<div class="input-group input-group-sm mb-2 has-validation">
						<span class="input-group-text">Customer Name</span>
						<select class="form-select" name="pl_customer_name" required>
							<?php 
								echo getCustomerNames($conn);
							?>
						</select>
						<div class="invalid-feedback" style="margin-left: 140px;">
							Please select a customer name.
						</div>
					</div>
					
					<div class="input-group input-group-sm mb-1">
						<span class="input-group-text">Egg Tray Charges</span>
						<select class="form-select" name="pl_eggtray_charge_sel" required>
							<option value="" disabled selected>SELECT</option>
							<option value="1">Yes</option>
							<option value="2">No</option>
						</select>
						<input type="text" name="pl_eggtray_charge" class="form-control" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" placeholder="Please enter..." autocomplete="off" required>
					</div>
					
					<div class="input-group input-group-sm mb-1">
						<span class="input-group-text">Shipping Charges</span>
						<select class="form-select" name="pl_shipping_charge_sel" required>
							<option value="" disabled selected>SELECT</option>
							<option value="1">Yes</option>
							<option value="2">No</option>
						</select>
						<input type="text" name="pl_shipping_charge" class="form-control" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" placeholder="Please enter..." autocomplete="off" required>
					</div>
					
					<div class="input-group input-group-sm mb-1">
						<span class="input-group-text">Other Charges</span>
						<select class="form-select" name="pl_other_charges_sel" required>
							<option value="" disabled selected>SELECT</option>
							<option value="1">Yes</option>
							<option value="2">No</option>
						</select>
						<input type="text" name="pl_other_charges" class="form-control" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" placeholder="Please enter..." autocomplete="off" required>
					</div>
					
					<div class="form-floating mb-2">
						<textarea class="form-control" name="pl_other_charges_remark" id="floatingTextarea2" required></textarea>
						<label for="floatingTextarea2">Remark</label>
					</div>
					
					<div class="input-group input-group-sm mb-1">
						<span class="input-group-text">Jumbo</span>
						<input type="text" name="pl_JMB" class="form-control" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off">
					</div>
					<div class="input-group input-group-sm mb-1">
						<span class="input-group-text">Extra Large</span>
						<input type="text" name="pl_XLR" class="form-control" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off">
					</div>	
					<div class="input-group input-group-sm mb-1">
						<span class="input-group-text">Large</span>
						<input type="text" name="pl_LRG" class="form-control" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off">
					</div>	
					<div class="input-group input-group-sm mb-1">
						<span class="input-group-text">Medium</span>
						<input type="text" name="pl_MED" class="form-control" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off">
					</div>	
					<div class="input-group input-group-sm mb-1">
						<span class="input-group-text">Small</span>
						<input type="text" name="pl_SML" class="form-control" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off">
					</div>	
					<div class="input-group input-group-sm mb-1">
						<span class="input-group-text">Pullet</span>
						<input type="text" name="pl_PUL" class="form-control" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off">
					</div>	
					<div class="input-group input-group-sm mb-1">
						<span class="input-group-text">Pewee</span>
						<input type="text" name="pl_PWE" class="form-control" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off">
					</div>	
					<div class="input-group input-group-sm mb-1">
						<span class="input-group-text">Super Pewee</span>
						<input type="text" name="pl_SPW" class="form-control" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off">
					</div>	
					<div class="input-group input-group-sm mb-1">
						<span class="input-group-text">B1</span>
						<input type="text" name="pl_B1" class="form-control" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off">
					</div>	
					<div class="input-group input-group-sm mb-1">
						<span class="input-group-text">B2</span>
						<input type="text" name="pl_B2" class="form-control" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off">
					</div>	
					<div class="input-group input-group-sm mb-1">
						<span class="input-group-text">B3</span>
						<input type="text" name="pl_B3" class="form-control" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off">
					</div>	
					<div class="input-group input-group-sm mb-1">
						<span class="input-group-text">Dirty</span>
						<input type="text" name="pl_Dirty" class="form-control" pattern="[0-9]+(\.[0-9]+)?" title="Please enter a valid number" autocomplete="off">
					</div>
				</div>
				<div class="modal-footer">
					<button type="submit" name="AddNew_PL" class="btn btn-light btn-wo-border shadow-sm">Save</button>
					<button type="submit" name="Update_PL" class="btn btn-light btn-wo-border shadow-sm">Update</button>
					<button type="submit" name="Delete_PL" class="btn btn-light btn-wo-border shadow-sm" onclick="return confirm( 'Are you sure you want to delete this?' )">Delete</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-customer modal-md" 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">New Customer</h6>
				<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
			<form id="cusForm" method="POST" class="needs-validation" novalidate>
				<div class="modal-body">
					<div class="input-group input-group-sm mb-1 has-validation">
						<span class="input-group-text">Customer Name</span>
						<input type="text" name="customer_name" class="form-control" autocomplete="off" required>
						<div class="invalid-feedback" style="margin-left: 140px;">
							Please enter a customer name.
						</div>
					</div>
				</div>
				<div class="modal-footer">
					<button type="submit" name="AddNew_CN" class="btn btn-light btn-wo-border shadow-sm">Save</button>
					<!--button type="submit" name="Delete_CN" class="btn btn-light" onclick="return confirm('Are you sure you want to delete this?')">Delete</button-->
					<button type="button" class="btn btn-dark btn-wo-border shadow-sm" data-bs-dismiss="modal">Close</button>
				</div>
			</form>
		</div>
	</div>
</div>
<!-- MODAL END-->
<div class="wrapper">
	<aside id="sidebar" class="expand bg-pg7-main">
		<div style="display: flex; align-items: center;">
			<button class="toggle-btn" type="button">
				<i class="lni lni-dashboard-square-1"></i>
			</button>
			<div class="sidebar-logo">
				<a href="dashboard.php?p=home" class="text-d"></a>
			</div>
		</div>
		<ul class="sidebar-nav">
			<?php if (isset($_SESSION["logged_in"]) && $_SESSION["logged_in"] === TRUE) { ?>
				<li class="sidebar-item">
					<a href="#" class="sidebar-link collapsed has-dropdown" data-bs-toggle="collapse"
					   data-bs-target="#inputprod" aria-expanded="false" aria-controls="inputprod" style="display: flex; align-items: center;">
					   <i class="lni lni-file-pencil"></i>
					   <span style="margin-left: 8px;">Input Production</span>
					</a>
					<ul id="inputprod" class="sidebar-dropdown list-unstyled collapse" data-bs-parent="#sidebar">
						<li class="sidebar-item">
							<a href="inputprod.php?u=<?php echo isset($userType) && !empty($userType) ? $userType : ""; ?>&p=ipep" class="sidebar-link">Egg Production</a>
						</li>
						<li class="sidebar-item">
							<a href="inputprod.php?u=<?php echo isset($userType) && !empty($userType) ? $userType : ""; ?>&p=ipes" class="sidebar-link">Egg Size</a>
						</li>
						<li class="sidebar-item">
							<a href="inputprod.php?u=<?php echo isset($userType) && !empty($userType) ? $userType : ""; ?>&p=ipfd" class="sidebar-link">Feed Delivery</a>
						</li>
						<li class="sidebar-item">
							<a href="inputprod.php?u=<?php echo isset($userType) && !empty($userType) ? $userType : ""; ?>&p=iptemp" class="sidebar-link">Temperature</span>
							</a>
						</li>
					</ul>
				</li>
			<?php } ?>
			
			<?php if (isset($userType) && $userType !== 2) { ?>
				<li class="sidebar-item">
					<a href="#" class="sidebar-link collapsed has-dropdown" data-bs-toggle="collapse"
					   data-bs-target="#controllers" aria-expanded="false" aria-controls="controllers" style="display: flex; align-items: center;">
					   <i class="lni lni-sliders-horizontal-square-2"></i>
					   <span style="margin-left: 8px;">Controllers</span>
					</a>
					<ul id="controllers" class="sidebar-dropdown list-unstyled collapse" data-bs-parent="#sidebar">
						<li class="sidebar-item">
							<a href="controller.php?u=<?php echo isset($userType) && !empty($userType) ? $userType : ""; ?>&p=es" class="sidebar-link">Egg Standards</a>
						</li>
						<li class="sidebar-item">
							<a href="controller.php?u=<?php echo isset($userType) && !empty($userType) ? $userType : ""; ?>&p=bd" class="sidebar-link">Batch Details</a>
						</li>
					</ul>
				</li>
			<?php } ?>
			
			<li class="sidebar-item">
				<a href="#" class="sidebar-link collapsed has-dropdown" data-bs-toggle="collapse"
				   data-bs-target="#reports" aria-expanded="false" aria-controls="reports" style="display: flex; align-items: center;">
				   <i class="lni lni-notebook-1"></i>
				   <span style="margin-left: 8px;">Production Reports</span>
				</a>
				<ul id="reports" class="sidebar-dropdown list-unstyled collapse" data-bs-parent="#sidebar">
					<li class="sidebar-item">
						<a href="dashboard.php?p=dep" class="sidebar-link">Egg Production</a>
					</li>
					<li class="sidebar-item">
						<a href="dashboard.php?p=des" class="sidebar-link">Egg Size</a>
					</li>
				</ul>
			</li>
			
			<?php if (isset($userType) && $userType !== 2) { ?>
			<li class="sidebar-item">
				<a href="dashboard.php?p=pl" class="sidebar-link" style="display: flex; align-items: center;">
					<i class="lni lni-hand-taking-dollar"></i>
					<span style="margin-left: 8px;">Customer Pricelists</span>
				</a>
			</li>
			<?php } ?>
			
			<?php if (isset($_SESSION["logged_in"]) && $_SESSION["logged_in"] === TRUE) { ?>
				<li class="sidebar-item">
					<a href="dashboard.php?p=dr" class="sidebar-link" style="display: flex; align-items: center;">
						<i class="lni lni-truck-delivery-1"></i>
						<span style="margin-left: 8px;" title="DR/ Invoice">Transactions</span>
					</a>
				</li>
			<?php } ?>
			
			<li class="sidebar-item">
				<a href="dashboard.php?p=home" class="sidebar-link" style="display: flex; align-items: center;">
					<i class="lni lni-gauge-1"></i>
					<span style="margin-left: 8px;">Dashboard</span>
				</a>
			</li>
			<li class="sidebar-item">
				<a href="#" class="sidebar-link collapsed has-dropdown" data-bs-toggle="collapse"
				   data-bs-target="#auth" aria-expanded="false" aria-controls="auth" style="display: flex; align-items: center;">
				   <i class="lni lni-shield-2-check"></i>
				   <span style="margin-left: 8px;">Auth</span>
				</a>
				<ul id="auth" class="sidebar-dropdown list-unstyled collapse" data-bs-parent="#sidebar">
					<li class="sidebar-item">
						<?php if (!isset($_SESSION["logged_in"]) || $_SESSION["logged_in"] === FALSE) { ?>
							<a href="#login" class="sidebar-link login">Login</a>
						<?php } ?>
						<?php if (isset($userType) && $userType !== 2) { ?>
							<a href="#register" class="sidebar-link register">Register</span></a>
						<?php } ?>
						<?php if (isset($_SESSION["logged_in"]) && $_SESSION["logged_in"] === TRUE) { ?>
							<a href="#changepassword" class="sidebar-link changepassword">Change Password</a>
						<?php } ?>
					</li>
				</ul>
			</li>
		</ul>
		<?php if (isset($_SESSION["logged_in"]) && $_SESSION["logged_in"] === TRUE) { ?>
			<div class="sidebar-footer">
				<a href="logout.php" class="sidebar-link" style="display: flex; align-items: center;">
					<i class="lni lni-exit"></i>
					<span style="margin-left: 8px;">Logout</span>
				</a>
			</div>
		<?php } ?>
	</aside>
	<div class="main">
		<?php if (TRUE) { ?>
			<nav class="navbar navbar-expand mx-4">
			
				<?php if (isset($_GET["p"]) && $_GET["p"] === "home") { ?>
					<form method="POST">
						<div class="row">
							<div class="col-auto">
								<div class="input-group">
									<div class="form-floating">
										<select class="form-select shadow-sm" name="selectBatchName" id="selectBatchName" style="width: 120px;">
											<?php 
												echo getBatchNameOptions($conn, "All");
											?>
										</select>
										<label for="selectBatchName">Batch Name</label>
									</div>
									<button type="submit" class="btn btn-dark btn-wo-border shadow-sm graphButton">Confirm</button>
								</div>
							</div>
						</div>
					</form>
				<?php } ?>
				
				<?php if (isset($_GET["p"]) && ($_GET["p"] === "dep" || $_GET["p"] === "des")) { ?>
					<form method="POST">
						<div class="row">
							<div class="col-auto">
								<div class="input-group">
									<div class="form-floating form-floating-group flex-grow-1">
										<input type="date" class="form-control shadow-sm" id="ProductionDate" name="ProductionDate" max="<?php echo date("Y-m-d"); ?>" value="<?php echo $ProductionDate; ?>">
										<label for="ProductionDate"><?php echo $dayOfWeek; ?></label>
									</div>
									<button type="submit" class="btn btn-dark btn-wo-border shadow-sm">Confirm</button>
								</div>
							</div>
						</div>
					</form>
				<?php } ?>
				
				<?php if (isset($_GET["p"]) && $_GET["p"] === "pl") { ?>
					<div class="row">
						<div class="col-auto">
							<div class="btn-group" role="group">
								<button type="button" name="AddNew_Customer" class="btn btn-light btn-wo-border shadow-sm fs-4 d-flex align-items-center justify-content-center" title="New Customer"><i class="lni lni-refresh-user-1"></i></button>
								<button type="button" name="AddNew_Pricelist" class="btn btn-light btn-wo-border shadow-sm fs-4 d-flex align-items-center justify-content-center" title="New Pricelist"><i class="lni lni-refresh-dollar-1"></i></button>
							</div>
						</div>	
						<div class="col-auto dt-search-placeholder">
							<!-- Search Box Here -->
						</div>
					</div>
				<?php } ?>
				
				<?php if (isset($_GET["p"]) && $_GET["p"] === "dr") { ?>
					<div class="row">
						<div class="col-auto">
							<button type="button" name="AddNew_DeliveryReceipt" class="btn btn-light btn-wo-border shadow-sm fs-4 d-flex align-items-center justify-content-center" title="Add New"><i class="lni lni-plus"></i></button>
						</div>
						<div class="col-auto dt-search-placeholder">
							<!-- Search Box Here -->
						</div>
						<!--div class="col-auto">
							<?php
								require_once("DisplayBalance.php");
							?>
						</div-->
					</div>
				<?php } ?>
				
				<div class="navbar-collapse collapse">
					<ul class="navbar-nav ms-auto">
						<li class="nav-item dropdown">
							<a href="#" data-bs-toggle="dropdown" class="nav-icon pe-md-0">
								<!--img src="/img/account.png" class="avatar img-fluid" alt=""-->
							</a>
						</li>
					</ul>
				</div>
			</nav>
		<?php } ?>
		
		<main class="content">
			<div class="container-fluid mx-4">
				<?php if (isset($_GET["p"]) && $_GET["p"] === "home") { ?>
					<div class="row">
						<div class="col-auto mt-1">
							<canvas id="myChart1" class="bg-dark bg-gradient rounded"></canvas>
						</div>
						<div class="col-auto mt-1">
							<canvas id="myChart2" class="bg-dark bg-gradient rounded"></canvas>
						</div>
						<div class="col-auto mt-1">
							<canvas id="myChart3" class="bg-dark bg-gradient rounded"></canvas>
						</div>
						<div class="col-auto mt-1">
							<canvas id="myChart4" class="bg-dark bg-gradient rounded"></canvas>
						</div>
					</div>
					
					<div class="row">
						<div class="col-auto mt-1">
							<canvas id="myChart5" class="bg-dark bg-gradient rounded"></canvas>
						</div>
						<div class="col-auto mt-1">
							<canvas id="myChart6" class="bg-dark bg-gradient rounded"></canvas>
						</div>
					</div>

					<div class="row">
						<div class="col-auto">
							<?php 
								require_once("GraphData_2.php");
							?>
						</div>
					</div>
					
					<?php if (isset($_SESSION["logged_in"]) && $_SESSION["logged_in"] === TRUE && $userType !== 2) { ?>
						<div class="row mt-2">
							<div class="col-auto">
								<button type="button" name="toggleBatchName" class="btn btn-light btn-wo-border shadow-sm">Show Data</button>
							</div>
						</div>
					<?php } ?>
				<?php } ?>
				
				<?php if (isset($_GET["p"]) && $_GET["p"] === "dep") { ?>
					<div class="row">
						<div class="col-auto">
							<?php
							if (isset($_GET["p"]) && $_GET["p"] === "dep") 
							{
								require_once("depDisplay_Table.php");
							}
							?>
						</div>
					</div>
				<?php } ?>
				
				<?php if (isset($_GET["p"]) && $_GET["p"] === "des") { ?>
					<div class="row">
						<div class="col-auto">
							<?php
							if (isset($_GET["p"]) && $_GET["p"] === "des") 
							{
								require_once("desDisplay_Table.php");
							}
							?>
						</div>
					</div>
				<?php } ?>
				
				<?php if (isset($_GET["p"]) && $_GET["p"] === "pl") { ?>
					<div class="row">
						<div class="col-auto">
							<?php
								require_once("plDisplay_Table.php");
							?>
						</div>
					</div>
				<?php } ?>
				
				<?php if (isset($_GET["p"]) && $_GET["p"] === "dr") { ?>
					<!--form method="POST">
						<div class="row">
							<div class="col-auto">
								<div class="input-group">
									<div class="form-floating form-floating-group flex-grow-1">
										<input type="date" class="form-control shadow-sm" id="ProductionDate" name="ProductionDate" max="<?php echo date("Y-m-d"); ?>" value="<?php echo $ProductionDate; ?>">
										<label for="ProductionDate"><?php echo $dayOfWeek; ?></label>
									</div>
									<button type="submit" class="btn btn-dark btn-wo-border shadow-sm">Confirm</button>
								</div>
							</div>
						</div>
					</form-->
					<div class="row mt-3">
						<div class="col-auto">
							<?php
								//require_once("drDisplay_Table.php");
								require_once("DisplayTransactions.php");
							?>
						</div>
					</div>
				<?php } ?>
				
				<?php if (isset($_SESSION["logged_in"])) { ?>
					<div id="chat-icon" data-bs-toggle="modal" data-bs-target="#chatModal">
						<i class="lni lni-message-2 bg-dark text-white rounded-circle fs-2 p-2"></i>
					</div>
					
					<!-- START Chat Modal -->
					<div class="modal fade" id="chatModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="chatModalLabel" aria-hidden="true">
						<div class="modal-dialog" role="document">
							<div class="modal-content">
								<div class="modal-header bg-light">
									<h6 class="modal-title fw-bold">System Notifications</h6>
									<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
								</div>
								<div class="modal-body">
									<div class="chat-box border p-3 mb-3" id="chat-box" style="height: 300px; overflow-y: scroll;">
										<!-- Messages will appear here -->
									</div>
									<?php if (isset($userType) && $userType === 3) { ?>
										<form id="chat-form">
											<div class="input-group">
												<input type="hidden" id="username" class="form-control" placeholder="Username" value="<?php echo $userName; ?>" readonly>
												<textarea id="message" class="form-control" placeholder="Type your message..." required></textarea>
												<button type="submit" class="btn btn-dark btn-wo-border text-white shadow-sm">Send</button>
											</div>
										</form>
									<?php } ?>
								</div>
							</div>
						</div>
					</div>
					<!-- END Chat Modal -->
				<?php } ?>
			</div>
		</main>
	</div>
</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_dep_2.js"></script>
<script type="text/javascript" src="bootstrap-5.3.3-dist/js/DataTables_des_2.js"></script>
<script type="text/javascript" src="bootstrap-5.3.3-dist/js/DataTables_dr_2.js"></script>
<script type="text/javascript" src="bootstrap-5.3.3-dist/js/DataTables_pldrsi.js"></script>
<script type="text/javascript" src="bootstrap-5.3.3-dist/js/DataTables_Graph.js"></script>

<!-- START Chart.js -->
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
<script type="text/javascript" src="bootstrap-5.3.3-dist/js/dashboard-chart.js"></script>
<!-- END Chart.js -->

<script type="text/javascript">
function toggleView(view) {
    var gridView = document.getElementById('MyTable_pldrsi');
    var cardView = document.getElementById('cardView');
	console.log('Toggling view to: ' +  view );
    if (view === 'grid') {
        gridView.style.display = 'block';
        cardView.style.display = 'none';
    } else {
        gridView.style.display = 'none';
        cardView.style.display = 'flex';
    }
}

var selectedValue = "<?php echo $selectBatchName; ?>";
var selectElement = document.getElementById( "selectBatchName" );

if ( selectElement ) {
	selectElement.value = selectedValue;
	
	for ( var i = 0; i < selectElement.options.length; i++ ) {
		if ( selectElement.options[i].value === selectedValue ) {
			selectElement.options[i].setAttribute( "selected", "selected" );
		} else {
			selectElement.options[i].removeAttribute( "selected" );
		}
	}
}

//@================= START - SideBar
const sideBar = document.querySelector( ".toggle-btn" );

sideBar.addEventListener( "click", function () {
  document.querySelector( "#sidebar" ).classList.toggle( "expand" );
} );
//@================= END - SideBar

//@================= START - CALCULATE INVOICE
function updateGrandTotal() {
    const eggtally = parseFloat(document.getElementById( "eggtally_result" ).value) || 0;
    const eggtraytally = parseFloat(document.getElementById( "eggtraytally_result" ).value) || 0;
    const shippingcharge = parseFloat(document.getElementById( "shippingcharge_result" ).value) || 0;
    const othercharges = parseFloat(document.getElementById( "othercharges_result" ).value) || 0;

    const grandTotal = eggtally + eggtraytally + shippingcharge + othercharges;
	
    const grandTotalInput = document.getElementById( "grandtotal_result" );
    if (grandTotalInput) {
        grandTotalInput.value = grandTotal === 0 ? "0.00" : grandTotal.toFixed(2);
    }
}

function calculateEggtrayTally() {
    const eggtrayInput = document.querySelector( "input[name='drsi_eggtray_pcs']" );
    const eggtrayChargeInput = document.querySelector( "input[name='drsi_eggtray_charge']" );
    const resultInput = document.getElementById( "eggtraytally_result" );

    if (eggtrayInput && eggtrayChargeInput && resultInput) {
        const eggtrayValue = parseFloat( eggtrayInput.value ) || 0;
        const eggtrayChargeValue = parseFloat( eggtrayChargeInput.value ) || 0;

        const result = eggtrayValue * eggtrayChargeValue;

        resultInput.value = result === 0 ? "0.00" : result.toFixed(2);
        //updateGrandTotal();
    }
}

function calculateAndDisplay() {
    const rows = document.querySelectorAll( "table tr" );

    rows.forEach( row => {
        const traysInput = row.querySelector( "input[name*='_trays']" );
        const priceInput = row.querySelector( "input[name*='_price']" );

        if ( traysInput && priceInput ) {
            const traysValue = parseFloat( traysInput.value ) || 0;
            const priceValue = parseFloat( priceInput.value ) || 0;

            const result = traysValue * priceValue;

            const resultInput = row.querySelector( ".result .value" );
            if ( resultInput ) {
                resultInput.value = result === 0 ? "" : result.toFixed(2);
            }
        }
    } );

    sumAllResults();
}

function sumAllResults() {
    let total = 0;

    document.querySelectorAll( ".result .value" ).forEach( span => {
        const value = parseFloat( span.value.replace( /&#8369;/, "" ).trim() );
        if ( !isNaN( value ) ) {
            total += value;
        }
    } );

    const totalInput = document.getElementById( "eggtally_result" );
    if ( totalInput ) {
        totalInput.value = total === 0 ? "" : total.toFixed(2);
    }

    updateGrandTotal();
}

//Check if grandtotal_result is updated and call functions accordingly
function calculateDR() {
	var intervalId = setInterval( function() {
		var grandTotalInput = $( "#grandtotal_result" );
		if ( grandTotalInput.val() === "" || grandTotalInput.val() === "0.00" ) {
			clearInterval( intervalId );
	
			calculateAndDisplay();
			sumAllResults();
			calculateEggtrayTally();
			updateGrandTotal();
		}
		formatInputsInDR();
	}, 1000 );
}
//@================= END - CALCULATE  INVOICE

//@================= START -  PRICELIST TOGGLE
function toggleInput( select ) {
	const selectElement = select;
	const selectName = selectElement.name;
	const selectValue = selectElement.value;
	const show = selectValue == "1";

	const inputField = selectElement.parentElement.querySelector( "input" );
	const inputDiv = inputField ? inputField.nextElementSibling : null;

	if ( inputField ) {
		if ( selectValue === "1" && selectValue !== "" ) {
			inputField.required = true;
			inputField.value = "";
			if ( inputDiv ) {
			}
		} else {
			inputField.required = false;
			inputField.value = "0";
			if ( inputDiv ) {
			}
		}
	}

	if ( selectName === "pl_other_charges_sel" ) {
		const textareaField = selectElement.parentElement.nextElementSibling?.querySelector( "textarea" );
		if ( textareaField ) {
			if ( selectValue === "1" && selectValue !== "" ) {
				textareaField.value = "";
			} else {
				textareaField.value = "NA";
			}
		}
	}
}

document.querySelectorAll( ".modal select" ).forEach( function( select ) {
	toggleInput( select );
} );

document.querySelectorAll( ".modal select" ).forEach( function( select ) {
	select.addEventListener( "change", function() {
		toggleInput( this );
	} );
} );
//@================= END  -  PRICELIST TOGGLE

//@================= START  -  DR CONVERT TRAYS TO CRATES
function updateInputValue( input ) {
	var 	inputName = $( input ).attr( "name" );
				inputName = inputName.split( "_" )[1];
	var 	inputValue = parseFloat( $(input).val() ) || 0; 

    var toCrates = $( input ).closest( "td" ).prev( "td" ).find( "input" );
    if ( toCrates.length > 0 ) {
        var newCrates;
        if ( inputName === "jmb" || inputName === "xlr" || inputName === "b1" || inputName === "b2" || inputName === "b3" || inputName === "dirty" ) {
            newCrates = Math.floor( inputValue / 10 );
        } else {
            newCrates = Math.floor( inputValue / 12 );
        }
		
		if ( newCrates === 0 ) {
			toCrates.val( "" );
		} else {
			toCrates.val( newCrates );
		}  
    }
}
//@================= END  -  DR CONVERT TRAYS TO CRATES

//@================= START  -  ASSORTED TALLY CHECKER
function checkAssortedTotal() {
	let total = 0;

	const inputNames = [
		"drsi_ass_jmb_bd",
		"drsi_ass_xlr_bd",
		"drsi_ass_lrg_bd",
		"drsi_ass_med_bd",
		"drsi_ass_sml_bd",
		"drsi_ass_pul_bd",
		"drsi_ass_pwe_bd",
		"drsi_ass_spw_bd",
		"drsi_ass_b1_bd",
		"drsi_ass_b2_bd",
		"drsi_ass_b3_bd",
		"drsi_ass_dirty_bd"
	];

	inputNames.forEach( function( name ) {
		const value = parseFloat( $( `input[name="${name}"]` ).val() ) || 0;
		total += value;
	} );

	const assortedValue = parseFloat( $( `input[name="drsi_assorted"]` ).val() ) || 0;

	return total === assortedValue;
}

function checkOthersTotal() {
	let total = 0;

	const inputNames = [
		"drsi_oth_jmb_bd",
		"drsi_oth_xlr_bd",
		"drsi_oth_lrg_bd",
		"drsi_oth_med_bd",
		"drsi_oth_sml_bd",
		"drsi_oth_pul_bd",
		"drsi_oth_pwe_bd",
		"drsi_oth_spw_bd",
		"drsi_oth_b1_bd",
		"drsi_oth_b2_bd",
		"drsi_oth_b3_bd",
		"drsi_oth_dirty_bd"
	];

	inputNames.forEach( function( name ) {
		const value = parseFloat( $( `input[name="${name}"]` ).val() ) || 0;
		total += value;
	} );

	const assortedValue = parseFloat( $( `input[name="drsi_others"]` ).val() ) || 0;

	return total === assortedValue;
}
//@================= END  -  ASSORTED TALLY CHECKER

//@================= START  -  NEW DR DISABLE INPUTS
function disableInputsIfEmpty() {
	var customerName = $( "select[name='drsi_customer_name']" ).val();
	var effectivityDate = $( "select[name='drsi_effectivity_date']" ).val();

	if ( !customerName || !effectivityDate ) {
		$( "#MyTable_drsi tbody td" ).not( "tr td:first-child, .footer2 td:nth-child(4), tr:nth-child(13) td:nth-child(3), tr:nth-child(14) td:nth-child(3), .footer2 td:nth-child(3)" ).each( function() {
			$( this ).find( "input" ).prop( "disabled", true );
		} );
	} else {
		$( "#MyTable_drsi tbody td" ).not( "tr td:first-child, .footer2 td:nth-child(4), tr:nth-child(13) td:nth-child(3), tr:nth-child(14) td:nth-child(3), .footer2 td:nth-child(3)" ).each( function() {
			$( this ).find( "input" ).prop( "disabled", false );
		} );
	}
}
//@================= END  -  NEW DR DISABLE INPUTS

function formatInputsInDR() {
	$( "#MyTable_drsi input.value" ).each( function() {
		const value = parseFloat( $( this ).val().replace( /,/g, "" )) || "";
		if ( value !== "" ) {
			$( this ).val( value.toLocaleString( undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 } ) );
		} else {
			$( this ).val( "" );
		}
	} );
}

$( document ).ready( function() {	
	$( "input[name*='_trays'], input[name='drsi_eggtray_pcs']" ).on( "input", function() {
		if ( this.name === "drsi_eggtray_pcs" ) {
			calculateAndDisplay();
			sumAllResults();
			calculateEggtrayTally();
			updateGrandTotal();
		} else {
			calculateAndDisplay();
		}
		
		formatInputsInDR();
	} );

    function handleButtonClick( event ) {
        if ( !checkAssortedTotal() ) {
            event.preventDefault();
            alert( "Please ensure the total value on Assorted* matches with Assorted Trays Breakdown." );
        }
		
		if ( !checkOthersTotal() ) {
            event.preventDefault();
            alert( "Please ensure the total value on Others** matches with Others Breakdown." );
        }
    }

    // Bind the function to the buttons
    $("button[name='AddNew_DR'], button[name='Update_DR']").on( "click", handleButtonClick );

	$( "input[name*='_trays']" ).each( function() { 
		$( this ).on( "change", function() { 
			updateInputValue( this ); 
		} ); 
	} );
	
	$( "button[name='toggleBatchName']" ).on( 'click', function() {
		$( "#GraphTable, #GraphTable2, #GraphTable3" ).toggleClass( "hidden" );
	} );
	
	$( "button[name='AddNew_Customer']" ).on( "click", function() {
		$( ".modal-customer" ).find( "form" ).trigger( "reset" );
		
		$( ".modal-customer" ).modal( "show" );
	} );
	
	$( "button[name='AddNew_Pricelist']" ).on( "click", function() {
		$( ".modal-pl" ).find( "form" ).trigger( "reset" );
		
		$( "button[name='AddNew_PL']" ).show();
		$( "button[name='Update_PL'], button[name='Delete_PL']" ).hide();
		
		$( ".modal-pl" ).modal( "show" );
	} );
	
	$( "select[name='drsi_customer_name'], select[name='drsi_effectivity_date']" ).on( "change", function() {
        disableInputsIfEmpty();
    } );
	
    $( "button[name='AddNew_DeliveryReceipt']" ).on( "click", function() {
        $( ".modal-drsi" ).find( "form" ).trigger( "reset" );
        $( ".modal-drsi" ).find( "input, select" ).not( "input[name='drsi_date_created'], input[name='drsi_number']" ).val( "" );
		
		$( "input[name='drsi_number']" ).val( <?php echo json_encode($dr_number); ?> );
		$( "input[name='drsi_date_created'], select[name='drsi_customer_name'], select[name='drsi_effectivity_date'], input[name='drsi_number']" ).prop( "disabled", false );

        $( "button[name='AddNew_DR']" ).show();
		$( "button[name='PrintButton_DR'], button[name='Confirm_DR'], button[name='Update_DR'], button[name='Delete_DR']" ).hide();

        $( ".modal-drsi" ).modal( "show" );
    } );
		
	$( ".login" ).on( "click", function() {
		$( ".modal-login" ).find( "form" ).trigger( "reset" );
		$( ".modal-login" ).modal( "show" );
	} );
	
	$( ".register" ).on( "click", function() {
		$( ".modal-register" ).find( "form" ).trigger( "reset" );
		$( ".modal-register" ).modal( "show" );
	} );
	
	$( ".changepassword" ).on( "click", function() {
		$( ".modal-changepassword" ).find( "form" ).trigger( "reset" );
		$( ".modal-changepassword" ).modal( "show" );
	} );
	
    $( ".modal-login, .modal-register, .modal-changepassword" ).on( "hidden.bs.modal", function () {
        $( this ).find( "form" ).trigger( "reset" );
		$( this ).find( ".formMessage" ).html( "" );
    } );
	
	$( "#loginForm" ).on( "submit", function( e ) {
        e.preventDefault();

        $.ajax( {
            type: "POST",
            url: "login.php",
            data: $( this ).serialize(),
            dataType: "json", 
            success: function( response ) {
                if ( response.status === "success" ) {
                    window.location.replace( response.redirect );
                } else {
                    $( "#loginForm .formMessage" ).html( "<div class='alert alert-danger d-flex align-items-center shadow' role='alert'><h5>" + response.message + "</h5></div>" );
                }
            }
        } );
    } );
	
	$( "#cpForm" ).on( "submit", function( e ) {
		e.preventDefault();

		$.ajax( {
			url: "register_updatepassword.php",
			type: "POST",
			data: $( this ).serialize(),
			dataType: "json",
			success: function( response ) {
				$( "#cpForm .formMessage" ).html( "<div class='alert alert-" + ( response.status === "success" ? "success" : "danger" ) + "'>" + response.message + "</div>" );
			},
			error: function() {
				$( "#cpForm .formMessage" ).html( "<div class='alert alert-danger'>An error occurred while processing your request.</div>" );
			}
		} );
	} );
	
	$( "#regForm" ).on( "submit", function( e ) {
		e.preventDefault();
		
		$.ajax( {
			url: "register_updatepassword.php",
			type: "POST",
			data: $( this ).serialize(),
			dataType: "json",
			success: function( response ) {
				$( "#regForm .formMessage" ).html( "<div class='alert alert-" + ( response.status === "success" ? "success" : "danger" ) + "'>" + response.message + "</div>" );
			},
			error: function() {
				$( "#regForm .formMessage" ).html( "<div class='alert alert-danger'>An error occurred while processing your request.</div>" );
			}
		} );
	} );

	$( ".pl-clickable" ).on( "click", function() {
		$( ".modal-pl" ).find( "form" ).trigger( "reset" );
		
		var data_id = $( this ).data( "id" );
		var pValue = new URLSearchParams( window.location.search ).get( "p" );
		
		if ( pValue === "pl" ) 
		{
			$.ajax( {
				url: "plRowData.php",
				type: "GET",
				data: { 
					"data_id": data_id
				},
				success: function( data ) {
					try {
						var parsedData = JSON.parse( data );
						if ( parsedData.error ) {
							return;
						} else {	
							$( ".modal-pl input[name='pl_id']" ).val( parsedData.pl_id ).attr( "value", parsedData.pl_id );
							$( ".modal-pl input[name='pl_effectivity_date']" ).val( parsedData.pl_effectivity_date ).attr( "value", parsedData.pl_effectivity_date );
							$( ".modal-pl select[name='pl_customer_name']" ).val( parsedData.pl_customer_name ).attr( "value", parsedData.pl_customer_name );
							
							if ( parseInt( parsedData.pl_eggtray_charge ) !== 0 ) {
								$( ".modal-pl select[name='pl_eggtray_charge_sel']" ).val(1).attr( "value", 1 );
								$( ".modal-pl input[name='pl_eggtray_charge']" ).val( parsedData.pl_eggtray_charge ).attr( "value", parsedData.pl_eggtray_charge );
							} else {
								$( ".modal-pl select[name='pl_eggtray_charge_sel']" ).val(2).attr( "value", 2 );
								$( ".modal-pl input[name='pl_eggtray_charge']" ).val( parsedData.pl_eggtray_charge ).attr( "value", parsedData.pl_eggtray_charge );
							}
							
							if ( parseInt( parsedData.pl_shipping_charge ) !== 0 ) {
								$( ".modal-pl select[name='pl_shipping_charge_sel']" ).val(1).attr( "value", 1 );
								$( ".modal-pl input[name='pl_shipping_charge']" ).val( parsedData.pl_shipping_charge ).attr( "value", parsedData.pl_shipping_charge );
							} else {
								$( ".modal-pl select[name='pl_shipping_charge_sel']" ).val(2).attr( "value", 2 );
								$( ".modal-pl input[name='pl_shipping_charge']" ).val( parsedData.pl_shipping_charge ).attr( "value", parsedData.pl_shipping_charge );
							}
							
							if ( parseInt( parsedData.pl_other_charges ) !== 0 ) {
								$( ".modal-pl select[name='pl_other_charges_sel']" ).val(1).attr( "value", 1 );
								$( ".modal-pl input[name='pl_other_charges']" ).val( parsedData.pl_other_charges ).attr( "value", parsedData.pl_other_charges );
								$( ".modal-pl textarea[name='pl_other_charges_remark']" ).val( parsedData.pl_other_charges_remark ).attr( "value", parsedData.pl_other_charges_remark );
							} else {
								$( ".modal-pl select[name='pl_other_charges_sel']" ).val(2).attr( "value", 2 );
								$( ".modal-pl input[name='pl_other_charges']" ).val( parsedData.pl_other_charges ).attr( "value", parsedData.pl_id );
								$( ".modal-pl textarea[name='pl_other_charges_remark']" ).val( parsedData.pl_other_charges_remark ).attr( "value", parsedData.pl_other_charges_remark );
							}
							
							$( ".modal-pl input[name='pl_JMB']" ).val( parsedData.pl_JMB ).attr( "value", parsedData.pl_JMB );
							$( ".modal-pl input[name='pl_XLR']" ).val( parsedData.pl_XLR ).attr( "value", parsedData.pl_XLR );
							$( ".modal-pl input[name='pl_LRG']" ).val( parsedData.pl_LRG ).attr( "value", parsedData.pl_LRG );
							$( ".modal-pl input[name='pl_MED']" ).val( parsedData.pl_MED ).attr( "value", parsedData.pl_MED );
							$( ".modal-pl input[name='pl_SML']" ).val( parsedData.pl_SML ).attr( "value", parsedData.pl_SML );
							$( ".modal-pl input[name='pl_PUL']" ).val( parsedData.pl_PUL ).attr( "value", parsedData.pl_PUL );
							$( ".modal-pl input[name='pl_PWE']" ).val( parsedData.pl_PWE ).attr( "value", parsedData.pl_PWE );
							$( ".modal-pl input[name='pl_SPW']" ).val( parsedData.pl_SPW ).attr( "value", parsedData.pl_SPW );
							$( ".modal-pl input[name='pl_B1']" ).val( parsedData.pl_B1 ).attr( "value", parsedData.pl_B1 );
							$( ".modal-pl input[name='pl_B2']" ).val( parsedData.pl_B2 ).attr( "value", parsedData.pl_B2 );
							$( ".modal-pl input[name='pl_B3']" ).val( parsedData.pl_B3 ).attr( "value", parsedData.pl_B3 );
							$( ".modal-pl input[name='pl_Dirty']" ).val( parsedData.pl_Dirty ).attr( "value", parsedData.pl_Dirty );
							
							$( "button[name='AddNew_PL']" ).hide();
							$( "button[name='Update_PL'], button[name='Delete_PL']" ).show();
							$( ".modal-pl" ).modal( "show" );
						}
					} catch ( e ) {
						return;
					}
				},
				error: function() {
					alert( "Error: "+ response.message );
				}
			} );
		}
	} );
	
	// TRIGGER CHANGE TO POPULATE
	$( ".modal-drsi" ).on( "shown.bs.modal", function() {
		$( "select[name='drsi_customer_name'], select[name='drsi_effectivity_date']" ).trigger( "change" );
	} );	
	
    $( "select[name='drsi_customer_name']" ).on( "change", function() {
		var pValue = new URLSearchParams( window.location.search ).get( "p" );
		
		if ( pValue === "dr" ) 
		{
			$.ajax( {
				url: "get_effectivity_date.php",
				type: "POST",
				data: { 
					drsi_customer_name: $( this ).val()
				},
				success: function( data ) {
					$( "select[name='drsi_effectivity_date']" ).html( data ).trigger( "change" );
				},
				error: function() {
					$( ".dispMessage" ).html( "<di v class='alert alert-danger'>" + response.message + "</div>" );
				}
			} );
		}
    } );

	$( "select[name='drsi_effectivity_date']" ).on( "change", debounce( function() {
		var pValue = new URLSearchParams( window.location.search ).get( "p" );
		
		if ( pValue === "dr" ) 
		{
			$.ajax( {
				url: "pop_effectivity_date.php",
				type: "POST",
				data: {
					drsi_customer_name: $( "select[name='drsi_customer_name']" ).val(),
					drsi_effectivity_date: $( this ).val()
				},
				success: function( data ) {
					try {
						var parsedData = JSON.parse( data );
						if ( parsedData.error ) {
							return;
						} else {
							$( ".modal-drsi input[name='drsi_eggtray_charge']" ).val( parsedData.pl_eggtray_charge ).attr( "value", parsedData.pl_eggtray_charge );
							if( parsedData.pl_eggtray_charge != 0.00 ) {
								$( ".modal-drsi input[name='drsi_eggtray_pcs']" ).closest("td").parent().show();
							} else {
								$( ".modal-drsi input[name='drsi_eggtray_pcs']" ).closest("td").parent().hide();
							}
							
							$( ".modal-drsi input[name='drsi_shipping_charge']" ).val( parsedData.pl_shipping_charge ).attr( "value", parsedData.pl_shipping_charge );
							if( parsedData.pl_shipping_charge != 0.00 ) {
								$( ".modal-drsi input[name='drsi_shipping_charge']" ).closest("td").parent().show();
							} else {
								$( ".modal-drsi input[name='drsi_shipping_charge']" ).closest("td").parent().hide();
							}
							
							$( ".modal-drsi input[name='drsi_other_charges']" ).val( parsedData.pl_other_charges ).attr( "value", parsedData.pl_other_charges );
							if( parsedData.pl_other_charges != 0.00 ) {
								$( ".modal-drsi input[name='drsi_other_charges']" ).closest("td").parent().show();
							} else {
								$( ".modal-drsi input[name='drsi_other_charges']" ).closest("td").parent().hide();
							}
							
							$( ".modal-drsi input[name='si_jmb_price']" ).val( parsedData.pl_JMB ).attr( "value", parsedData.pl_JMB );
							$( ".modal-drsi input[name='si_xlr_price']" ).val( parsedData.pl_XLR ).attr( "value", parsedData.pl_XLR );
							$( ".modal-drsi input[name='si_lrg_price']" ).val( parsedData.pl_LRG ).attr( "value", parsedData.pl_LRG );
							$( ".modal-drsi input[name='si_med_price']" ).val( parsedData.pl_MED ).attr( "value", parsedData.pl_MED );
							$( ".modal-drsi input[name='si_sml_price']" ).val( parsedData.pl_SML ).attr( "value", parsedData.pl_SML );
							$( ".modal-drsi input[name='si_pul_price']" ).val( parsedData.pl_PUL ).attr( "value", parsedData.pl_PUL );
							$( ".modal-drsi input[name='si_pwe_price']" ).val( parsedData.pl_PWE ).attr( "value", parsedData.pl_PWE );
							$( ".modal-drsi input[name='si_spw_price']" ).val( parsedData.pl_SPW ).attr( "value", parsedData.pl_SPW );
							$( ".modal-drsi input[name='si_b1_price']" ).val( parsedData.pl_B1 ).attr( "value", parsedData.pl_B1 );
							$( ".modal-drsi input[name='si_b2_price']" ).val( parsedData.pl_B2 ).attr( "value", parsedData.pl_B2 );
							$( ".modal-drsi input[name='si_b3_price']" ).val( parsedData.pl_B3 ).attr( "value", parsedData.pl_B3 );
							$( ".modal-drsi input[name='si_dirty_price']" ).val( parsedData.pl_Dirty ).attr( "value", parsedData.pl_Dirty );
						}
					} catch ( e ) {
						return;
					}
				},
				error: function() {
					$( ".dispMessage" ).html( "<div class='alert alert-danger'>" + response.message + "</div>" );
				}
			} );	
		}
	}, 300 ) );
	
	$( ".dr-clickable" ).on( "click", function() {
		$( ".modal-drsi" ).find( "form" ).trigger( "reset" );

		var data_id = $( this ).data( "id" );
		var data_status = $( this ).data( "status" );
		var pValue = new URLSearchParams( window.location.search ).get( "p" );
		var userType = <?php echo json_encode($userType); ?>;
		
		if ( pValue === "dr" ) 
		{
			$.ajax( {
				url: "drRowData.php",
				type: "GET",
				data: { 
					"data_id" : data_id
				},
				success: function( data ) {
					try {
						var parsedData = JSON.parse( data );
						if ( parsedData.error ) {
							return;
						} else {
							$( ".modal-drsi input[name='drsi_id']" ).val( parsedData.dr_id ).attr( "value", parsedData.dr_id );
							$( ".modal-drsi input[name='drsi_date_created']" ).val( parsedData.dr_date_created ).attr( "value", parsedData.dr_date_created );

							// Populate and set the customer name select element
							var $customerNameSelect = $( ".modal-drsi select[name='drsi_customer_name']" );
							$customerNameSelect.html( parsedData.optionsHtmlCustomerName );
							$customerNameSelect.val( parsedData.dr_customer_name );

							// Ensure correct option is selected by setting "selected" attribute explicitly
							$customerNameSelect.find( "option" ).each( function() {
								if ( $( this ).val() === parsedData.dr_customer_name ) {
									$( this ).attr( "selected", true );
								} else {
									$( this ).removeAttr( "selected" );
								}
							} );

							var $effectivityDateSelect = $( ".modal-drsi select[name='drsi_effectivity_date']" );

							// Use MutationObserver to detect changes and set the value
							var observer = new MutationObserver( function( mutations ) {
								mutations.forEach( function( mutation ) {
									if ( mutation.type === "childList" && mutation.addedNodes.length > 0 ) {
										// Set the value
										$effectivityDateSelect.val( parsedData.dr_effectivity_date ).change();

										// Add the "selected" attribute
										$effectivityDateSelect.find( "option" ).each( function() {
											if ( $( this ).val() === parsedData.dr_effectivity_date ) {
												$( this ).attr( "selected", true );
											} else {
												$( this ).removeAttr( "selected" );
											}
										} );

										// Disconnect the observer
										observer.disconnect();
									}
								} );
							} );

							observer.observe( $effectivityDateSelect[0], { childList: true } );

							// Populate the options list (this should trigger the observer)
							$effectivityDateSelect.html( parsedData.optionsHtml );
							
							$( ".modal-drsi input[name='drsi_number']" ).val( parsedData.dr_number ).attr( "value", parsedData.dr_number );
							
							$( ".modal-drsi input[name='drsi_receiver']" ).val( parsedData.receiver ).attr( "value", parsedData.receiver );
							$( ".modal-drsi input[name='drsi_received_date']" ).val( parsedData.received_date ).attr( "value", parsedData.received_date );
							
							$( ".modal-drsi input[name='drsi_eggtray_pcs']" ).val( parsedData.dr_eggtray_pcs ).attr( "value", parsedData.dr_eggtray_pcs );
							$( ".modal-drsi input[name='drsi_eggtray_charge']" ).val( parsedData.dr_eggtray_charge ).attr( "value", parsedData.dr_eggtray_charge );
							
							$( ".modal-drsi input[name='drsi_jmb_crates']" ).val( parsedData.dr_jmb_crates ).attr( "value", parsedData.dr_jmb_crates );
							$( ".modal-drsi input[name='drsi_jmb_trays']" ).val( parsedData.dr_jmb_trays ).attr( "value", parsedData.dr_jmb_trays );

							$( ".modal-drsi input[name='drsi_xlr_crates']" ).val( parsedData.dr_xlr_crates ).attr( "value", parsedData.dr_xlr_crates );
							$( ".modal-drsi input[name='drsi_xlr_trays']" ).val( parsedData.dr_xlr_trays ).attr( "value", parsedData.dr_xlr_trays );
							
							$( ".modal-drsi input[name='drsi_lrg_crates']" ).val( parsedData.dr_lrg_crates ).attr( "value", parsedData.dr_lrg_crates );
							$( ".modal-drsi input[name='drsi_lrg_trays']" ).val( parsedData.dr_lrg_trays ).attr( "value", parsedData.dr_lrg_trays );
							
							$( ".modal-drsi input[name='drsi_med_crates']" ).val( parsedData.dr_med_crates ).attr( "value", parsedData.dr_med_crates );
							$( ".modal-drsi input[name='drsi_med_trays']" ).val( parsedData.dr_med_trays ).attr( "value", parsedData.dr_med_trays );
							
							$( ".modal-drsi input[name='drsi_sml_crates']" ).val( parsedData.dr_sml_crates ).attr( "value", parsedData.dr_sml_crates );
							$( ".modal-drsi input[name='drsi_sml_trays']" ).val( parsedData.dr_sml_trays ).attr( "value", parsedData.dr_sml_trays );
							
							$( ".modal-drsi input[name='drsi_pul_crates']" ).val( parsedData.dr_pul_crates ).attr( "value", parsedData.dr_pul_crates );
							$( ".modal-drsi input[name='drsi_pul_trays']" ).val( parsedData.dr_pul_trays ).attr( "value", parsedData.dr_pul_trays );
							
							$( ".modal-drsi input[name='drsi_pwe_crates']" ).val( parsedData.dr_pwe_crates ).attr( "value", parsedData.dr_pwe_crates );
							$( ".modal-drsi input[name='drsi_pwe_trays']" ).val( parsedData.dr_pwe_trays ).attr( "value", parsedData.dr_pwe_trays );
							
							$( ".modal-drsi input[name='drsi_spw_crates']" ).val( parsedData.dr_spw_crates ).attr( "value", parsedData.dr_spw_crates );
							$( ".modal-drsi input[name='drsi_spw_trays']" ).val( parsedData.dr_spw_trays ).attr( "value", parsedData.dr_spw_trays );
							
							$( ".modal-drsi input[name='drsi_b1_crates']" ).val( parsedData.dr_b1_crates ).attr( "value", parsedData.dr_b1_crates );
							$( ".modal-drsi input[name='drsi_b1_trays']" ).val( parsedData.dr_b1_trays ).attr( "value", parsedData.dr_b1_trays );
							
							$( ".modal-drsi input[name='drsi_b2_crates']" ).val( parsedData.dr_b2_crates ).attr( "value", parsedData.dr_b2_crates );
							$( ".modal-drsi input[name='drsi_b2_trays']" ).val( parsedData.dr_b2_trays ).attr( "value", parsedData.dr_b2_trays );
							
							$( ".modal-drsi input[name='drsi_b3_crates']" ).val( parsedData.dr_b3_crates ).attr( "value", parsedData.dr_b3_crates );
							$( ".modal-drsi input[name='drsi_b3_trays']" ).val( parsedData.dr_b3_trays ).attr( "value", parsedData.dr_b3_trays );
							
							$( ".modal-drsi input[name='drsi_dirty_crates']" ).val( parsedData.dr_dirty_crates ).attr( "value", parsedData.dr_dirty_crates );
							$( ".modal-drsi input[name='drsi_dirty_trays']" ).val( parsedData.dr_dirty_trays ).attr( "value", parsedData.dr_dirty_trays );
							
							$( ".modal-drsi input[name='drsi_assorted']" ).val( parsedData.dr_assorted ).attr( "value", parsedData.dr_assorted );
							$( ".modal-drsi input[name='drsi_others']" ).val( parsedData.dr_others ).attr( "value", parsedData.dr_others );
							
							$( ".modal-drsi input[name='drsi_ass_jmb_bd']" ).val( parsedData.dr_ass_jmb_bd ).attr( "value", parsedData.dr_ass_jmb_bd );
							$( ".modal-drsi input[name='drsi_ass_xlr_bd']" ).val( parsedData.dr_ass_xlr_bd ).attr( "value", parsedData.dr_ass_xlr_bd );
							$( ".modal-drsi input[name='drsi_ass_lrg_bd']" ).val( parsedData.dr_ass_lrg_bd ).attr( "value", parsedData.dr_ass_lrg_bd );
							$( ".modal-drsi input[name='drsi_ass_med_bd']" ).val( parsedData.dr_ass_med_bd ).attr( "value", parsedData.dr_ass_med_bd );
							$( ".modal-drsi input[name='drsi_ass_sml_bd']" ).val( parsedData.dr_ass_sml_bd ).attr( "value", parsedData.dr_ass_sml_bd );
							$( ".modal-drsi input[name='drsi_ass_pul_bd']" ).val( parsedData.dr_ass_pul_bd ).attr( "value", parsedData.dr_ass_pul_bd );
							$( ".modal-drsi input[name='drsi_ass_pwe_bd']" ).val( parsedData.dr_ass_pwe_bd ).attr( "value", parsedData.dr_ass_pwe_bd );
							$( ".modal-drsi input[name='drsi_ass_spw_bd']" ).val( parsedData.dr_ass_spw_bd ).attr( "value", parsedData.dr_ass_spw_bd );
							$( ".modal-drsi input[name='drsi_ass_b1_bd']" ).val( parsedData.dr_ass_b1_bd ).attr( "value", parsedData.dr_ass_b1_bd );
							$( ".modal-drsi input[name='drsi_ass_b2_bd']" ).val( parsedData.dr_ass_b2_bd ).attr( "value", parsedData.dr_ass_b2_bd );
							$( ".modal-drsi input[name='drsi_ass_b3_bd']" ).val( parsedData.dr_ass_b3_bd ).attr( "value", parsedData.dr_ass_b3_bd );
							$( ".modal-drsi input[name='drsi_ass_dirty_bd']" ).val( parsedData.dr_ass_dirty_bd ).attr( "value", parsedData.dr_ass_dirty_bd );
							$( ".modal-drsi input[name='drsi_oth_jmb_bd']" ).val( parsedData.dr_oth_jmb_bd ).attr( "value", parsedData.dr_oth_jmb_bd );
							$( ".modal-drsi input[name='drsi_oth_xlr_bd']" ).val( parsedData.dr_oth_xlr_bd ).attr( "value", parsedData.dr_oth_xlr_bd );
							$( ".modal-drsi input[name='drsi_oth_lrg_bd']" ).val( parsedData.dr_oth_lrg_bd ).attr( "value", parsedData.dr_oth_lrg_bd );
							$( ".modal-drsi input[name='drsi_oth_med_bd']" ).val( parsedData.dr_oth_med_bd ).attr( "value", parsedData.dr_oth_med_bd );
							$( ".modal-drsi input[name='drsi_oth_sml_bd']" ).val( parsedData.dr_oth_sml_bd ).attr( "value", parsedData.dr_oth_sml_bd );
							$( ".modal-drsi input[name='drsi_oth_pul_bd']" ).val( parsedData.dr_oth_pul_bd ).attr( "value", parsedData.dr_oth_pul_bd );
							$( ".modal-drsi input[name='drsi_oth_pwe_bd']" ).val( parsedData.dr_oth_pwe_bd ).attr( "value", parsedData.dr_oth_pwe_bd );
							$( ".modal-drsi input[name='drsi_oth_spw_bd']" ).val( parsedData.dr_oth_spw_bd ).attr( "value", parsedData.dr_oth_spw_bd );
							$( ".modal-drsi input[name='drsi_oth_b1_bd']" ).val( parsedData.dr_oth_b1_bd ).attr( "value", parsedData.dr_oth_b1_bd );
							$( ".modal-drsi input[name='drsi_oth_b2_bd']" ).val( parsedData.dr_oth_b2_bd ).attr( "value", parsedData.dr_oth_b2_bd );
							$( ".modal-drsi input[name='drsi_oth_b3_bd']" ).val( parsedData.dr_oth_b3_bd ).attr( "value", parsedData.dr_oth_b3_bd );
							$( ".modal-drsi input[name='drsi_oth_dirty_bd']" ).val( parsedData.dr_oth_dirty_bd ).attr( "value", parsedData.dr_oth_dirty_bd );
							
							calculateDR();
							
							$( "button[name='AddNew_DR']" ).hide();
						
							if( userType !== 3 ) {
								$( "button[name='Delete_DR']" ).hide();
							} else {
								$( "button[name='Delete_DR']" ).show();
							}
							
							var intervalId = setInterval( function() {
								var modal = $( ".modal-drsi" );
								var isDisabled = modal.find( "input, select" ).prop( "disabled" );
								
								if ( isDisabled === false ) {
									clearInterval( intervalId );
									//data_status = 1 'Pending'
									//data_status = 2 'Done'
									//dr_type = 1 'Delivery'
									//dr_type = 2 'Invoice'
									if ( data_status === 1 ) {
										modal.find( "thead tr th" ).find( "input, select" ).prop( "disabled", true );
										
										$( "button[name='PrintButton_DR']" ).hide();
										$( "button[name='Confirm_DR'], button[name='Update_DR']" ).show();
									} else {
										modal.find( "thead tr th, tbody tr td, tfoot tr td" ).find( "input, select" ).prop( "disabled", true );
									
										$( "button[name='PrintButton_DR']" ).show();
										$( "button[name='Confirm_DR'], button[name='Update_DR']" ).hide();
									}
								} 
							}, 100 );
							
							$( ".modal-drsi" ).modal( "show" );
						}
					} catch ( e ) {
						return;
					}
				},
				error: function() {
					alert( "Error: "+ response.message );
				}
			} );
		}
	} );

	var refreshMessagesInterval;

	$( "#chatModal" ).on( "shown.bs.modal", function() {
		if ( !refreshMessagesInterval ) {
			loadMessages();
			refreshMessagesInterval = setInterval( loadMessages, 5000 ); 
		}
	} );

	$( "#chatModal" ).on( "hidden.bs.modal", function() {
		clearInterval( refreshMessagesInterval );
		refreshMessagesInterval = null; 
	} );

	$( "#chat-form" ).submit( function ( e ) {
		e.preventDefault();
		var username = $( "#username" ).val();
		var message = $( "#message" ).val();

		$.post( "save_message.php", { username: username, message: message }, function () {
			$( "#message" ).val( "" );
			loadMessages();
		} );
	} );
	
	$( "#message" ).on( "keydown", function() {
		clearInterval( refreshMessagesInterval );
		refreshMessagesInterval = null;
	} ).on( "keyup", function() {
		if ( !refreshMessagesInterval ) {
			refreshMessagesInterval = setInterval( loadMessages, 5000 );
		}
	} );

	function loadMessages() {
		$.get( "load_messages.php", function ( data ) {
			$( "#chat-box" ).html( data );
		} );
	}
} );
</script>
</body>
<?php
require_once("NewCustomerName.php");
require_once("NewPriceList.php");
require_once("NewTransactions.php");
require_once("DeleteTransactions.php");

if (isset($_GET["p"]) && $_GET["p"] === "dr" && !isset($userType)) {
	header("Location: dashboard.php?p=home");
	exit();
}

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