<script>
	// function getTotalQuantity(counter) {
	// 	var selectedMedicine = $('#medicine' + counter).val();

	// 	console.log("Selected medicine ID: " + selectedMedicine); // Debugging line

	// 	$.ajax({
	// 		type: "POST",
	// 		url: "stock_update.php",
	// 		dataType: "json",
	// 		data: { medicine_id: selectedMedicine, row_id: counter },
	// 		success: function (response) {
	// 			console.log(response);
	// 			if (response.error) {
	// 				alert('Error: ' + response.error);
	// 			} else {
	// 				$('#total_qty' + counter).val(response.total_quantity || 'Not available');
	// 			}
	// 		},
	// 		error: function (jqXHR, textStatus, errorThrown) {
	// 			console.error('AJAX error: ' + textStatus + ', ' + errorThrown);
	// 		}
	// 	});
	// }


	// Aasish add the Function to fetch total quantity using AJAX

	function checkIssuedConsumeQty(counter) {
		console.log(counter);

		if (counter === null || counter === '') {
			var count = $("#count_items1").val();

			for (var i = 0; i < count; i++) {

				var medicine = $("#medicine").val();
				if (medicine !== undefined) {

					var issued_qty = $("#issued_qty" + i).val();
					var total_qty = $("#total_qty" + i).val();

					if (total_qty < issued_qty) {
						BootstrapDialog.alert("Stock Is Not Available !!");
					}
					if (issued_qty < 0) {
						BootstrapDialog.alert("Issued Qty Cant be Negative!!");
					}
				}
			}
		} else {
			var apt_id = $("#appointment_id").val();
			var item_id = $("#medicine" + counter).val();
			var batch = $("#consum_item_batch_no" + counter).val();
			var miscellaneous = 'N';
			$.ajax({
				type: 'post',
				url: 'get_prev_issue_mis_qty.php',
				data: {
					apt_id: apt_id,
					item_id: item_id,
					item_batch_no: batch,
					miscellaneous: miscellaneous
				},
				success: function (data) {
					try {
						data = JSON.parse(data);

						var curr_issued_qty = parseInt($("#issued_qty" + counter).val());

						var prev_issue = parseInt(data);
						if(isNaN(prev_issue) || prev_issue === undefined || prev_issue === '') { prev_issue = 0; }

						var total_qty = parseInt($("#total_qty" + counter).val());
						if (isNaN(total_qty) || total_qty === undefined || total_qty === '') { total_qty = 0; }

						console.log(" curr qty " + curr_issued_qty + " total avl with prev issue " + (total_qty + prev_issue));

						if ((total_qty + prev_issue) < curr_issued_qty) {
							BootstrapDialog.alert("You are adding more than available stock please be careful !!");
							$("#issued_qty" + counter).val('');
						}
						if (curr_issued_qty < 0) {
							BootstrapDialog.alert("Issue Qty Cant be Negative!!");
							$('#issued_qty' + counter).val('');
						}
					} catch (err) { }

				},
				error: function (data) {

				}
			});
		}
	}



	function save_consume() {
		$.ajax({
			url: 'save_consumables.php',
			type: "POST",
			data: $("#consume_form").serialize(),
			success: function (data) {


				BootstrapDialog.alert('Details Saved Successfully.');

			},
			error: function (data) {
				BootstrapDialog.alert('Error Saving Details');
				//return;
			}
		});
	}
	function setConsumableItemBatchNo(count, batch) {
		var item_id = $('#medicine' + count).val();
		$.ajax({
			url: 'get_item_batch_nos.php',
			type: 'POST',
			data: {
				item_id: item_id,
				batch: batch,
			},
			dataType: 'json',
			success: function (data) {
				var content_item_batch =
					"<option value=\"\" selected disabled >Please Select Batch No</option>";
				var total_qty = 0;
				if (data != null && data != "") {
					item_batch = data;
					for (var i = 0; i < data.length; i++) {
						var select = '';

						if ((batch == '' || batch == null) && i == 0) {
							select = 'selected';
						}
						if (batch == data[i].item_batch_no) {
							select = 'selected';
						}
						const expiryDate = new Date(data[i].expiry_date);
						const currentDate = new Date();
						const sixtyDaysLater = new Date(currentDate);
						sixtyDaysLater.setDate(currentDate.getDate() + 60);

						// Check if expiry is within the next 60 days
						if (expiryDate > currentDate && expiryDate <= sixtyDaysLater) {
							console.log("Alert condition reached.");
							BootstrapDialog.alert("This " + data[i].item_batch_no + " batch no has expiry within the next 60 days");
						}

						total_qty += parseInt(data[i].stock_qty);
						content_item_batch += "<option value='" + data[i].item_batch_no + "' " + select + ">" +
							data[i]
								.item_batch_no + " (Expiry Date:" + myDateFormaterMonthYear(data[i].expiry_date) +
							", Stock Qty:" + data[i].stock_qty + ")</option>"
					}
				}
				$('#total_qty' + count).val(total_qty || 'Not available');
				$("#consum_item_batch_no" + count).html(content_item_batch);
			},
			error: function (data) { }
		});
	}

</script>
<div class="modal fade" id="consumables" role="dialog" aria-hidden="true">
	<div class="modal-dialog modal-lg">

		<div class="modal-content">
			<div class="modal-header">

			</div>
			<form role="form" id="consume_form" name="consume_form" action="#" method="post">
				<div class="modal-body">


					<div class="row">
						<div class="col-sm-12 table-responsive">
							<table id="intake_table" class="table table-striped table-bordered ordered-list"
								style="padding: 2px; margin: 2px;">
								<thead>
									<h3>
										<center>CONSUMABLES</center>
									</h3>
									<tr class="success">
										<!-- <th style="font-size: 9px; text-align: center;">Time</th> -->
										<th style="font-size: 9px; text-align: center;">Item</th>
										<th style="font-size: 9px; text-align: center;">Batch</th>
										<!-- Aasish -->
										<th style="font-size: 9px; text-align: center;">Available qty</th>
										<!-- Aasish -->
										<th style="font-size: 9px; text-align: center;">Issued qty</th>
										<th style="font-size: 9px; text-align: center;"></th>

									</tr>
								</thead>


								<tbody>

									<?php $i = 0;
									$row = null;
									if (isset($_REQUEST['appointmentId'])) {
										$sql_intake = "select * from opd_consumables where consume_id ='" . $_REQUEST['appointmentId'] . "'";
										error_log("ksfjckesncf" . $sql_intake);
										$result_intake = mysqli_query($conn, $sql_intake);
										$num_intake = @mysqli_num_rows($result_intake);
										$row_intake = @mysqli_fetch_array($result_intake);
									}
									do {
										?>


										<tr>

											<td style="width:20%">
												<select class="form-control select2" id="medicine<?php echo $i ?>"
													name="medicine<?php echo $i ?>" data-placeholder="Choose a item..."
													style="width: 100%;"
													onchange="setConsumableItemBatchNo('<?php echo $i ?>','<?= $row_intake['consum_item_batch_no'] ?>')">
													<option value=""></option>
													<?php echo generate_options("SELECT item_id,trim(concat(ifnull(form_name,''),' ',item_name)) item_name FROM tbl_items i left join medicine_form f on i.item_form_id=f.form_id  where status='1' and is_prescription!='1' and cat='11' order by item_name", $row_intake['medicine'], 'item_id', 'item_name', '', ''); ?>

												</select>

											</td>
											<td style="width:20%">
												<select onchange='' name="consum_item_batch_no<?php echo $i; ?>"
													id="consum_item_batch_no<?php echo $i; ?>" class="form-control">
													<option value="" selected>Batches</option>
												</select>
											</td>
											<!-- Aasish -->
											<td style="width:20%">
												<input class="form-control" value="<?php echo $total_quantity; ?>"
													name="total_qty<?php echo $i; ?>" id="total_qty<?php echo $i; ?>"
													type="text" readonly />
											</td>
											<!-- Aasish -->

											<td style="width:20%">
												<input class="form-control" value="<?php echo $row_intake['issued_qty'] ?>"
													name="issued_qty<?php echo $i ?>" id="issued_qty<?php echo $i ?>"
													type="number" oninput="checkIssuedConsumeQty(<?php echo $i ?>)" />


											</td>


											<td style="width:20%; text-align:center">
												<a href="#" class="btn-lg" data-toggle="tooltip" id="deletebtn"
													title="Delete"><span class="glyphicon glyphicon-trash"></span></a>
											</td>

										</tr>
										<script>
											setConsumableItemBatchNo('<?php echo $i ?>', '<?= $row_intake['consum_item_batch_no'] ?>');
											// getTotalQuantity(<?php //echo $i; ?>);
										</script>

										<?php

										$i++;
									} while ($row_intake = @mysqli_fetch_array($result_intake)) //end of while
									?>


								</tbody>

								<tfoot>
									<tr>
										<td colspan="4" style="text-align: center; width:100%">
											<button type="button" class="btn btn-block btn-primary btn-sm"
												id="addrow1">Add Consumable</button>
											<input type="hidden" name="count_items1" id="count_items1"
												value="<?php echo $i ?>" />
											<input id="appointment_id" type="hidden" style="height: 30px"
												class="form-control" name="appointment_id"
												value="<?php echo $_REQUEST['appointmentId'] ?>" />

											<input id="emp_id" name="emp_id" type="hidden" value="<?php if ($row['emp_id'] != '' || $row['emp_id'] != null) {
												$emp_id = $row['emp_id'];
												echo $row['emp_id'];
											} else {
												$emp_id = $_REQUEST['emp_id'];
												echo $_REQUEST['emp_id'];
											} ?>" />

										</td>
									</tr>
									<tr>
									</tr>
								</tfoot>


							</table>
						</div>
					</div>

				</div>
				<div class="modal-footer">

					<button type="button" class="btn btn-info btn-sm save_button" onclick="save_consume();">
						SAVE
					</button>

					<button type="button" class="btn btn-danger  btn-sm" data-dismiss="modal">
						<i class="ace-icon fa fa-times bigger-110"></i>CANCEL
					</button>
				</div>
			</form>

		</div>
	</div>

</div>


<script type="text/javascript">
	$(document).ready(function () {

		var itemOptions = "<?php echo generate_options("SELECT item_id,trim(concat(ifnull(form_name,''),' ',item_name)) item_name FROM tbl_items i left join medicine_form f on i.item_form_id=f.form_id  where status='1' and is_prescription!='1' and cat='11' order by item_name", $row_treatment['item_id'], 'item_id', 'item_name', '', ''); ?> ";


		$("#addrow1").on("click", function () {
			var newRow = $("<tr>");
			var counter = $("#count_items1").val();
			var cols = "";
			var select_treatment = "";
			select_treatment += "<select ";
			select_treatment += 'onchange= " setConsumableItemBatchNo(`' + counter + '`,``)"';
			select_treatment += "id=\"medicine" + counter + "\"name=\"medicine" + counter + "\"  data-placeholder=\"Choose a item...\"  class=\"form-control select2\"  style=\"width: 100%;\" ";
			//select_treatment+="style=\"display: none;\"";
			select_treatment += ">";

			select_treatment += "<option value=\"\">  </option>";
			select_treatment += itemOptions
			select_treatment += "</select>";


			cols += '<td>' + select_treatment + '</td><td style="width:20%"><select name="consum_item_batch_no' + counter + '" id="consum_item_batch_no' + counter + '" class="form-control"><option value="" selected>Batches</option></select></td>';

			cols += '<td><input type="text" readonly class="form-control" id="total_qty' + counter + '" name="total_qty' + counter + '"/></td>';

			cols += '<td><input type="number" class="form-control" oninput=checkIssuedConsumeQty(`' + counter + '`) id="issued_qty' + counter + '" name="issued_qty' + counter + '"/></td>';

			cols += '<td align="center"><a href="#" class="btn-lg" data-toggle="tooltip" id="deletebtn" title="Delete"><span class="glyphicon glyphicon-trash"></span></a></td>';

			newRow.append(cols);
			$("#intake_table").append(newRow);
			/*$('#item_id'+counter).chosen({allow_single_deselect:true}); 
			$('#item_id'+counter).next().css({'width': $('#item_id'+counter).parent().width()});*/

			$('.date-picker').datepicker({
				autoclose: true,
				todayHighlight: true
			})
			$('#consume_time' + counter).datetimepicker({
				format: 'DD/MM/YYYY h:mm A', //use this option to display seconds
				defaultDate: new Date(),
				maxDate: new Date(),
				icons: {
					time: 'fa fa-clock-o',
					date: 'fa fa-calendar',
					up: 'fa fa-chevron-up',
					down: 'fa fa-chevron-down',
					previous: 'fa fa-chevron-left',
					next: 'fa fa-chevron-right',
					today: 'fa fa-arrows',
					clear: 'fa fa-trash',
					close: 'fa fa-times'
				}
			}).next().on(ace.click_event, function () {
				$(this).prev().focus();
			});

			counter++;
			$('.select2').select2()
			$("#count_items1").val(counter);
		});



		$("#intake_table").on("click", "#deletebtn", function (event) {
			$(this).closest("tr").remove();
			// counter -= 1
			// $("#count_items1").val(counter);
		});
		$('.select2').select2()

	});

	// Aasish add the Function to fetch total quantity using AJAX

</script>