<?php include('techsyn_header.php'); ?>
<!-- Main Content Container for side bar and body-->
<div class="main-container ace-save-state" id="main-container">
    <script type="text/javascript">
        try {
            ace.settings.loadState('main-container')
        } catch (e) {}
    </script>
    <?php include('techsyn_sidebar.php'); ?>

    <!--breadcrumb-->
    <div class="main-content">
        <div class="main-content-inner">
            <div class="breadcrumbs ace-save-state" id="breadcrumbs">
                <ul class="breadcrumb">
                    <li>
                        <i class="ace-icon fa fa-home home-icon"></i>
                        <a href="#">Home</a>
                    </li>
                    <li class="#">Staff Management</li>
                    <li class="active">Attendance</li>
                </ul>

            </div>
            <!-- End of breadcrumb -->

            <?php
            //    $query = "SELECT * FROM procurement where (procurement_date > DATE_SUB(NOW(), INTERVAL 24 HOUR))";
            //   // echo $query;

            // $result_pro = @mysqli_query($conn,$query);
            //    while( $row_pro = mysqli_fetch_assoc($result_pro)){

            //      $procurement_id=$row_pro['procurement_id'];	

            //    }

            ?>

            <?php
            $i = 0;
            $selectedMonth = '';
            $selectedYear = '';

            if (isset($_REQUEST['flex_attendance_id'])) {
                $sql = "SELECT * FROM attendance_master WHERE attendance_id='" . $_REQUEST['flex_attendance_id'] . "'";

                $result = mysqli_query($conn, $sql);
                $num_rows = @mysqli_num_rows($result);
                $row = null;
                if ($num_rows > 0) {
                    $row = @mysqli_fetch_array($result);
                    $selectedMonth = $row['month'];
                    $selectedYear = $row['year'];
                    $monthNames = [
                        '1' => 'January',
                        '2' => 'February',
                        '3' => 'March',
                        '4' => 'April',
                        '5' => 'May',
                        '6' => 'June',
                        '7' => 'July',
                        '8' => 'August',
                        '9' => 'September',
                        '10' => 'October',
                        '11' => 'November',
                        '12' => 'December'
                    ];
                    $selectedMonthName = $monthNames[$selectedMonth];
                }
            }
            ?>


            <div class="page-content">
                <div class="box box-primary" style="padding: 10px; margin: 2px 0px 50px 5px; width: 99.5%; ">
                    <form id="attendance_form" method="post">
                        <!-- box-body-->
                        <div class="box-body">
                            <div class="row" style="margin-left: 50px; margin-right: 50px">
                                <div class="col-sm-3">
                                    <div class="form-group">

                                        <label>Attendance Date</label>

                                        <div class="input-group date">
                                            <div class="input-group-addon">
                                                <i class="fa fa-calendar"></i>
                                            </div>
                                            <input type="text" class="form-control" readonly value="<?php echo date("d/m/Y", strtotime($row['attendance_date'])) ?>">

                                            <input class="form-control date-picker" value="<?php echo date("d/m/Y", strtotime($row['attendance_date'])) ?>" name="attendance_date" id="attendance_date" type="hidden" data-date-format="dd/mm/yyyy" />
                                        </div>
                                        <!-- /.input group -->
                                    </div>

                                    <!-- <div class="form-group col-sm-6">
                                    <label>Remarks</label>
                                    <textarea name="remarks" id="remarks" rows="3" class="autosize-transition form-control" style="overflow: hidden; overflow-wrap: break-word; resize: horizontal; height: 52px;"><?php echo $row['remark'] ?></textarea>
                                </div> -->
                                </div>
                                <div class="col-sm-3">
                                    <label for="monthSelect">Selected Month:</label>
                                    <div>
                                        <input type="text" id="monthSelect" value="<?php echo $selectedMonthName; ?>" class="form-control" readonly />
                                    </div>
                                </div>
                                <div class="col-sm-3">
                                    <label for="yearSelect">Selected Year:</label>
                                    <div>
                                        <input type="text" id="yearSelect" value="<?php echo $selectedYear; ?>" class="form-control" readonly />
                                    </div>
                                </div>

                                <div class="col-sm-3">
                                    <label for="yearSelect">Staff Name</label>
                                    <div>
                                    <h3 style="text-align: left">
<?php
                                                        $staffId = $row['emp_id'];
                                                        echo  $empName =  getFieldFromTable('staff_name', 'staff_master', 'staff_id', $row['emp_id'])
                                                        ?>
                                    </h3>
</h3>
                                    </div>
                                </div>
                                <input type="hidden" name="attendance_emp" id="attendance_emp" value="<?php echo $staffId; ?>">
                                <script>
                                    window.addEventListener('load', onChangeYearMonth);

                                    function onChangeYearMonth() {
                                        var selectedMonthName = $("#monthSelect").val();
                                        var monthNameToNumber = {
                                            "January": 1,
                                            "February": 2,
                                            "March": 3,
                                            "April": 4,
                                            "May": 5,
                                            "June": 6,
                                            "July": 7,
                                            "August": 8,
                                            "September": 9,
                                            "October": 10,
                                            "November": 11,
                                            "December": 12
                                        };

                                        var selectedMonth = monthNameToNumber[selectedMonthName];
                                        var selectedYear = $("#yearSelect").val();

                                        if (!selectedMonth || !selectedYear) {
                                            console.error('Month or year is empty');
                                            return;
                                        }

                                        // console.log('Parsed month:', selectedMonth);
                                        // console.log('Parsed year:', selectedYear);

                                        $('input[type="datetime-local"]').each(function() {
                                            restrictDateTimes(this, selectedYear, selectedMonth);
                                        });
                                    }

                                    function setDefaultDateTime(selector, year, month) {
                                        var formattedMonth = month < 10 ? '0' + month : month;
                                        $(selector).val(year + '-' + formattedMonth + '-01T00:00');
                                    }

                                    function restrictDateTimes(selector, year, month) {
                                        // console.log('selector', selector);
                                        // console.log('year:', year);
                                        // console.log('month:', month);

                                        var daysInMonth = new Date(year, month, 0).getDate();

                                        var minDate = new Date(year, month - 1, 1).toISOString().split('T')[0] + 'T00:00';
                                        var maxDate = new Date(year, month - 1, daysInMonth).toISOString().split('T')[0] + 'T23:59';

                                        $(selector).attr('min', minDate);
                                        $(selector).attr('max', maxDate);
                                    }
                                </script>

                                <div class="row">
                                    <div class="col-sm-12">
                                        <table id="myTable" class="table table-bordered order-list">
                                            <thead>
                                                <tr>
                                                    <th>Staff Name</th>
                                                    <th>DeployMent OHC</th>
                                                    <!-- <th>WO</th> -->
                                                    <th>In DateTime</th>
                                                    <th>Out DateTime</th>
                                                    <th>OT</th>
                                                    <th>Shift</th>
                                                    <th>Remarks</th>
                                                    <th>Created by</th>
                                                    <th>Modified by</th>
                                                    <th>Delete</th>
                                                </tr>
                                            </thead>

                                            <?php
                                            $row = null;

                                            $sql = "
                                                SELECT 
                                                    b.*, 
                                                    pm_created.patient_name AS created_by_name, 
                                                    pm_modified.patient_name AS modified_by_name FROM 
                                                    attendance_master a 
                                                LEFT JOIN attendance_detail b ON a.attendance_id = b.attendance_id 
                                                LEFT JOIN tbl_users u_created ON b.created_by = u_created.user_id 
                                                LEFT JOIN  patient_master pm_created ON u_created.emp_id = pm_created.id 
                                                LEFT JOIN tbl_users u_modified ON b.modified_by = u_modified.user_id 
                                                LEFT JOIN patient_master pm_modified ON u_modified.emp_id = pm_modified.id 
                                                WHERE 
                                                    b.attendance_id = '" . $_REQUEST['flex_attendance_id'] . "' 
                                                    AND b.staff_id = '" . $staffId . "'
                                                ORDER BY 
                                                    b.staff_id";
                                            // error_log("data fetching " . $sql);
                                            $result = mysqli_query($conn, $sql);
                                            $num_rows = @mysqli_num_rows($result);
                                            $row = @mysqli_fetch_array($result);

                                            do {
                                            ?>

                                                <tbody>

                                                    <tr>

                                                        <td style="width:30%">
                                                            <input type="hidden" name="attendance_id" id="attendance_id" value=<?php echo $_REQUEST['flex_attendance_id'] ?>>
                                                            <!-- <select class="form-control select2" id="staff_id<?php echo $i ?>" name="staff_id<?php echo $i ?>" data-placeholder="Choose staff" style="width: 100%;">
                                                                <option value=""></option>
                                                                <?php echo generateOption('staff_master', 'staff_name', 'staff_id', $row['staff_id'], '') ?>

                                                            </select> -->


                                                            <h3 style="text-align: center;">
<?php                                                   
                                                        echo  $empName;
                                                        ?>
                                    </h3>
                                                        </td>

                                                        <td style="width:10%">
                                                            <select name="ohc_location<?php echo $i ?>" id="ohc_location<?php echo $i ?>" class="form-control">
                                                                <option value="">select</option>
                                                                <?php echo generateOption('ohc_type', 'ohc_type_name', 'ohc_type_id', $row['staff_deploy_ohc'], '') ?>
                                                            </select>
                                                        </td>
                                                        <!-- <td style="width:10%">
                                                        <select name="wo<?php echo $i ?>" id="wo<?php echo $i ?>" class="form-control">
                                                            <option value="">Select</option>

                                                            <option value="P" <?php if ($row['wo'] == 'P') echo "selected"; ?>>Present</option>
                                                            <option value="W" <?php if ($row['wo'] == 'W') echo "selected"; ?>>Off</option>
                                                        </select>
                                                    </td> -->

                                                        <td style="width:8%">
                                                            <input class="form-control" name="in_time<?php echo $i ?>" id="in_time<?php echo $i ?>" value="<?php echo $row['in_time'] ?>" type="datetime-local" />

                                                        </td>
                                                        <td style="width:8%">
                                                            <input class="form-control" name="out_time<?php echo $i ?>" id="out_time<?php echo $i ?>" value="<?php echo $row['out_time'] ?>" type="datetime-local" />

                                                        </td>

                                                        <td style="width:10%">
                                                            <input value="<?php echo $row['ot'] ?>" type="number" placeholder="Enter OT In Hours" name="ot<?php echo $i ?>" id="ot<?php echo $i ?>" class="form-control" min="0" />
                                                        </td>
                                                        <td style="width:10%">
                                                            <select name="shift<?php echo $i ?>" id="shift<?php echo $i ?>" class="form-control select2">
                                                                <?php
                                                                $ShiftOptionSql = "SELECT status_name , shift_status_id FROM shift_status ";
                                                                //    echo $shift_status_options =generateOptionForMultipleWithWhereClause('shift_status','status_name','shift_status_id','','','is_shift','Y'); 
                                                                echo generate_options($ShiftOptionSql, $row['shift'], 'shift_status_id', 'status_name', '', '');
                                                                ?>
                                                            </select>
                                                        </td>
                                                        <td style="width:30%">
                                                            <input type="text" value="<?php echo $row['remark'] ?>" name="remarks<?php echo $i ?>" id="remarks<?php echo $i ?>" class="form-control" class="form-control" />

                                                        </td>

                                                        <td style="width:15%">
                                                            <input type="text" value="<?php echo htmlspecialchars($row['created_by_name']); ?>" name="created_by<?php echo $i; ?>" id="created_by<?php echo $i; ?>" class="form-control" readonly />
                                                        </td>
                                                        <td style="width:15%">
                                                            <input type="text" value="<?php echo htmlspecialchars($row['modified_by_name']); ?>" name="modified_by<?php echo $i; ?>" id="modified_by<?php echo $i; ?>" class="form-control" readonly />
                                                        </td>



                                                        <td style="width:10%">

                                                        </td>

                                                    </tr>

                                                <?php
                                                $i++;
                                            } while ($row = @mysqli_fetch_array($result)) //end of while
                                                ?>


                                                </tbody>

                                                <tfoot>
                                                    <tr style="margin-left:10px;">
                                                        <td colspan="10" style="text-align: left;">
                                                            <input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" />
                                                            <input type="hidden" name="count_items" id="count_items" value="<?php echo $i ?>" />

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


                                        </table>

                                    </div>



                                </div>



                            </div>
                            <!-- End box-body-->
                            <!--box-footer-->
                            <div class="box-footer" style="text-align: center">
                                <button class="btn btn-info save_button" type="button" onclick="validate();">
                                    <i class="ace-icon fa fa-floppy-o bigger-110"></i>
                                    Save
                                </button>

                                &nbsp; &nbsp; &nbsp;
                                <button class="btn btn-warning" type="reset">
                                    <i class="ace-icon fa fa-undo bigger-110"></i>
                                    Reset
                                </button>
                            </div>
                            <!--End box-footer-->



                    </form>
                </div>
            </div>



            <!-- End of page-content -->
        </div>
    </div>
</div>

<script>
    function validate() {
        let date = $("#attendance_date").val();
        if (date == null || date == '') {
            BootstrapDialog.alert('Please Enter Attendance Date !!!!');
            return false;
        }

        var count = $("#count_items").val();
        let inDateTimes = [];

        for (var i = 0; i < count; i++) {
            let staff_id = $("#staff_id" + i).val();
            let ohc_location = $("#ohc_location" + i).val();
            let intime = $("#in_time" + i).val();
            let outtime = $("#out_time" + i).val();
            let wo = $("#wo" + i).val();

            if (staff_id == undefined) {
                continue;
            }

            if (staff_id == null || staff_id == '') {
                BootstrapDialog.alert('Please select Staff Name !!!!');
                return false;
            }
            if (ohc_location == null || ohc_location == '') {
                BootstrapDialog.alert('Please select ohc_location!!!!');
                return false;
            }

            if (wo != "W") {
                if (intime == null || intime == '') {
                    BootstrapDialog.alert('Please select In DateTime !!!!');
                    return false;
                }
                if (outtime == null || outtime == '') {
                    BootstrapDialog.alert('Please select Out DateTime !!!!');
                    return false;
                }
            }

            const date1 = new Date(intime);
            const date2 = new Date(outtime);
            if (date1 > date2) {
                BootstrapDialog.alert("Out DateTime Cannot be less than In DateTime At Row " + (i + 1));
                return false;
            }

            if (inDateTimes.includes(intime)) {
                BootstrapDialog.alert("Duplicate In DateTime found at Row " + (i + 1));
                return false;
            } else {
                inDateTimes.push(intime);
            }
        }


        save();
    }
</script>

<style>
    #modal-add-ailment {
        overflow-y: scroll;
    }
</style>



<?php include('techsyn_footer.php'); ?>
<script type="text/javascript">
    $('.select2').select2()
    jQuery(function($) {

        var myTable =
            $('#dynamic-table')

            .DataTable({
                bAutoWidth: false,
                "aoColumns": [{
                        "bSortable": false
                    },
                    null, null, null, null, null,
                    {
                        "bSortable": false
                    }
                ],
                "aaSorting": [],





                select: {
                    style: 'multi'
                }
            });




        var defaultCopyAction = myTable.button(1).action();
        myTable.button(1).action(function(e, dt, button, config) {
            defaultCopyAction(e, dt, button, config);
            $('.dt-button-info').addClass('gritter-item-wrapper gritter-info gritter-center white');
        });


        var defaultColvisAction = myTable.button(0).action();
        myTable.button(0).action(function(e, dt, button, config) {

            defaultColvisAction(e, dt, button, config);


            if ($('.dt-button-collection > .dropdown-menu').length == 0) {
                $('.dt-button-collection')
                    .wrapInner('<ul class="dropdown-menu dropdown-light dropdown-caret dropdown-caret" />')
                    .find('a').attr('href', '#').wrap("<li />")
            }
            $('.dt-button-collection').appendTo('.tableTools-container .dt-buttons')
        });



        setTimeout(function() {
            $($('.tableTools-container')).find('a.dt-button').each(function() {
                var div = $(this).find(' > div').first();
                if (div.length == 1) div.tooltip({
                    container: 'body',
                    title: div.parent().text()
                });
                else $(this).tooltip({
                    container: 'body',
                    title: $(this).text()
                });
            });
        }, 500);





        myTable.on('select', function(e, dt, type, index) {
            if (type === 'row') {
                $(myTable.row(index).node()).find('input:checkbox').prop('checked', true);
            }
        });
        myTable.on('deselect', function(e, dt, type, index) {
            if (type === 'row') {
                $(myTable.row(index).node()).find('input:checkbox').prop('checked', false);
            }
        });




        $('th input[type=checkbox], td input[type=checkbox]').prop('checked', false);


        $('#dynamic-table > thead > tr > th input[type=checkbox], #dynamic-table_wrapper input[type=checkbox]').eq(0).on('click', function() {
            var th_checked = this.checked;

            $('#dynamic-table').find('tbody > tr').each(function() {
                var row = this;
                if (th_checked) myTable.row(row).select();
                else myTable.row(row).deselect();
            });
        });


        $('#dynamic-table').on('click', 'td input[type=checkbox]', function() {
            var row = $(this).closest('tr').get(0);
            if (this.checked) myTable.row(row).deselect();
            else myTable.row(row).select();
        });



        $(document).on('click', '#dynamic-table .dropdown-toggle', function(e) {
            e.stopImmediatePropagation();
            e.stopPropagation();
            e.preventDefault();
        });




        var active_class = 'active';
        $('#simple-table > thead > tr > th input[type=checkbox]').eq(0).on('click', function() {
            var th_checked = this.checked;

            $(this).closest('table').find('tbody > tr').each(function() {
                var row = this;
                if (th_checked) $(row).addClass(active_class).find('input[type=checkbox]').eq(0).prop('checked', true);
                else $(row).removeClass(active_class).find('input[type=checkbox]').eq(0).prop('checked', false);
            });
        });

        $('#simple-table').on('click', 'td input[type=checkbox]', function() {
            var $row = $(this).closest('tr');
            if ($row.is('.detail-row ')) return;
            if (this.checked) $row.addClass(active_class);
            else $row.removeClass(active_class);
        });




        $('[data-rel="tooltip"]').tooltip({
            placement: tooltip_placement
        });


        function tooltip_placement(context, source) {
            var $source = $(source);
            var $parent = $source.closest('table')
            var off1 = $parent.offset();
            var w1 = $parent.width();

            var off2 = $source.offset();


            if (parseInt(off2.left) < parseInt(off1.left) + parseInt(w1 / 2)) return 'right';
            return 'left';
        }




        /***************/
        $('.show-details-btn').on('click', function(e) {
            e.preventDefault();
            $(this).closest('tr').next().toggleClass('open');
            $(this).find(ace.vars['.icon']).toggleClass('fa-angle-double-down').toggleClass('fa-angle-double-up');
        });
        /***************/






    })


    function save() {
        $.ajax({
            url: 'save_attendance.php ',
            type: "POST",
            data: $("#attendance_form").serialize(),
            success: function(data) { //alert(data);
                BootstrapDialog.alert('Attendance Saved Successfully.');
                $("#flex1").flexReload();
                return;


            },
            error: function(data) {
                BootstrapDialog.alert('Error Saving Attendance');
                return;
            }
        });
        $('.close').click();
        // location.href="procurement_list.php";
    }
    $('.date-picker').datepicker({
        autoclose: true,
        format: 'dd/mm/yyyy'
    }).next().on(ace.click_event, function() {
        $(this).prev().focus();
    });
</script>
<!-- bootstrap & fontawesome -->
<link rel="stylesheet" href="assets/font-awesome/4.5.0/css/font-awesome.min.css" />

<!-- page specific plugin styles -->
<link rel="stylesheet" href="assets/css/jquery-ui.custom.min.css" />
<link rel="stylesheet" href="assets/css/chosen.min.css" />
<link rel="stylesheet" href="assets/css/bootstrap-datepicker3.min.css" />
<link rel="stylesheet" href="assets/css/bootstrap-timepicker.min.css" />
<link rel="stylesheet" href="assets/css/daterangepicker.min.css" />
<link rel="stylesheet" href="assets/css/bootstrap-datetimepicker.min.css" />
<link rel="stylesheet" href="assets/css/bootstrap-colorpicker.min.css" />
<script type="text/javascript" src="js/typeahead.bundle.js"></script>
<script src="assets/js/jquery-ui.custom.min.js"></script>
<script src="assets/js/jquery.ui.touch-punch.min.js"></script>
<script src="assets/js/chosen.jquery.min.js"></script>
<script src="assets/js/spinbox.min.js"></script>
<script src="assets/js/bootstrap-datepicker.min.js"></script>
<script src="assets/js/bootstrap-timepicker.min.js"></script>
<script src="assets/js/jquery.dataTables.min.js"></script>
<script src="assets/js/jquery.dataTables.bootstrap.min.js"></script>
<script src="assets/js/dataTables.buttons.min.js"></script>
<script src="assets/js/buttons.flash.min.js"></script>
<script src="assets/js/buttons.html5.min.js"></script>
<script src="assets/js/buttons.print.min.js"></script>
<script src="assets/js/buttons.colVis.min.js"></script>
<script src="assets/js/dataTables.select.min.js"></script>


<script src="assets/js/moment.min.js"></script>
<script src="assets/js/daterangepicker.min.js"></script>
<script src="assets/js/bootstrap-datetimepicker.min.js"></script>
<script src="assets/js/bootstrap-colorpicker.min.js"></script>
<script src="assets/js/jquery.knob.min.js"></script>
<script src="assets/js/autosize.min.js"></script>
<script src="assets/js/jquery.inputlimiter.min.js"></script>
<script src="assets/js/jquery.maskedinput.min.js"></script>
<script src="assets/js/bootstrap-tag.min.js"></script>
<script src="assets/js/ace-elements.min.js"></script>

<script type="text/javascript">
    $(document).ready(function() {
        var counter = $("#count_items").val();
        var itemOptions = "<?php echo generateOption('staff_master', 'staff_name', 'staff_id', '', '');  ?>";

        var itemOptions2 = "<option value='yes'>Yes</option><option value='no'>No</option>";

        var ShiftOptions = "<?php $ShiftSql = " SELECT * FROM shift_status";
                            echo generate_options($ShiftSql, '', 'shift_status_id', 'status_name', '', '');  ?>";

        var itemOptions3 = "<?php echo  generateOption('ohc_type', 'ohc_type_name', 'ohc_type_id', $_SESSION['current_ohcttype'], '') ?>";

        var itemOptions4 = "<option value='P'>Present</option><option value='W'>Off</option>";


        var selectedMonthName = $("#monthSelect").val();
        var monthNameToNumber = {
            "January": 1,
            "February": 2,
            "March": 3,
            "April": 4,
            "May": 5,
            "June": 6,
            "July": 7,
            "August": 8,
            "September": 9,
            "October": 10,
            "November": 11,
            "December": 12
        };

        var selectedMonth = monthNameToNumber[selectedMonthName];
        var selectedYear = $("#yearSelect").val();
        $("#addrow").on("click", function() {
var EmpName = "<h3 style='text-align: center;'><?php echo $empName ?></h3>";

            var newRow = $("<tr>");
            var cols = "";
            var select_treatment = "";
            var select_treatment2 = "";
            var select_treatment3 = "";
            var select_treatment4 = "";
            var ShiftSelect = "";



            // select_treatment += "<select ";
            // select_treatment += "id=\"staff_id" + counter + "\"name=\"staff_id" + counter + "\"   data-placeholder=\"Choose Staff...\"  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>';

            cols += '<td>'+ EmpName +'</td>';



            select_treatment3 += "<select ";
            select_treatment3 += "id=\"ohc_location" + counter + "\"name=\"ohc_location" + counter + "\"   class=\"form-control\"  style=\"width: 100%;\" ";
            //select_treatment+="style=\"display: none;\"";
            select_treatment3 += ">";

            select_treatment3 += "<option value=\"\">select</option>";
            select_treatment3 += itemOptions3
            select_treatment3 += "</select>";

            cols += '<td>' + select_treatment3 + '</td>';

            // select_treatment4 += "<select ";
            // select_treatment4 += "id=\"wo" + counter + "\"name=\"wo" + counter + "\"   class=\"form-control\"  style=\"width: 100%;\" ";
            // //select_treatment+="style=\"display: none;\"";
            // select_treatment4 += ">";

            // select_treatment4 += "<option value=\"\">select</option>";
            // select_treatment4 += itemOptions4
            // select_treatment4 += "</select>";

            // cols += '<td>' + select_treatment4 + '</td>';

            cols += '<td><input type="datetime-local" class="form-control" id="in_time' + counter + '" name="in_time' + counter + '"/></td>';
            cols += '<td><input type="datetime-local" class="form-control" id="out_time' + counter + '" name="out_time' + counter + '"/></td>';


            // select_treatment2 += "<select ";
            // select_treatment2 += "id=\"ot" + counter + "\"name=\"ot" + counter + "\"   class=\"form-control\"  style=\"width: 100%;\" ";
            // //select_treatment+="style=\"display: none;\"";
            // select_treatment2 += ">";

            // select_treatment2 += "<option value=\"\">select</option>";
            // select_treatment2 += itemOptions2
            // select_treatment2 += "</select>";

            // cols += '<td>' + select_treatment2 + '</td>';

            cols += '<td><input type="number" min="0" placeholder="Enter OT in Hours" class="form-control" id="ot' + counter + '" name="ot' + counter + '"/></td>';

            ShiftSelect += "<select name=\"shift" + counter + "\" id=\"shift" + counter + "\" class=\"form-control select2\" style=\"width: 100%;\">";
            ShiftSelect += "<option value=\"\">select</option>";
            ShiftSelect += ShiftOptions;
            ShiftSelect += "</select>";

            cols += '<td>' + ShiftSelect + '</td>';


            cols += '<td><input type="text" class="form-control" id="remarks' + counter + '" name="remarks' + 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);
            $("table.order-list").append(newRow);
            var item_id = $("#item_id" + (counter - 1)).val();
            /*$('#item_id'+counter).chosen({allow_single_deselect:true}); 
            $('#item_id'+counter).next().css({'width': $('#item_id'+counter).parent().width()});*/
            counter++;
            $('.select2').select2()
            $("#count_items").val(counter);
            setDefaultDateTime('#in_time' + (counter - 1), selectedYear, selectedMonth);
            setDefaultDateTime('#out_time' + (counter - 1), selectedYear, selectedMonth);
            console.log('Parsed month:', selectedMonth);
            restrictDateTimes('#in_time' + (counter - 1) + ', #out_time' + (counter - 1), selectedYear, selectedMonth);

        });



        $("table.order-list").on("click", "#deletebtn", function(event) {
            // selected_items = jQuery.grep(selected_items, function(value) {
            // 	return value != $("#item_id" + (counter - 1)).val();
            // });
            $(this).closest("tr").remove();
        });


    });
</script>

<script type="text/javascript">
    jQuery(function($) {
        $('#id-disable-check').on('click', function() {
            var inp = $('#form-input-readonly').get(0);
            if (inp.hasAttribute('disabled')) {
                inp.setAttribute('readonly', 'true');
                inp.removeAttribute('disabled');
                inp.value = "This text field is readonly!";
            } else {
                inp.setAttribute('disabled', 'disabled');
                inp.removeAttribute('readonly');
                inp.value = "This text field is disabled!";
            }
        });


        if (!ace.vars['touch']) {
            $('.chosen-select').chosen({
                allow_single_deselect: true
            });


            $(window)
                .off('resize.chosen')
                .on('resize.chosen', function() {
                    $('.chosen-select').each(function() {
                        var $this = $(this);
                        $this.next().css({
                            'width': $this.parent().width()
                        });
                    })
                }).trigger('resize.chosen');
            //resize chosen on sidebar collapse/expand
            $(document).on('settings.ace.chosen', function(e, event_name, event_val) {
                if (event_name != 'sidebar_collapsed') return;
                $('.chosen-select').each(function() {
                    var $this = $(this);
                    $this.next().css({
                        'width': $this.parent().width()
                    });
                })
            });


            $('#chosen-multiple-style .btn').on('click', function(e) {
                var target = $(this).find('input[type=radio]');
                var which = parseInt(target.val());
                if (which == 2) $('#form-field-select-4').addClass('tag-input-style');
                else $('#form-field-select-4').removeClass('tag-input-style');
            });
        }


        $('[data-rel=tooltip]').tooltip({
            container: 'body'
        });
        $('[data-rel=popover]').popover({
            container: 'body'
        });

        autosize($('textarea[class*=autosize]'));

        $('textarea.limited').inputlimiter({
            remText: '%n character%s remaining...',
            limitText: 'max allowed : %n.'
        });




        //"jQuery UI Slider"
        //range slider tooltip example
        $("#slider-range").css('height', '200px').slider({
            orientation: "vertical",
            range: true,
            min: 0,
            max: 100,
            values: [17, 67],
            slide: function(event, ui) {
                var val = ui.values[$(ui.handle).index() - 1] + "";

                if (!ui.handle.firstChild) {
                    $("<div class='tooltip right in' style='display:none;left:16px;top:-6px;'><div class='tooltip-arrow'></div><div class='tooltip-inner'></div></div>")
                        .prependTo(ui.handle);
                }
                $(ui.handle.firstChild).show().children().eq(1).text(val);
            }
        }).find('span.ui-slider-handle').on('blur', function() {
            $(this.firstChild).hide();
        });


        $("#slider-range-max").slider({
            range: "max",
            min: 1,
            max: 10,
            value: 2
        });

        $("#slider-eq > span").css({
            width: '90%',
            'float': 'left',
            margin: '15px'
        }).each(function() {
            // read initial values from markup and remove that
            var value = parseInt($(this).text(), 10);
            $(this).empty().slider({
                value: value,
                range: "min",
                animate: true

            });
        });

        $("#slider-eq > span.ui-slider-purple").slider('disable'); //disable third item


        $('#id-input-file-1 , #id-input-file-2').ace_file_input({
            no_file: 'No File ...',
            btn_choose: 'Choose',
            btn_change: 'Change',
            droppable: false,
            onchange: null,
            thumbnail: false //| true | large
            //whitelist:'gif|png|jpg|jpeg'
            //blacklist:'exe|php'
            //onchange:''
            //
        });
        //pre-show a file name, for example a previously selected file
        //$('#id-input-file-1').ace_file_input('show_file_list', ['myfile.txt'])






        //datepicker plugin
        //link
        $('.date-picker').datepicker({
                autoclose: true,
                todayHighlight: true
            })
            //show datepicker when clicking on the icon
            .next().on(ace.click_event, function() {
                $(this).prev().focus();
            });



        //chosen plugin inside a modal will have a zero width because the select element is originally hidden
        //and its width cannot be determined.
        //so we set the width after modal is show
        $('#modal-form').on('shown.bs.modal', function() {
            if (!ace.vars['touch']) {
                $(this).find('.chosen-container').each(function() {
                    $(this).find('a:first-child').css('width', '210px');
                    $(this).find('.chosen-drop').css('width', '210px');
                    $(this).find('.chosen-search input').css('width', '200px');
                });
            }
        })
        /**
        //or you can activate the chosen plugin after modal is shown
        //this way select element becomes visible with dimensions and chosen works as expected
        $('#modal-form').on('shown', function () {
        	$(this).find('.modal-chosen').chosen();
        })
        */



        $(document).one('ajaxloadstart.page', function(e) {
            autosize.destroy('textarea[class*=autosize]')

            $('.limiterBox,.autosizejs').remove();
            $('.daterangepicker.dropdown-menu,.colorpicker.dropdown-menu,.bootstrap-datetimepicker-widget.dropdown-menu').remove();
        });

    });
</script>