<script>
    // function getTotalQuantityMiscellaneous(counter) {
    //     var selectedMedicine = $('#miscellaneous_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) {
    //                 BootstrapDialog.alert('Error: ' + response.error);
    //             } else {
    //                 $('#miscellaneous_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 checkIssuedQty(counter) {
        console.log(counter);

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

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

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

                    var issued_qty = $("#miscellaneous_issued_qty" + i).val();
                    var total_qty = $("#miscellaneous_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 = $("#miscellaneous_medicine" + counter).val();
            var batch = $("#miscellaneous_item_batch_no" + counter).val();
            var miscellaneous = 'Y';
            $.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($("#miscellaneous_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($("#miscellaneous_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 !!");
                            $("#miscellaneous_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_miscellaneous_stock() {

        // checkIssuedQty();

        $.ajax({
            url: 'save_miscellaneous_stock_opd.php',
            type: "POST",
            data: $("#miscellaneous_stock_form").serialize(),
            success: function (data) {


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

            },
            error: function (data) {
                BootstrapDialog.alert('Error Saving Details');
                //return;
            }
        });
    }
    function setMiscellaneousItemBatchNo(count, batch) {
        var item_id = $('#miscellaneous_medicine' + count).val();
        $.ajax({
            url: 'get_item_batch_miscellaneous_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_mis = 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_mis += 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>"
                    }
                }
                $('#miscellaneous_total_qty' + count).val(total_qty_mis || 'Not available');
                $("#miscellaneous_item_batch_no" + count).html(content_item_batch);
            },
            error: function (data) { }
        });
    }

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

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

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


                    <div class="row">
                        <div class="col-sm-12 table-responsive">
                            <table id="intake_miscellaneous_table"
                                class="table table-striped table-bordered ordered-list"
                                style="padding: 2px; margin: 2px;">
                                <thead>
                                    <h3>
                                        <center>Ambulance</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_miscellaneous_treatment where appointment_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="miscellaneous_medicine<?php echo $i ?>"
                                                    name="miscellaneous_medicine<?php echo $i ?>"
                                                    data-placeholder="Choose a item..." style="width: 100%;"
                                                    onchange="setMiscellaneousItemBatchNo('<?php echo $i ?>','<?= $row_intake['medicine'] ?>')">
                                                    <option value=""></option>
                                                    <?php echo generate_options("SELECT DISTINCT(i.item_id) AS item_id ,TRIM(CONCAT(IFNULL(form_name,''),' ',item_name)) item_name FROM tbl_items i RIGHT JOIN item_stock_miscellaneous im ON i.item_id = im.item_id LEFT JOIN medicine_form f ON i.item_form_id=f.form_id  WHERE STATUS='1' AND is_prescription!='1' ORDER BY item_name", $row_intake['medicine'], 'item_id', 'item_name', '', ''); ?>

                                                </select>

                                            </td>
                                            <td style="width:20%">
                                                <select onchange='' name="miscellaneous_item_batch_no<?php echo $i; ?>"
                                                    id="miscellaneous_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="miscellaneous_total_qty<?php echo $i; ?>"
                                                    id="miscellaneous_total_qty<?php echo $i; ?>" type="text" readonly />
                                            </td>
                                            <!-- Aasish -->

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


                                            </td>


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

                                        </tr>
                                        <script>
                                            setMiscellaneousItemBatchNo('<?php echo $i ?>', '<?= $row_intake['miscellaneous_item_batch_no'] ?>');
                                            // getTotalQuantityMiscellaneous(<?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="miscellaneous_addrow">Add More</button>
                                            <input type="hidden" name="miscellaneous_count_items"
                                                id="miscellaneous_count_items" 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_miscellaneous_stock();">
                        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 DISTINCT(i.item_id) AS item_id ,TRIM(CONCAT(IFNULL(form_name,''),' ',item_name)) item_name FROM tbl_items i RIGHT JOIN item_stock_miscellaneous im ON i.item_id = im.item_id LEFT JOIN medicine_form f ON i.item_form_id=f.form_id  WHERE STATUS='1' AND is_prescription!='1' ORDER BY item_name", $row_treatment['item_id'], 'item_id', 'item_name', '', ''); ?> ";


        $("#miscellaneous_addrow").on("click", function () {
            var newRow = $("<tr>");
            var counter = $("#miscellaneous_count_items").val();
            var cols = "";
            var select_treatment = "";
            select_treatment += "<select ";
            select_treatment += 'onchange= " setMiscellaneousItemBatchNo(`' + counter + '`,``)"';
            select_treatment += "id=\"miscellaneous_medicine" + counter + "\"name=\"miscellaneous_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="miscellaneous_item_batch_no' + counter + '" id="miscellaneous_item_batch_no' + counter + '" class="form-control"><option value="" selected>Batches</option></select></td>';


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

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

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

            newRow.append(cols);
            $("#intake_miscellaneous_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
            })
            $('#miscellaneous_item_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()
            $("#miscellaneous_count_items").val(counter);
        });



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

    });

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

</script>