<?php require "code_css_form.php"; ?>
<style>
  /* .select2-container {
    z-index: 1000000  !important; 
  } */

  .details {
    display: none;
    /* Initially hide details */
  }

  .td_font_size {
    font-size: 12px !important;
  }

  /* .td_input_size{
    width: 150px !important;
  } */
  .inline-grid {
    display: inline-grid;
  }



  .item-name {
    cursor: pointer;
  }

  .item-name i {
    margin-left: 5px;
  }

  .invoice_table_section {
    border: 1px solid #337ab7 !important;
    overflow-y: auto;
    border: 1px solid rgb(51, 122, 183) !important;
    height: 291px !important;
  }

  .select2-container--default .select2-selection--single {
    border-radius: 0px;
  }

  /*LEFT SIDE: ITEMS TABLE*/
  .table-striped>tbody>tr:nth-of-type(2n+1) {
    background-color: #ede3e3 !important;
  }

  .table-striped>tbody>tr {
    background-color: #ddc8c8 !important;
  }

  /*SET TOTAL FONT*/
  .tot_qty1,
  .tot_amt1,
  .tot_disc1,
  .tot_grand1 {
    font-size: 19px;
    color: #023763;
  }

  /*CURSOR POINTER CLASS*/
  .pointer {
    cursor: pointer;
  }

  .navbar-nav>.user-menu>.dropdown-width-lg {
    width: 350px;
  }

  .header-custom {
    background-image: -webkit-gradient(linear, left top, right top, from(#20b9ae), to(#006fd6));
    color: white;
  }

  .border-custom-bottom {
    border-bottom: 1px solid;
    padding-top: 10px;
    padding-bottom: 5px;
  }

  .custom-font-size {
    font-size: 22px;
  }

  .search_item {
    text-transform: uppercase;
    font-size: 10px;
    color: #000000;
    text-align: center;
    text-overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
  }

  .item_image {
    min-width: 70px;
    min-height: 70px;
    max-width: 70px;
    max-height: 70px;
  }

  .item_box {
    border-top: none;
  }

  .min_width {
    min-width: 70px;
  }

  #tax_modal1,
  #unit_modal1,
  #category_modal1,
  #brand_modal1,
  #customer-modal1,
  #discount-modal,
  #sales_item {
    z-index: 999000;
  }

  /* Increase z-index for Select2 dropdown */
  .select2-container--open .select2-dropdown {
    z-index: 9999999999999 !important;
    /* Adjust the value as needed */
  }


  .ui-autocomplete {
    z-index: 9999999999999 !important;
    /* Adjust as needed */
  }

  .modal {
    overflow-x: hidden !important;
    overflow-y: auto !important;
  }
</style>
<!-- **********************MODALS***************** -->
<?php require "modal_brand.php"; ?>
<?php require "modal_category.php"; ?>
<?php require "modal_unit.php"; ?>
<?php require "modal_tax.php"; ?>
<!-- **********************MODALS***************** -->
<?php require "modal_customer.php"; ?>
<?php require "modal_pos_sales_item.php"; ?>
<!-- **********************MODALS END***************** -->
<!-- modal pos -->
<div class="modal fade " id="pos-modal">
  <div class="modal-dialog modal-lg" style="width:100% !important">
    <div class="modal-content">
      <div class="modal-header header-custom">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title text-center"><?= $this->lang->line('pos'); ?></h4>
      </div>
      <div class="modal-body">

        <section class="content">
          <div class="row">
            <!-- left column -->
            <div class="col-md-4">

              <!-- general form elements -->
              <div class="box box-primary">
                <!-- form start -->
                <form class="form-horizontal" id="pos-form1">
                  <div class="box-header with-border" style="padding-bottom: 0px;">
                    <div class="row">
                      <div class="col-md-12">
                        <!-- <div class="col-md-4">
                          <h3 class="box-title text-primary"><i class="fa fa-shopping-cart text-aqua"></i> Sales Invoice</h3>
                        </div> -->

                        <?php if (isset($sales_id)) : ?>
                          <?php if ($CI->permissions('sales_add')) { ?>
                            <div class="col-md-4 pull-right">
                              <a href='<?= $base_url; ?>pos' class="btn btn-primary pull-right">New Invoice</a>
                            </div>
                          <?php } ?>
                        <?php endif; ?>

                      </div>
                    </div>




                  </div>
                  <!-- /.box-header -->

                  <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
                  <input type="hidden" value='0' id="hidden_rowcount1" name="hidden_rowcount">
                  <input type="hidden" value='' id="hidden_invoice_id1" name="hidden_invoice_id">
                  <input type="hidden" id="base_url" value="<?php echo $base_url;; ?>">

                  <input type="hidden" value='' id="temp_customer_id1" name="temp_customer_id">

                  <!-- **********************MODALS***************** -->
                  <?php include "modal_payments_multi.php"; ?>
                  <!-- **********************MODALS END***************** -->
                  <!-- **********************MODALS***************** -->
                  <div class="modal fade" id="discount-modal">
                    <div class="modal-dialog">
                      <div class="modal-content">
                        <div class="modal-header">
                          <button type="button" class="close" onclick="discountModalClose()" aria-label="Close">
                            <span aria-hidden="true">&times;</span></button>
                          <h4 class="modal-title">Set Discount</h4>
                        </div>
                        <div class="modal-body">
                          <div class="row">
                            <div class="col-md-6">
                              <div class="box-body">
                                <div class="form-group">
                                  <label for="discount_input">Discount</label>
                                  <input type="text" class="form-control" id="discount_input1" name="discount_input" placeholder="">
                                </div>
                              </div>
                            </div>
                            <div class="col-md-6">
                              <div class="box-body">
                                <div class="form-group">
                                  <label for="discount_type">Discount Type</label>
                                  <select class="form-control" id='discount_type1' name="discount_type">
                                    <option value='in_percentage'>Per%</option>
                                    <option value='in_fixed'>Fixed</option>
                                  </select>
                                </div>
                              </div>
                            </div>
                          </div>

                        </div>
                        <div class="modal-footer">
                          <button type="button" class="btn btn-warning" onclick="discountModalClose()">Close</button>
                          <button type="button" class="btn btn-primary discount_update">Update</button>
                        </div>
                      </div>
                      <!-- /.modal-content -->
                    </div>
                    <!-- /.modal-dialog -->
                  </div>
                  <!-- /.modal -->
                  <!-- **********************MODALS END***************** -->
                  <div class="box-body">
                    <?php if (isset($sales_id)) { ?>
                      <div class="row">
                        <div class="col-md-6">
                          <div class="input-group date">
                            <div class="input-group-addon">
                              <i class="fa fa-calendar"></i>
                            </div>
                            <input type="text" class="form-control pull-right datepicker" id="sales_date" name="sales_date" readonly value="">
                          </div>
                          <span id="sales_date_msg" style="display:none" class="text-danger"></span>
                        </div>
                      </div><!-- row end -->
                      <br>
                    <?php } ?>
                    <div class="row">
                      <div class="col-md-6">
                        <div class="input-group">
                          <span class="input-group-addon" title="Customer"><i class="fa fa-user"></i></span>
                          <select class="form-control select2" id="customer_id1" name="customer_id" style="width: 100%;" onkeyup="shift_cursor(event,'expense_for')">
                            <?php
                            $query1 = "select * from db_customers where status=1";
                            $q1 = $this->db->query($query1);

                            if ($q1->num_rows($q1) > 0) {
                              foreach ($q1->result() as $res1) {
                                echo "<option  value='" . $res1->id . "'>" . $res1->customer_name . "</option>";
                              }
                            } else {
                            ?>
                              <option value="">No Records Found</option>
                            <?php
                            }
                            ?>
                          </select>
                          <span class="input-group-addon pointer" data-toggle="modal" data-target="#customer-modal1" title="New Customer?"><i class="fa fa-user-plus text-primary fa-lg"></i></span>
                        </div>
                        <span class="customer_points text-success" style="display: none;"></span>


                      </div>
                      <div class="col-md-6">
                        <div class="input-group">
                          <span class="input-group-addon" title="Select Items"><i class="fa fa-barcode"></i></span>
                          <input type="text" class="form-control" placeholder="Item name/Barcode/Itemcode [Shift+S]" id="item_search_pos">
                        </div>
                      </div>
                    </div><!-- row end -->
                    <br>
                    <div class="row">
                      <div class="col-md-12">
                        <div class="form-group">
                          <div class="col-sm-12 invoice_table_section">
                            <table class="table table-condensed table-bordered table-striped table-responsive items_table">
                              <tbody id="pos-form-tbody" style="font-size: 16px;font-weight: bold;overflow: scroll;height:0px !important">
                                <thead class="bg-primary" style="display: none !important;">
                                  <th width="30%"><?= $this->lang->line('item_name'); ?></th>
                                  <th width="10%"><?= $this->lang->line('stock'); ?></th>
                                  <th width="25%"><?= $this->lang->line('quantity'); ?></th>
                                  <th width="15%"><?= $this->lang->line('price'); ?></th>
                                  <th width="10%"><?= $this->lang->line('discount'); ?></th>
                                  <th width="10%" class='<?= tax_disable_class() ?>'><?= $this->lang->line('tax'); ?></th>
                                  <th width="15%"><?= $this->lang->line('subtotal'); ?></th>
                                  <th width="5%"><i class="fa fa-close"></i></th>
                                </thead>
                              </tbody>
                              <tfoot>
                                <!-- footer code -->
                              </tfoot>
                            </table>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="row">
                      <div class="col-xs-12 ">
                        <div class="col-md-6">
                          <div style="display: flex;">
                            <input type="checkbox" class="form-control" id="send_sms" name="send_sms">
                            <label style="display: flex;font-size:12px !important;font-weight:normal !important" for="sales_discount"><label for='send_sms'><?= $this->lang->line('send_sms_to_customer'); ?></label>
                              <i class="hover-q " data-container="body" data-toggle="popover" data-placement="top" data-content="If checkbox is Disabled! You need to enable it from SMS -> SMS API <br><b>Note:<i>Walk-in Customer will not receive SMS!</i></b>" data-html="true" data-trigger="hover" data-original-title="" title="Do you wants to send SMS ?">
                                <i class="fa fa-info-circle text-maroon text-black hover-q"></i>
                              </i>
                            </label>
                          </div>
                        </div>
                        <div class="col-md-6">
                          <div class="form-group" style="display: flex;font-size:12px !important;font-weight:normal !important">
                            <label for="other_charges" class="col-sm-7 control-label"><?= $this->lang->line('other_charges'); ?><label class="text-danger">*</label></label>

                            <div class="col-sm-5">
                              <input type="text" class="form-control text-right" id="other_charges1" name="other_charges" placeholder="0.00">
                              <span id="other_charges_msg" style="display:none" class="text-danger"></span>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>

                  </div>
                  <!-- /.box-body -->

                  <div class="box-footer bg-gray">
                    <div class="row">
                      <div class="col-md-6">
                        <label style="margin-left:15px"> <?= $this->lang->line('quantity'); ?>:</label>
                        <span class="text-bold tot_qty1"></span>
                      </div>
                      <div class="col-md-6">
                        <label style="margin-right:12px"><?= $this->lang->line('total_amount'); ?>:</label>
                        <?= $CI->currency('<span style="font-size: 19px;" class="tot_amt1 text-bold"></span>'); ?>
                      </div>
                      <div class="col-md-6">
                        <label style="margin-left:15px"><?= $this->lang->line('total_discount'); ?>:<a class="fa fa-pencil-square-o cursor-pointer" data-toggle="modal" data-target="#discount-modal"></a></label>
                        <?= $CI->currency('<span style="font-size: 19px;" class="tot_disc1 text-bold"></span>'); ?>
                      </div>
                      <div class="col-md-6">
                        <label style="margin-right:12px"><?= $this->lang->line('grand_total'); ?>:</label>
                        <?= $CI->currency('<span style="font-size: 19px;" class="tot_grand1 text-bold"></span>'); ?>
                      </div>
                    </div>

                    <div class="row">

                      <?php if (isset($sales_id)) {
                        $btn_id = 'update';
                        $btn_name = "Cash"; ?>
                        <input type="hidden" name="sales_id" id="sales_id" value="<?php echo $sales_id; ?>" />
                      <?php } else {
                        $btn_id = 'save';
                        $btn_name = "Cash";
                      } ?>

                      <div class="col-md-12">

                        <div class="col-sm-6">
                          <button type="button" id="hold_invoice1" name="" class="btn bg-maroon btn-block btn-flat" title="Hold Invoice [Shift+H]">
                            <i class="fa fa-hand-paper-o" aria-hidden="true"></i>
                            Hold
                          </button>
                        </div>
                        <div class="col-sm-6">
                          <button type="button" id="" name="" class="btn btn-primary btn-block btn-flat show_payments_modal" title="Multiple Payments [Shift+M]">
                            <i class="fa fa-credit-card" aria-hidden="true"></i>
                            Multiple
                          </button>
                        </div>
                        <div class="col-sm-6" style="margin-top:4px">
                          <button type="button" id="<?php echo "show_cash_modal"; ?>" name="" class="btn btn-success btn-block btn-flat shift_c" title="By Cash & Save [Shift+C]">
                            <i class="fa fa-money" aria-hidden="true"></i>
                            <?php echo $btn_name; ?>
                          </button>
                        </div>

                        <div class="col-sm-6" style="margin-top:4px">
                          <button type="button" id="pay_all" name="" class="btn bg-purple btn-block btn-flat shift_a" title="By Cash & Save [Shift+A]">
                            <i class="fa fa-money" aria-hidden="true"></i>
                            Pay All
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                </form>
              </div>
              <!-- /.box -->
            </div>
            <!--/.col (left) -->
            <!-- right column -->
            <div class="col-md-8">
              <!-- Horizontal Form -->
              <div class="box box-info">
                <!-- form start -->

                <div class="box-body">

                  <div class="row">
                    <div class="col-md-4">
                      <div class="input-group input-group-md">
                        <select class="form-control select2" id="warehouse_id2" name="warehouse_id" style="width: 100%;">
                          <?php
                          $query1 = "select * from db_warehouse where status=1";
                          $q1 = $this->db->query($query1);
                          echo '<option value="">All Warehouse</option>';
                          if ($q1->num_rows($q1) > 0) {
                            foreach ($q1->result() as $res1) {
                              echo "<option value='" . $res1->id . "'>" . $res1->warehouse_name . "</option>";
                            }
                          } else {
                          ?>
                            <option value="">No Records Found</option>
                          <?php
                          }
                          ?>
                        </select>
                        <span class="input-group-btn">
                          <button type="button" class="btn text-blue btn-flat reset_warehouse" title="Reset Warehouse" data-toggle="tooltip" data-placement="top">
                            <i class="fa fa-undo"></i>
                          </button>
                        </span>
                      </div>
                    </div>
                    <div class="col-md-4">
                      <div class="input-group input-group-md">
                        <select class="form-control select2" id="category_id" name="category_id" style="width: 100%;">
                          <?php
                          $query1 = "select * from db_category where status=1";
                          $q1 = $this->db->query($query1);
                          echo '<option value="">All Categories</option>';
                          if ($q1->num_rows($q1) > 0) {
                            foreach ($q1->result() as $res1) {
                              echo "<option value='" . $res1->id . "'>" . $res1->category_name . "</option>";
                            }
                          } else {
                          ?>
                            <option value="">No Records Found</option>
                          <?php
                          }
                          ?>
                        </select>
                        <span class="input-group-btn">
                          <button type="button" class="btn text-blue btn-flat reset_categories" title="Reset Brand" data-toggle="tooltip" data-placement="top">
                            <i class="fa fa-undo"></i>
                          </button>
                        </span>
                      </div>
                    </div>
                    <div class="col-md-4">
                      <div class="input-group input-group-md">
                        <select class="form-control select2" id="brand_id" name="brand_id" style="width: 100%;">
                          <?php
                          $query1 = "select * from db_brands where status=1";
                          $q1 = $this->db->query($query1);
                          echo '<option value="">All Brands</option>';
                          if ($q1->num_rows($q1) > 0) {
                            foreach ($q1->result() as $res1) {
                              echo "<option value='" . $res1->id . "'>" . $res1->brand_name . "</option>";
                            }
                          } else {
                          ?>
                            <option value="">No Records Found</option>
                          <?php
                          }
                          ?>
                        </select>
                        <span class="input-group-btn">
                          <button type="button" class="btn text-blue btn-flat reset_brands" title="Reset Brand" data-toggle="tooltip" data-placement="top">
                            <i class="fa fa-undo"></i>
                          </button>
                        </span>
                      </div>
                    </div>
                  </div><!-- row end -->



                  <div class="row">
                    <div class="col-md-12">
                      <!-- <div class="form-group"> -->
                      <!--  <div class="col-sm-12"> -->
                      <!-- <style type="text/css">
                        
                      </style> -->
                      <section class="content">
                        <div class="row search_div" style="overflow-y: scroll;min-height: 100px;height: 500px;">
                        </div>
                      </section>
                      <div class=" text-center" style="display:none;">
                        <button type="button" class="btn btn-default btn-lrg ajax" title="Ajax Request">
                          <i class="fa fa-spin fa-refresh"></i>&nbsp; Loading More Data
                        </button>
                      </div>

                      <!-- </div> -->
                      <!-- </div> -->
                    </div>
                  </div>

                </div>
                <!-- /.box-body -->
              </div>
              <!-- /.box -->

              <!-- /.box -->
            </div>
            <!--/.col (right) -->
          </div>
          <!-- /.row -->
        </section>

      </div>
    </div>
    <!-- /.modal-content -->
  </div>
</div>

<div class="col-md-12">
  <!-- ********** ALERT MESSAGE START******* -->
  <?php if (demo_app()) { ?>
    <div class="alert alert-success  text-left">
      <a href="javascript:void()" class="close" data-dismiss="alert" aria-label="close">&times;</a>
      <strong>
        Ultimate Inventory with POS new Version <?= app_version(); ?> released , Faster and Customizable Application Software. If you have any queries please message <a target='_blank' href='https://codecanyon.net/item/ultimate-inventory-with-pos/23992003/comments'>here</a>. [Some features are disabled in demo and it will be reset after each hour.]
      </strong>
    </div>
  <?php } ?>
  <?php
  if ($this->session->flashdata('success') != '') :
  ?>
    <div class="alert alert-success alert-dismissable text-center">
      <a href="javascript:void()" class="close" data-dismiss="alert" aria-label="close">&times;</a>
      <strong><?= $this->session->flashdata('success') ?></strong>
    </div>
  <?php
  endif;
  if ($this->session->flashdata('error') != '') :
  ?>
    <div class="alert alert-danger alert-dismissable text-center">
      <a href="javascript:void()" class="close" data-dismiss="alert" aria-label="close">&times;</a>
      <strong><?= $this->session->flashdata('error') ?></strong>
    </div>
  <?php
  endif;
  if ($this->session->flashdata('warning') != '') :
  ?>
    <div class="alert alert-warning alert-dismissable text-center">
      <a href="javascript:void()" class="close" data-dismiss="alert" aria-label="close">&times;</a>
      <strong><?= $this->session->flashdata('warning') ?></strong>
    </div>
  <?php
  endif;
  ?>
  <!-- ********** ALERT MESSAGE END******* -->
</div>



<!-- Hidden form for database restore -->
<div class="modal fade" id="restoreModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-sm" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Database Restore</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form id="restoreDatabaseForm" method="post" action="<?php echo base_url('pos/restore_database'); ?>" enctype="multipart/form-data">
          <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
          <label for="backupFile">Select Backup File:</label><br>
          <input type="file" id="backupFile" name="backupFile"><br><br>
          <input type="submit" value="Restore" class="btn btn-primary">
        </form>

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


<!-- AdminLTE App -->
<script>
  var AdminLTEOptions = {
    /*https://adminlte.io/themes/AdminLTE/documentation/index.html*/
    sidebarExpandOnHover: true,
    navbarMenuHeight: "200px", //The height of the inner menu
    animationSpeed: 250,
  };
</script>
<!-- FastClick -->
<script src="<?php echo $theme_link; ?>plugins/fastclick/fastclick.js"></script>
<!-- Select2 -->
<script src="<?php echo $theme_link; ?>plugins/select2/select2.full.min.js"></script>
<!-- AdminLTE for demo purposes -->
<!-- <script src="<?php echo $theme_link; ?>dist/js/demo.js"></script> -->
<!--Toastr notification -->
<script src="<?php echo $theme_link; ?>toastr/toastr.js"></script>
<script src="<?php echo $theme_link; ?>toastr/toastr_custom.js"></script>
<!-- bootstrap datepicker -->
<script src="<?php echo $theme_link; ?>plugins/daterangepicker/moment.min.js"></script>
<script src="<?php echo $theme_link; ?>plugins/daterangepicker/daterangepicker.js"></script>
<!-- bootstrap datepicker -->
<script src="<?php echo $theme_link; ?>plugins/datepicker/bootstrap-datepicker.js"></script>
<script src="<?php echo $theme_link; ?>js/sweetalert.min.js"></script>
<script src="<?php echo $theme_link; ?>plugins/shortcuts/shortcuts.js"></script>
<script src="<?php echo $theme_link; ?>js/special_char_check.js"></script>
<script src="<?php echo $theme_link; ?>js/custom.js"></script>
<script src="<?php echo $theme_link; ?>js/sweetalert.min.js"></script>
<script src="<?php echo $theme_link; ?>plugins/autocomplete/autocomplete.js"></script>
<!-- <script>
  $(function() {
    $('input').iCheck({
      checkboxClass: 'icheckbox_square-orange',
      /*uncheckedClass: 'bg-white',*/
      radioClass: 'iradio_square-orange',
      increaseArea: '10%' // optional
    });
  });
</script> -->


<script type="text/javascript">
  $(function($) { // this script needs to be loaded on every page where an ajax POST may happen
    $.ajaxSetup({
      data: {
        '<?php echo $this->security->get_csrf_token_name(); ?>': '<?php echo $this->security->get_csrf_hash(); ?>'
      }
    });
  });
</script>
<script type="text/javascript">
  //Date picker
  $('.datepicker').datepicker({
    autoclose: true,
    format: '<?php echo $VIEW_DATE; ?>',
    todayHighlight: true
  });
</script>
<script>
  function discountModalClose() {
    $('#discount-modal').modal('hide');
  }
  $(function() {
    //Date range as a button
    $('.daterange-btn').daterangepicker({
        ranges: {
          'Today': [moment(), moment()],
          'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
          'Last 7 Days': [moment().subtract(6, 'days'), moment()],
          'Last 30 Days': [moment().subtract(29, 'days'), moment()],
          'This Month': [moment().startOf('month'), moment().endOf('month')],
          'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        },
        startDate: moment().subtract(29, 'days'),
        endDate: moment()
      },
      function(start, end) {
        $('.daterange-btn span').html(start.format('<?php echo strtoupper($VIEW_DATE); ?>') + ' - ' + end.format('<?php echo strtoupper($VIEW_DATE); ?>'))
      }
    );
  });
</script>
<script type="text/javascript">
  $(document).ready(function() {
    $('[data-toggle="popover"]').popover();
  });
</script>


<script type="text/javascript">
  $(document).ajaxStart(function() {
    Pace.restart();
  });
</script>
<script type="text/javascript">
  $(document).ready(function() {
    setTimeout(function() {
      $(".alert-dismissable").fadeOut(1000, function() {});
    }, 10000);
  });
</script>
<script type="text/javascript">
  function round_off(input = 0) {
    <?php if (is_enabled_round_off()) { ?>
      return Math.round(input);
    <?php } else { ?>
      return input;
    <?php } ?>
  }
</script>
<script>
  function tax_disabled() {
    <?php if (is_tax_disabled()) { ?>
      return true;
    <?php } else { ?>
      return false;
    <?php } ?>
  }
</script>



<script>
  /*Email validation code*/
  function validateEmail(sEmail) {
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if (filter.test(sEmail)) {
      return true;
    } else {
      return false;
    }
  }
  /*Email validation code end*/
  /* customers modal start*/
  $(".add_customer1").on("click", function(e) {
    var base_url = $("#base_url").val().trim();
    //Initially flag set true
    var flag = true;

    function check_field(id) {
      if (!$("#" + id + "1").val().trim()) //Also check Others????
      {

        $('#' + id + '_msg').fadeIn(200).show().html('Required Field').addClass('required');
        $('#' + id).css({
          'background-color': '#E8E2E9'
        });
        flag = false;
      } else {
        $('#' + id + '_msg').fadeOut(200).hide();
        $('#' + id).css({
          'background-color': '#FFFFFF'
        }); //White color
      }
    }
    //Validate Input box or selection box should not be blank or empty
    check_field("customer_name");
    //check_field("state");


    if (flag == false) {
      toastr["warning"]("You have Missed Something to Fillup!");
      return;
    }
    var email = $("#email1").val().trim();
    if (email != '' && !validateEmail(email)) {
      $("#email_msg1").html("Invalid Email!").show();
      //flag=false;
      toastr["warning"]("Please Enter valid Email ID.")
      return;
    } else {
      $("#email_msg1").html("Invalid Email!").hide();
    }
    var this_id = this.id;



    // if (confirm("Are you Sure ?")) {
    e.preventDefault();
    data = new FormData($('#customer-form1')[0]); //form name
    /*Check XSS Code*/
    if (!xss_validation(data)) {
      return false;
    }

    $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
    $("#" + this_id).attr('disabled', true); //Enable Save or Update button
    $.ajax({
      type: 'POST',
      url: base_url + 'pos/newcustomer',
      data: data,
      cache: false,
      contentType: false,
      processData: false,
      success: function(result) {
        //alert(result);//return;
        var data = jQuery.parseJSON(result);
        if (data.result == "success") {
          $('#customer-modal1').modal('toggle');
          var newOption = '<option value=' + data.id + ' selected>' + data.customer_name + '</option>';
          $('#customer_id1').append(newOption).trigger('change');
          //$("#amount").val(data.advance);
          $('#customer-form1')[0].reset();
          toastr["success"]("New Customer Added!!");
          success.currentTime = 0;
          success.play();
        } else if (data.result == "failed") {
          toastr["error"]("Sorry! Failed to save Record.Try again!");
          failed.currentTime = 0;
          failed.play();
        } else {
          toastr["error"](data.result);
          failed.currentTime = 0;
          failed.play();
        }
        $("#" + this_id).attr('disabled', false); //Enable Save or Update button
        $(".overlay").remove();

      }
    });
    // } //confirmation sure


    //e.preventDefault
  });
  /* customers modal end */
  /* Suppliers modals start*/
  $(".add_supplier").on("click", function(e) {
    var base_url = $("#base_url").val().trim();
    //Initially flag set true
    var flag = true;

    function check_field(id) {
      if (!$("#" + id).val().trim()) //Also check Others????
      {

        $('#' + id + '_msg').fadeIn(200).show().html('Required Field').addClass('required');
        $('#' + id).css({
          'background-color': '#E8E2E9'
        });
        flag = false;
      } else {
        $('#' + id + '_msg').fadeOut(200).hide();
        $('#' + id).css({
          'background-color': '#FFFFFF'
        }); //White color
      }
    }
    //Validate Input box or selection box should not be blank or empty
    check_field("supplier_name");
    //check_field("state");


    if (flag == false) {
      toastr["warning"]("You have Missed Something to Fillup!");
      return;
    }
    var email = $("#email").val().trim();
    if (email != '' && !validateEmail(email)) {
      $("#email_msg").html("Invalid Email!").show();
      //flag=false;
      toastr["warning"]("Please Enter valid Email ID.")
      return;
    } else {
      $("#email_msg").html("Invalid Email!").hide();
    }
    var this_id = this.id;



    // if (confirm("Are you Sure ?")) {

    e.preventDefault();
    data = new FormData($('#supplier-form')[0]); //form name
    /*Check XSS Code*/
    if (!xss_validation(data)) {
      return false;
    }

    $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
    $("#" + this_id).attr('disabled', true); //Enable Save or Update button
    $.ajax({
      type: 'POST',
      url: base_url + 'purchase/newsupplier',
      data: data,
      cache: false,
      contentType: false,
      processData: false,
      success: function(result) {
        //alert(result);//return;
        var data = jQuery.parseJSON(result);
        if (data.result == "success") {
          $('#supplier-modal').modal('toggle');
          var newOption = '<option value=' + data.id + ' selected>' + data.supplier_name + '</option>';
          $('#supplier_id').append(newOption).trigger('change');
          //$("#amount").val(data.advance);
          $('#supplier-form')[0].reset();
          toastr["success"]("New supplier Added!!");
          success.currentTime = 0;
          success.play();
        } else if (data.result == "failed") {
          toastr["error"]("Sorry! Failed to save Record.Try again!");
          failed.currentTime = 0;
          failed.play();
        } else {
          toastr["error"](data.result);
          failed.currentTime = 0;
          failed.play();
        }
        $("#" + this_id).attr('disabled', false); //Enable Save or Update button
        $(".overlay").remove();

      }
    });
    // } //confirmation sure


    //e.preventDefault
  });
  /* Suppliers modal end*/
  /* brand modal start*/
  $(".add_brand1").on("click", function(e) {
    var base_url = $("#base_url").val().trim();
    //Initially flag set true
    var flag = true;

    function check_field(id) {
      if (!$("#" + id).val().trim()) //Also check Others????
      {

        $('#' + id + '_msg').fadeIn(200).show().html('Required Field').addClass('required');
        $('#' + id).css({
          'background-color': '#E8E2E9'
        });
        flag = false;
      } else {
        $('#' + id + '_msg').fadeOut(200).hide();
        $('#' + id).css({
          'background-color': '#FFFFFF'
        }); //White color
      }
    }
    //Validate Input box or selection box should not be blank or empty
    check_field("brand");


    if (flag == false) {
      toastr["warning"]("You have Missed Something to Fillup!");
      return;
    }

    var this_id = this.id;

    // if (confirm("Are you Sure ?")) {
    e.preventDefault();
    data = new FormData($('#brand_form')[0]); //form name
    /*Check XSS Code*/
    if (!xss_validation(data)) {
      return false;
    }

    $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
    $("#" + this_id).attr('disabled', true); //Enable Save or Update button
    $.ajax({
      type: 'POST',
      url: base_url + 'brands/add_brand_modal',
      data: data,
      cache: false,
      contentType: false,
      processData: false,
      success: function(result) {
        //alert(result);//return;
        var data = jQuery.parseJSON(result);
        if (data.result == "success") {
          $('#brand_modal1').modal('toggle');
          var newOption = '<option value=' + data.id + ' selected>' + data.brand + '</option>';
          $('#brand_id').append(newOption).trigger('change');
          //$("#amount").val(data.advance);
          $('#brand_form1')[0].reset();
          toastr["success"]("New brand Added!!");
          success.currentTime = 0;
          success.play();
        } else if (data.result == "failed") {
          toastr["error"]("Sorry! Failed to save Record.Try again!");
          failed.currentTime = 0;
          failed.play();
        } else {
          toastr["error"](data.result);
          failed.currentTime = 0;
          failed.play();
        }
        $("#" + this_id).attr('disabled', false); //Enable Save or Update button
        $(".overlay").remove();

      }
    });
    // } //confirmation sure


    //e.preventDefault
  });
  /* brands modal end */
  /* category modal start*/
  $(".add_category1").on("click", function(e) {
    var base_url = $("#base_url").val().trim();
    //Initially flag set true
    var flag = true;

    function check_field(id) {
      if (!$("#" + id).val().trim()) //Also check Others????
      {

        $('#' + id + '_msg').fadeIn(200).show().html('Required Field').addClass('required');
        $('#' + id).css({
          'background-color': '#E8E2E9'
        });
        flag = false;
      } else {
        $('#' + id + '_msg').fadeOut(200).hide();
        $('#' + id).css({
          'background-color': '#FFFFFF'
        }); //White color
      }
    }
    //Validate Input box or selection box should not be blank or empty
    check_field("category");


    if (flag == false) {
      toastr["warning"]("You have Missed Something to Fillup!");
      return;
    }

    var this_id = this.id;

    // if (confirm("Are you Sure ?")) {
    e.preventDefault();
    data = new FormData($('#category_form1')[0]); //form name
    /*Check XSS Code*/
    if (!xss_validation(data)) {
      return false;
    }

    $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
    $("#" + this_id).attr('disabled', true); //Enable Save or Update button
    $.ajax({
      type: 'POST',
      url: base_url + 'category/add_category_modal',
      data: data,
      cache: false,
      contentType: false,
      processData: false,
      success: function(result) {
        //alert(result);//return;
        var data = jQuery.parseJSON(result);
        if (data.result == "success") {
          $('#category_modal1').modal('toggle');
          var newOption = '<option value=' + data.id + ' selected>' + data.category + '</option>';
          $('#category_id').append(newOption).trigger('change');
          //$("#amount").val(data.advance);
          $('#category_form1')[0].reset();
          toastr["success"]("New category Added!!");
          success.currentTime = 0;
          success.play();
        } else if (data.result == "failed") {
          toastr["error"]("Sorry! Failed to save Record.Try again!");
          failed.currentTime = 0;
          failed.play();
        } else {
          toastr["error"](data.result);
          failed.currentTime = 0;
          failed.play();
        }
        $("#" + this_id).attr('disabled', false); //Enable Save or Update button
        $(".overlay").remove();

      }
    });
    // } //confirmation sure


    //e.preventDefault
  });
  /* categorys modal end */
  /* unit modal start*/
  $(".add_unit1").on("click", function(e) {
    var base_url = $("#base_url").val().trim();
    //Initially flag set true
    var flag = true;

    function check_field(id) {
      if (!$("#" + id).val().trim()) //Also check Others????
      {

        $('#' + id + '_msg').fadeIn(200).show().html('Required Field').addClass('required');
        $('#' + id).css({
          'background-color': '#E8E2E9'
        });
        flag = false;
      } else {
        $('#' + id + '_msg').fadeOut(200).hide();
        $('#' + id).css({
          'background-color': '#FFFFFF'
        }); //White color
      }
    }
    //Validate Input box or selection box should not be blank or empty
    check_field("unit_name");


    if (flag == false) {
      toastr["warning"]("You have Missed Something to Fillup!");
      return;
    }

    var this_id = this.id;

    // if (confirm("Are you Sure ?")) {
    e.preventDefault();
    data = new FormData($('#unit_form1')[0]); //form name
    /*Check XSS Code*/
    if (!xss_validation(data)) {
      return false;
    }

    $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
    $("#" + this_id).attr('disabled', true); //Enable Save or Update button
    $.ajax({
      type: 'POST',
      url: base_url + 'units/add_unit_modal',
      data: data,
      cache: false,
      contentType: false,
      processData: false,
      success: function(result) {
        //alert(result);//return;
        var data = jQuery.parseJSON(result);
        if (data.result == "success") {
          $('#unit_modal1').modal('toggle');
          var newOption = '<option value=' + data.id + ' selected>' + data.unit + '</option>';
          $('#unit_id').append(newOption).trigger('change');
          //$("#amount").val(data.advance);
          $('#unit_form1')[0].reset();
          toastr["success"]("New unit Added!!");
          success.currentTime = 0;
          success.play();
        } else if (data.result == "failed") {
          toastr["error"]("Sorry! Failed to save Record.Try again!");
          failed.currentTime = 0;
          failed.play();
        } else {
          toastr["error"](data.result);
          failed.currentTime = 0;
          failed.play();
        }
        $("#" + this_id).attr('disabled', false); //Enable Save or Update button
        $(".overlay").remove();

      }
    });
    // } //confirmation sure


    //e.preventDefault
  });
  /* units modal end */
  /* tax modal start*/
  $(".add_tax1").on("click", function(e) {
    var base_url = $("#base_url").val().trim();
    //Initially flag set true
    var flag = true;

    function check_field(id) {
      if (!$("#" + id).val().trim()) //Also check Others????
      {

        $('#' + id + '_msg').fadeIn(200).show().html('Required Field').addClass('required');
        $('#' + id).css({
          'background-color': '#E8E2E9'
        });
        flag = false;
      } else {
        $('#' + id + '_msg').fadeOut(200).hide();
        $('#' + id).css({
          'background-color': '#FFFFFF'
        }); //White color
      }
    }
    //Validate Input box or selection box should not be blank or empty
    check_field("tax_name");
    check_field("tax");


    if (flag == false) {
      toastr["warning"]("You have Missed Something to Fillup!");
      return;
    }

    var this_id = this.id;

    // if (confirm("Are you Sure ?")) {
    e.preventDefault();
    data = new FormData($('#tax_form1')[0]); //form name
    /*Check XSS Code*/
    if (!xss_validation(data)) {
      return false;
    }

    $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
    $("#" + this_id).attr('disabled', true); //Enable Save or Update button
    $.ajax({
      type: 'POST',
      url: base_url + 'tax/add_tax_modal',
      data: data,
      cache: false,
      contentType: false,
      processData: false,
      success: function(result) {
        //alert(result);//return;
        var data = jQuery.parseJSON(result);
        if (data.result == "success") {
          $('#tax_modal1').modal('toggle');
          var newOption = '<option data-tax=' + data.tax + ' value=' + data.id + ' selected>' + data.tax_name + '(' + data.tax + ')</option>';
          $('#tax_id').append(newOption).trigger('change');
          //$("#amount").val(data.advance);
          $('#tax_form1')[0].reset();
          toastr["success"]("New tax Added!!");
          success.currentTime = 0;
          success.play();
        } else if (data.result == "failed") {
          toastr["error"]("Sorry! Failed to save Record.Try again!");
          failed.currentTime = 0;
          failed.play();
        } else {
          toastr["error"](data.result);
          failed.currentTime = 0;
          failed.play();
        }
        $("#" + this_id).attr('disabled', false); //Enable Save or Update button
        $(".overlay").remove();

      }
    });
    // } //confirmation sure


    //e.preventDefault
  });
  $(".<?php echo basename(__FILE__, '.php'); ?>-active-li").addClass("active");
</script>

<script src="<?php echo $theme_link; ?>plugins/iCheck/icheck.min.js"></script>

<script src="<?php echo $theme_link; ?>js/fullscreen.js"></script>
<script src="<?php echo $theme_link; ?>js/modals.js"></script>
<script src="<?php echo $theme_link; ?>js/pos.js?v=164"></script>
<script src="<?php echo $theme_link; ?>dist/js/bootstrap3-typeahead.min.js"></script>

<script>
  $("#other_charges1").keyup(function(event) {
    final_total();
  });
  //RIGHT SIT DIV:-> FILTER ITEM INTO THE ITEMS LIST
  function search_it() {

    var input = $("#search_it").val().trim();
    var item_count = $(".search_div .search_item").length;
    var error_count = item_count;
    for (i = 0; i < item_count; i++) {

      if ($("#item_" + i).html().toUpperCase().indexOf(input.toUpperCase()) > -1) {

        $("#item_" + i).show();
        $("#item_parent_" + i).show();
      } else {

        $("#item_" + i).hide();
        $("#item_parent_" + i).hide();
        error_count--;
      }
      if (error_count == 0) {
        $(".error_div").show();
      } else {
        $(".error_div").hide();
      }

    }
  }

  //LEFT SIDE: ON CLICK ITEM ADD TO INVOICE LIST
  function addrow1(id = '', item_obj = '') {

    var item_id = (item_obj == '') ? $('#div1_' + id).attr('data-item-id') : item_obj.item_id;
    var item_check = check_same_item(item_id);
    if (!item_check) {
      return false;
    }
    var rowcount = $("#hidden_rowcount1").val(); //0,1,2...


    var item_name = (item_obj == '') ? $('#div1_' + id).attr('data-item-name') : item_obj.item_name;

    var stock = (item_obj == '') ? $('#div1_' + id).attr('data-item-available-qty') : item_obj.stock;
    stock = (parseFloat(stock)).toFixed(2);

    var tax_type = (item_obj == '') ? $('#div1_' + id).attr('data-item-tax-type') : item_obj.tax_type;
    var tax_id = (item_obj == '') ? $('#div1_' + id).attr('data-item-tax-id') : item_obj.tax_id;
    var tax_value = (item_obj == '') ? $('#div1_' + id).attr('data-item-tax-value') : item_obj.tax;

    var tax_name = (item_obj == '') ? $('#div1_' + id).attr('data-item-tax-name') : item_obj.tax_name;
    var tax_amt = (item_obj == '') ? $('#div1_' + id).attr('data-item-tax-amt') : item_obj.item_tax_amt;
    var purchase_price = (item_obj == '') ? $('#div1_' + id).attr('data-purchase_price') : item_obj.purchase_price;
    //var gst_per         =$('#div1_'+id).attr('data-item-tax-per');
    //var gst_amt         =$('#div1_'+id).attr('data-item-gst-amt');
    var discount_type = (item_obj == '') ? $('#div1_' + id).attr('data-discount_type') : item_obj.discount_type;
    var discount = (item_obj == '') ? $('#div1_' + id).attr('data-discount') : item_obj.discount;

    var item_cost = (item_obj == '') ? $('#div1_' + id).attr('data-item-cost') : item_obj.purchase_price;
    var sales_price = (item_obj == '') ? $('#div1_' + id).attr('data-item-sales-price') : item_obj.sales_price;
    var sales_price_temp = sales_price;
    sales_price = (parseFloat(sales_price)).toFixed(2);

    if (stock > 0) {
      if (stock > 1) {
        qty = 1;
      } else {
        qty = stock;
      }
    } else {
      zero_stock1();
      return;
    }
    var quantity = '<div class="input-group input-group-sm"><span class="input-group-btn"><button onclick="decrement_qty(' + item_id + ',' + rowcount + ')" type="button" class="btn btn-default btn-flat"><i class="fa fa-minus text-danger"></i></button></span>';
    quantity += '<input type="text" value="' + qty + '" class="form-control text-center no-padding text-center min_width td_input_size" onchange="item_qty1_input(' + item_id + ',' + rowcount + ')" id="item_qty1_' + item_id + '" name="item_qty1_' + item_id + '">';
    quantity += '<span class="input-group-btn"><button onclick="increment_qty(' + item_id + ',' + rowcount + ')" type="button" class="btn btn-default btn-flat"><i class="fa fa-plus text-success"></i></button></span></div>';
    var sub_total = (parseFloat(1) * parseFloat(sales_price)).toFixed(2); //Initial
    var remove_btn = '<a class="fa fa-fw fa-trash-o text-red" style="cursor: pointer;font-size: 20px;" onclick="removerow(' + rowcount + ')" title="Delete Item?"></a>';

    var str = ' <tr id="row1_' + rowcount + '" data-row="0" data-item-id=' + item_id + '>'; /*item id*/
    str += '<td id="td1_' + rowcount + '_0"><a data-toggle="tooltip" onclick="toggleRowDetails(' + rowcount + ')" title="Click to Change Tax" class="td_font_size pointer item-name" id="td_data1_' + rowcount + '_0">' + item_name + '  <i class="fa fa-eye pointer"></i></a></td>'; /* td_0_0 item name*/

    str += '<td  class="details td_font_size"><div class="col-md-3 text-left">Stock:</div><div class="col-md-9 text-center" id="td1_' + rowcount + '_1">' + stock + '</div></div></td>'; /* td_0_1 item available qty*/
    str += '<td class="details td_font_size"><div style="display:flex !important;justify-content:space-around !important"><div class="col-md-3 text-left">Quantity:</div><div class="col-md-9"  id="td1_' + rowcount + '_2">' + quantity + '</div></div></td>'; /* td_0_2 item available qty*/



    info = '<input id="sales_price1_' + rowcount + '" onblur="set_to_original(' + rowcount + ',' + item_cost + ')" onkeyup="update_price(' + rowcount + ',' + item_cost + ')" name="sales_price_' + rowcount + '" type="text" class="form-control no-padding min_width td_input_size  text-center  text-center" value="' + sales_price + '">';
    str += '<td class="details text-right td_font_size"><div style="display:flex !important;justify-content:space-around !important"><div class="col-md-3 text-left">Price:</div><div class="col-md-9" id="td1_' + rowcount + '_3" >' + info + '</div></div></td>'; /* td_0_3 item sales price*/

    /*Discount*/
    info = '<input data-toggle="tooltip" title="Click to Change" onclick="show_sales_item_modal(' + rowcount + ')" id="item_discount1_' + rowcount + '" readonly name="item_discount_' + rowcount + '" type="text" class="form-control no-padding min_width pointer td_input_size td_input_size  text-center" value="0">';

    str += '<td class="details text-right td_font_size"><div style="display:flex !important;justify-content:space-around !important"><div class="col-md-3 text-left">Discount:</div><div class="col-md-9" id="td1_' + rowcount + '_6" >' + info + '</div></div></td>';

    /*Tax amt*/
    str += '<td class="details td_font_size <?= tax_disable_class() ?>"><div style="display:flex !important;justify-content:space-around !important"><div class="col-md-3 text-left">Tax:</div><div class="col-md-9" id="td1_' + rowcount + '_11" ><input data-toggle="tooltip" title="Click to Change" id="td_data1_' + rowcount + '_11" onclick="show_sales_item_modal(' + rowcount + ')" name="td_data1_' + rowcount + '_11" type="text" class="td_input_size form-control  text-center no-padding pointer min_width" readonly value="' + tax_amt + '"></div></div></td>';

    str += '<td class="text-right td_font_size"><div style="display:flex !important;justify-content:space-around !important"><div class="col-md-3 text-left">Subtotal:</div><div class="col-md-9"><input data-toggle="tooltip" title="Total" id="td_data1_' + rowcount + '_4" name="td_data1_' + rowcount + '_4" type="text" class="form-control  text-center no-padding pointer td_input_size" readonly value="' + sub_total + '"></div></td>'; /* td_0_4 item sub_total */
    str += '<td class="text-right" ><div class="col-sm-12 text-center" id="td1_' + rowcount + '_5">' + remove_btn + '</div></td>'; /* td_0_5 item gst_amt */



    str += '<input type="hidden" name="tr_item_id1_' + rowcount + '" id="tr_item_id1_' + rowcount + '" value="' + item_id + '">';
    // str+='<input type="hidden" id="tr_item_per_'+rowcount+'" name="tr_item_per_'+rowcount+'" value="'+gst_per+'">';
    str += '<input type="hidden" id="tr_sales_price_temp_' + rowcount + '" name="tr_sales_price_temp_' + rowcount + '" value="' + sales_price_temp + '">';
    str += '<input type="hidden" id="tr_tax_type_' + rowcount + '" name="tr_tax_type_' + rowcount + '" value="' + tax_type + '">';
    str += '<input type="hidden" id="tr_tax_id_' + rowcount + '" name="tr_tax_id_' + rowcount + '" value="' + tax_id + '">';
    str += '<input type="hidden" id="tr_tax_value_' + rowcount + '" name="tr_tax_value_' + rowcount + '" value="' + tax_value + '">';
    str += '<input type="hidden" id="description_' + rowcount + '" name="description_' + rowcount + '" value="">';
    str += '<input id="item_discount_type1_' + rowcount + '" name="item_discount_type_' + rowcount + '" type="hidden" value="' + discount_type + '">';
    str += '<input id="item_discount_input1_' + rowcount + '" name="item_discount_input_' + rowcount + '" type="hidden" value="' + discount + '">';
    str += '<input type="hidden" id="purchase_price_' + rowcount + '" name="purchase_price_' + rowcount + '" value="' + purchase_price + '">';

    str += '</tr>';

    //LEFT SIDE: ADD OR APPEND TO SALES INVOICE TERMINAL
    $('#pos-form-tbody').append(str);

    //LEFT SIDE: INCREMANT ROW COUNT
    $("#hidden_rowcount1").val(parseFloat($("#hidden_rowcount1").val()) + 1);
    failed.currentTime = 0;
    failed.play();
    //CALCULATE FINAL TOTAL AND OTHER OPERATIONS
    //final_total();

    make_subtotal(item_id, rowcount);

  }

  function toggleRowDetails(rowcount) {
    var $row = $('#row1_' + rowcount);
    var $row = $('#row1_' + rowcount).closest('tr'); // Find the closest <tr> element relative to the button

    if ($row.length > 0) {
      // Toggle visibility of the row by toggling a CSS class like 'inline-grid'
      $row.toggleClass('inline-grid');
    } else {
      console.error('Row element not found for rowcount: ' + rowcount);
    }
    var $details = $row.find('td.details');
    var $icon = $row.find('.item-name i');

    // Toggle visibility of details within the row
    $details.each(function() {
      $(this).css('display', function(_, value) {
        return value === 'none' ? 'ruby-text' : 'none';
      });
    });
    // Toggle icons based on visibility of details
    if ($details.is(':visible')) {
      // Details are visible, show fa-eye-slash icon
      $icon.removeClass('fa-eye').addClass('fa-eye-slash');
    } else {
      // Details are hidden, show fa-eye icon
      $icon.removeClass('fa-eye-slash').addClass('fa-eye');
    }
  }

  function update_price(row_id, item_cost) {
    make_subtotal($("#tr_item_id1_" + row_id).val(), row_id);
  }

  function set_to_original(row_id, item_cost) {
    return true;
    /*Input*/
    var sales_price = $("#sales_price1_" + row_id).val().trim();
    if (sales_price != '' || sales_price == 0) {
      sales_price = parseFloat(sales_price);
    }

    /*Default set from item master*/
    var item_price = parseFloat($("#tr_sales_price_temp_" + row_id).val().trim());

    if (sales_price < item_cost) {
      toastr["success"]("Default Price Set " + item_price);
      $("#sales_price1_" + row_id).parent().removeClass('has-error');
      $("#sales_price1_" + row_id).val(item_price);
    }
    make_subtotal($("#tr_item_id1_" + row_id).val(), row_id);
  }


  //INCREMENT ITEM
  function increment_qty(item_id, rowcount) {
    var item_qty = $("#item_qty1_" + item_id).val();
    var stock = $("#td1_" + rowcount + "_1").html();

    if (parseFloat(item_qty) < parseFloat(stock)) {
      new_item_qty = parseFloat(item_qty) + 1;

      if (parseFloat(new_item_qty) > parseFloat(stock)) {
        new_item_qty = stock;
      }

      $("#item_qty1_" + item_id).val(parseFloat(new_item_qty).toFixed(2));
    }
    make_subtotal(item_id, rowcount);
  }
  //DECREMENT ITEM
  function decrement_qty(item_id, rowcount) {
    var item_qty = parseFloat($("#item_qty1_" + item_id).val());
    item_qty = isNaN(item_qty) ? 0 : item_qty;
    var stock = parseFloat($("#td1_" + rowcount + "_1").html());
    stock = isNaN(stock) ? 0 : stock;

    if (item_qty < 1) {
      $("#item_qty1_" + item_id).val((item_qty).toFixed(2));
      toastr["warning"]("Minimum Stock!");
      return;
    }
    if (item_qty <= 1) {
      $("#item_qty1_" + item_id).val((1).toFixed(2));
      toastr["warning"]("Minimum Stock!");
      return;
    }

    $("#item_qty1_" + item_id).val((parseFloat(item_qty) - 1).toFixed(2));
    make_subtotal(item_id, rowcount);
  }
  //LEFT SIDE: IF ITEM QTY CHANGED MANUALLY
  function item_qty1_input(item_id, rowcount) {
    var item_qty = parseFloat($("#item_qty1_" + item_id).val());
    var stock = parseFloat($("#td1_" + rowcount + "_1").html());

    if (isNaN(item_qty) || item_qty <= 0) {
      $("#item_qty1_" + item_id).val(1);
      toastr["warning"]("Invalid quantity. Quantity set to 1.");
      item_qty = 1;
    }

    if (item_qty > stock) {
      $("#item_qty1_" + item_id).val(stock);
      toastr["warning"]("Quantity exceeds available stock. Quantity set to " + stock + ".");
      item_qty = stock;
    }

    make_subtotal(item_id, rowcount);
  }


  function zero_stock() {
    toastr["error"]("Out of Stock!");
    return;
  }
  //LEFT SIDE: REMOVE ROW 
  function removerow(id) { //id=Rowid  
    $("#row1_" + id).remove();
    failed.currentTime = 0;
    failed.play();
    final_total();
  }

  //MAKE SUBTOTAL
  function make_subtotal(item_id, rowcount) {
    set_tax_value(rowcount);

    var tax_type = $("#tr_tax_type_" + rowcount).val();
    var tax_amount = parseFloat($("#td_data1_" + rowcount + "_11").val());

    var sales_price = parseFloat($("#sales_price1_" + rowcount).val());
    var item_qty = parseFloat($("#item_qty1_" + item_id).val());

    var subtotal = item_qty * sales_price;
    subtotal += (tax_type == 'Inclusive') ? 0 : tax_amount;

    var discount_amt = parseFloat($("#item_discount1_" + rowcount).val());
    subtotal -= discount_amt;

    $("#td_data1_" + rowcount + "_4").val(subtotal.toFixed(2));
    final_total();
  }

  function calulate_discount(discount_input, discount_type, total) {
    if (discount_type == 'in_percentage') {
      return parseFloat((total * discount_input) / 100);
    } else { //in_fixed
      return parseFloat(discount_input);
    }
  }
  //LEFT SIDE: FINAL TOTAL
  function final_total() {
    var total = 0;
    var item_qty = 0;
    var rowcount = $("#hidden_rowcount1").val();
    var discount_input = $("#discount_input1").val();
    var discount_type = $("#discount_type1").val();
    var other_charges = parseFloat($("#other_charges1").val());
    other_charges = (isNaN(other_charges)) ? parseFloat(0) : other_charges;
    if ($(".items_table tr").length > 1) {
      for (i = 0; i < rowcount; i++) {
        if (document.getElementById('tr_item_id1_' + i)) {
          item_id = $("#tr_item_id1_" + i).val();

          total = parseFloat(total) + + +parseFloat($("#td_data1_" + i + "_4").val()).toFixed(2);
          item_qty = parseFloat(item_qty) + + +parseFloat($("#item_qty1_" + item_id).val()).toFixed(2);
        }
      } //for end
    } //items_table

    total += other_charges;
    total = round_off(total);

    var discount_amt = 0;
    if (total > 0) {
      var discount_amt = calulate_discount(discount_input, discount_type, total); //return value 
    }

    set_total(item_qty, total, discount_amt, total - discount_amt);
  }

  function set_total(tot_qty = 0, tot_amt = 0, tot_disc = 0, tot_grand = 0) {
    $(".tot_qty1").html(tot_qty);
    $(".tot_amt1").html((round_off(tot_amt).toFixed(2)));
    $(".tot_disc1").html((round_off(tot_disc).toFixed(2)));
    $(".tot_grand1").html((round_off(tot_grand)).toFixed(2));
  }

  //LEFT SIDE: FINAL TOTAL
  function adjust_payments() {
    var total = 0;
    var item_qty = 0;
    var rowcount = $("#hidden_rowcount1").val();
    var discount_input = $("#discount_input1").val();
    var discount_type = $("#discount_type1").val();
    var other_charges = parseFloat($("#other_charges1").val());
    other_charges = (isNaN(other_charges)) ? parseFloat(0) : other_charges;

    if ($(".items_table tr").length > 1) {
      for (i = 0; i < rowcount; i++) {
        if (document.getElementById('tr_item_id1_' + i)) {
          total = parseFloat(total) + + +parseFloat($("#td_data1_" + i + "_4").val()).toFixed(2);
          item_id = $("#tr_item_id1_" + i).val();
          item_qty = parseFloat(item_qty) + + +parseFloat($("#item_qty1_" + item_id).val()).toFixed(2);
        }
      } //for end
    } //items_table
    total += other_charges;
    total = round_off(total);
    //Find customers payment

    var payments_row = get_id_value("payment_row_count");
    console.log("payments_row=" + payments_row);
    var paid_amount = parseFloat(0);
    for (var i = 1; i <= payments_row; i++) {
      if (document.getElementById("amount_" + i)) {
        var amount = parseFloat(get_id_value("amount_" + i));
        amount = isNaN(amount) ? 0 : amount;
        console.log("amount_" + i + "=" + amount);
        paid_amount += amount;
      }
    }

    //RIGHT SIDE DIV
    var discount_amt = calulate_discount(discount_input, discount_type, total); //return value


    var change_return = 0;
    var balance = total - discount_amt - paid_amount;
    if (balance < 0) {
      //console.log("Negative");
      change_return = Math.abs(parseFloat(balance));
      balance = 0;
    }

    balance = round_off(balance);
    $(".sales_div_tot_qty").html(item_qty);
    $(".sales_div_tot_amt").html((round_off(total)).toFixed(2));
    $(".sales_div_tot_discount").html((parseFloat(round_off(discount_amt))).toFixed(2));
    $(".sales_div_tot_payble").html((parseFloat(round_off(total - discount_amt))).toFixed(2));
    $(".sales_div_tot_paid").html((round_off(paid_amount)).toFixed(2));
    $(".sales_div_tot_balance").html((parseFloat(round_off(balance))).toFixed(2));

    /**/
    $(".sales_div_change_return ").html((change_return).toFixed(2));

  }

  function check_same_item(item_id) {

    if ($(".items_table tr").length > 1) {
      var rowcount = $("#hidden_rowcount1").val();
      for (i = 0; i <= rowcount; i++) {
        if ($("#tr_item_id1_" + i).val() == item_id) {
          increment_qty(item_id, i);
          failed.currentTime = 0;
          failed.play();
          return false;
        }
      } //end for
    }
    return true;
  }

  $(document).ready(function() {
    //FIRST TIME: LOAD
    //get_details();
    //alert($("section").height());//600+
    //alert($(".items_table").height());//29.76
    //alert($(".content-wrapper").height());//629
    get_details();

    var first_div = parseFloat($(".content-wrapper").height());
    var second_div = parseFloat($("section").height());
    var items_table = parseFloat($(".items_table").height());
    $(".items_table").parent().css("height", (first_div - second_div) + items_table + 250); /**/
    $(".search_div").parent().css("height", ((second_div - items_table) > 500) ? 500 : (second_div - items_table)); /**/


    //FIRST TIME: SET TOTAL ZERO
    set_total();

    //RIGHT DIV: FILTER INPUT BOX
    $("#search_it").on("keyup", function() {
      search_it();
    });

    //CATEGORY WISE ITEM FETCH FROM SERVER
    var show_only_searched = true;
    $("#category_id,#brand_id,#warehouse_id2").on("change", function() {
      get_details(null, show_only_searched);
    });

    //DISCOUNT UPDATE
    $(".discount_update").on("click", function() {
      final_total();
      $('#discount-modal').modal('toggle');
    });



    //RIGHT SIDE: CLEAR SEARCH BOX
    /* $(".show_all").on("click",function(){
       $("#search_it").val('').trigger("keyup");
       $("#category_id").val('').trigger("change");
     });*/

    //Reset Category & brand
    $(".reset_categories").on("click", function() {
      $("#category_id").val('').trigger("change");
    });
    $(".reset_brands").on("click", function() {
      $("#brand_id").val('').trigger("change");
    });


    //UPDATE PROCESS START
    <?php if (isset($sales_id) && !empty($sales_id)) { ?>

      $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
      $.get("<?php echo $base_url ?>pos/fetch_sales/<?php echo $sales_id ?>", {}, function(result) {
        // console.log(result);
        result = result.split("<<<###>>>");
        $('#pos-form-tbody').append(result[0]);
        $('#discount_input1').val(result[1]);
        $('#discount_type1').val(result[2]);
        $('#customer_id1').val(result[3]).select2();
        $('#temp_customer_id1').val(result[3]);
        $('#other_charges1').val(result[4]);
        $('#sales_date').val(result[5]);
        $("#hidden_rowcount1").val(parseFloat($(".items_table tr").length) - 1);

        $(".overlay").remove();
        $("#customer_id1").trigger("change");
        if (result[5] == 1) {
          $("#binvoice").prop("checked", true);
          $('#binvoice').parent('div').addClass('checked');
        }

        final_total();
        adjust_payments();

      });
      //DISABLE THE HOLD BUTTON
      $("#hold_invoice,#show_cash_modal").attr('disabled', true).removeAttr('id');

    <?php } ?>
    //UPDATE PROCESS END

    // hold_invoice_list();
  }); //ready() end


  function get_item_details(item_id) {

    $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
    $.post("<?php echo $base_url; ?>pos/get_item_details", {
      item_id: item_id
    }, function(result) {
      //console.log(result);
      var item = jQuery.parseJSON(result);

      var obj = {};
      obj['item_id'] = item['id'];
      obj['item_name'] = item['item_name'];
      obj['stock'] = item['stock'];
      obj['sales_price'] = item['sales_price'];
      obj['purchase_price'] = item['purchase_price'];
      obj['tax_id'] = item['tax_id'];
      obj['tax_type'] = item['tax_type'];
      obj['tax'] = item['tax'];
      obj['tax_name'] = item['tax_name'];
      obj['item_tax_amt'] = item['item_tax_amt'];
      obj['discount_type'] = item['discount_type'];
      obj['discount'] = item['discount'];
      addrow1(null, obj);
      $(".overlay").remove();
    });

  }
  $(".item_search").bind("paste", function(e) {
    $(".item_search").autocomplete('search');
  });
  $("#item_search_pos").bind("paste", function(e) {
    $("#item_search_pos").autocomplete('search');
  });

  $("#item_search_pos").autocomplete({

    source: function(data, cb) {
      $.ajax({
        autoFocus: true,
        url: $("#base_url").val() + 'items/get_json_items_details',
        method: 'GET',
        dataType: 'json',

        showHintOnFocus: true,
        autoSelect: true,
        selectInitial: true,

        data: {
          name: data.term,
          /*warehouse_id:$("#warehouse_id").val().trim(),*/
        },
        success: function(res) {
          //console.log(res);
          var result;
          result = [{
            //label: 'No Records Found '+data.term,
            label: 'No Records Found ',
            value: ''
          }];

          if (res.length) {

            result = $.map(res, function(el) {
              return {
                label: el.item_code + '--[Qty:' + el.stock + '] --' + el.label,
                value: '',
                id: el.id,
                item_name: el.value,
                stock: el.stock,
                // mobile: el.mobile,
                //customer_dob: el.customer_dob,
                //address: el.address,

              };

            });
          }
          cb(result);
        }
      });
    },

    response: function(e, ui) {
      if (ui.content.length == 1) {
        $(this).data('ui-autocomplete')._trigger('select', 'autocompleteselect', ui);
        $(this).autocomplete("close");
      }
      //console.log(ui.content[0].id);
    },
    //loader start
    search: function(e, ui) {

    },
    select: function(e, ui) {
      // console.log('inside select');
      //$("#mobile").val(ui.item.mobile)
      //$("#item_search_pos").val(ui.item.value);
      //$("#customer_dob").val(ui.item.customer_dob)
      //$("#address").val(ui.item.address)

      //console.log("stock="+$(this).val()); //Input box value

      if (typeof ui.content != 'undefined') {
        //console.log("Autoselected first");
        if (isNaN(ui.content[0].id)) {
          return;
        }
        var stock = ui.content[0].stock;
        var item_id = ui.content[0].id;

      } else {
        //console.log("manual Selected");
        var stock = ui.item.stock;
        var item_id = ui.item.id;
      }

      if (parseFloat(stock) == 0) {
        toastr["error"]("Out of Stock!");
        $("#item_search_pos").val('');
        return;
      }
      //addrow(item_id);
      get_item_details(item_id);
      $("#item_search_pos").val('');


    },
    //loader end
  });

  //DATEPICKER INITIALIZATION
  $('#order_date,#delivery_date,#cheque_date').datepicker({
    autoclose: true,
    format: 'dd-mm-yyyy',
    todayHighlight: true
  });
  $('#customer_dob,#birthday_person_dob').datepicker({
    calendarWeeks: true,
    todayHighlight: true,
    autoclose: true,
    format: 'dd-mm-yyyy',
    startView: 2
  });

  //Datemask dd-mm-yyyy
  //$("#customer_dob,#birthday_person_dob").inputmask("dd-mm-yyyy", {"placeholder": "dd-mm-yyyy"});

  //Timepicker
  /*$('.timepicker').timepicker({
    showInputs: false,
  });*/

  //Sale Items Modal Operations Start
  function show_sales_item_modal(row_id) {
    $('#sales_item').modal('toggle');
    //$("#popup_tax_id").select2();

    //Find the item details
    var item_name = $("#td_data1_" + row_id + "_0").html();
    var tax_type = $("#tr_tax_type_" + row_id).val();
    var tax_id = $("#tr_tax_id_" + row_id).val();
    var description = $("#description_" + row_id).val();

    /*Discount*/
    var item_discount_input = $("#item_discount_input1_" + row_id).val();
    var item_discount_type = $("#item_discount_type1_" + row_id).val();

    //Set to Popup
    $("#item_discount_input").val(item_discount_input);
    $("#item_discount_type").val(item_discount_type).select2();

    $("#popup_item_name").html(item_name);
    $("#popup_tax_type").val(tax_type).select2();
    $("#popup_tax_id").val(tax_id).select2();
    $("#popup_row_id").val(row_id);
    $("#popup_description").val(description);
  }

  function set_info() {
    var row_id = $("#popup_row_id").val();
    var tax_type = $("#popup_tax_type").val();
    var tax_id = $("#popup_tax_id").val();
    var description = $("#popup_description").val();
    var tax_name = ($('option:selected', "#popup_tax_id").attr('data-tax-value'));
    var tax = parseFloat($('option:selected', "#popup_tax_id").attr('data-tax'));

    /*Discounr*/
    var item_discount_input = $("#item_discount_input").val();
    var item_discount_type = $("#item_discount_type").val();

    //Set it into row 
    $("#item_discount_input1_" + row_id).val(item_discount_input);
    $("#item_discount_type1_" + row_id).val(item_discount_type);

    $("#tr_tax_type_" + row_id).val(tax_type);
    $("#tr_tax_id_" + row_id).val(tax_id);
    $("#description_" + row_id).val(description);
    $("#tr_tax_value_" + row_id).val(tax); //%
    //$("#td_data1_"+row_id+"_12").html(tax_type+" "+tax_name);

    var item_id = $("#tr_item_id1_" + row_id).val();
    make_subtotal(item_id, row_id);
    //calculate_tax(row_id);
    $('#sales_item').modal('toggle');
  }

  function set_tax_value(row_id) {
    //get the sales price of the item
    var tax_type = $("#tr_tax_type_" + row_id).val();
    var tax = $("#tr_tax_value_" + row_id).val(); //%
    var item_id = $("#tr_item_id1_" + row_id).val();
    var qty = ($("#item_qty1_" + item_id).val());
    qty = (isNaN(qty)) ? 0 : qty;

    var sales_price = parseFloat($("#sales_price1_" + row_id).val());
    sales_price = (isNaN(sales_price)) ? 0 : sales_price;
    sales_price = sales_price * qty;

    /*Discount*/
    var item_discount_type = $("#item_discount_type1_" + row_id).val();
    var item_discount_input = parseFloat($("#item_discount_input1_" + row_id).val());
    item_discount_input = (isNaN(item_discount_input)) ? 0 : item_discount_input;

    //Calculate discount      
    var discount_amt = (item_discount_type == 'Percentage') ? ((sales_price) * item_discount_input) / 100 : (item_discount_input * qty);

    sales_price -= parseFloat(discount_amt);

    var tax_amount = (tax_type == 'Inclusive') ? calculate_inclusive(sales_price, tax) : calculate_exclusive(sales_price, tax);

    $("#item_discount1_" + row_id).val(discount_amt);
    $("#td_data1_" + row_id + "_11").val(tax_amount);
  }
  //Sale Items Modal Operations End
</script>

<script>
  function reset_tooltip() {
    $('[data-toggle="tooltip"]').tooltip("destroy");
    $('[data-toggle="tooltip"]').tooltip(); // re-enabling 
  }
  $('.search_div').on('scroll', function() {
    if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
      load_next_details();
    }
  });

  function load_next_details() {
    var last_id = $(".item_box:last").attr("data-item-id");
    get_details(last_id);
  }



  function get_details(last_id = '', show_only_searched = false) {
    $.ajax({
      url: '<?php echo $base_url; ?>pos/get_details1',
      type: "post",
      data: {
        last_id: (!show_only_searched) ? last_id : '',
        id: $("#category_id").val(),
        warehouse_id: $("#warehouse_id2").val(),
        //search_it  : $("#search_it").val(),
        brand_id: $("#brand_id").val(),
      },
      beforeSend: function() {
        $('.ajax-load').show();
      }
    }).done(function(data) {
      $('.ajax-load').hide();

      if (data == '') {
        $(".error_div").show();
      } else {
        $(".error_div").hide();
      }


      if (show_only_searched) {
        $(".search_div").html('');
      }
      $(".search_div").append(data);
      reset_tooltip();
    }).fail(function(jqXHR, ajaxOptions, thrownError) {
      alert('server not responding...');
    });
  }
  /* taxs modal end */
  $('#customer-modal1').on('shown.bs.modal', function() {
    $('.select2').select2();
  });

  $('#hold_invoice1').on("click", function(e) {

    //table should not be empty
    if ($(".items_table tr").length == 1) {
      toastr["error"]("Please Select Items from List!!");
      failed.currentTime = 0;
      failed.play();
      return;
    }

    swal({
        title: "Hold Invoice ? Same Reference will replace the old list if exist!!",
        icon: "warning",
        buttons: true,
        dangerMode: true,
        content: {
          element: "input",
          attributes: {
            placeholder: "Please Enter Reference Number!",
            type: "text",

            inputAttributes: {
              maxlength: '5'
            }
          },
        },
      }).then(name => {
        //If input box blank Throw Error
        if (!name.trim()) {
          throw null;
          return false;
        }
        var reference_id = name;
        /* ********************************************************** */
        var base_url = $("#base_url").val().trim();

        //RETRIVE ALL DYNAMIC HTML VALUES
        var tot_qty = $(".tot_qty1").text();
        var tot_amt = $(".tot_amt1").text();
        var tot_disc = $(".tot_disc1").text();
        var tot_grand = $(".tot_grand1").text();
        var hidden_rowcount = $("#hidden_rowcount1").val();

        var this_id = this.id; //id=save or id=update

        e.preventDefault();
        data = new FormData($('#pos-form1')[0]); //form name
        /*Check XSS Code*/
        if (!xss_validation(data)) {
          return false;
        }

        $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
        $("#" + this_id).attr('disabled', true); //Enable Save or Update button				
        $.ajax({
          type: 'POST',
          url: base_url + 'pos/hold_invoice?command=' + this_id + '&tot_qty=' + tot_qty + '&tot_amt=' + tot_amt + '&tot_disc=' + tot_disc + '&tot_grand=' + tot_grand + "&reference_id=" + reference_id,
          data: data,
          cache: false,
          contentType: false,
          processData: false,
          success: function(result) {
            //alert(result);return;
            $("#hidden_invoice_id1").val('');
            result = result.trim().split("<<<###>>>");

            if (result[0] == "success") {
              $('#pos-form-tbody').html('');
              //CALCULATE FINAL TOTAL AND OTHER OPERATIONS

              hold_invoice_list();
              success.currentTime = 0;
              success.play();
              $("#other_charges1").val('');
              final_total();
            } else if (result[0] == "failed") {
              toastr['error']("Sorry! Failed to save Record.Try again");
            } else {
              alert(result);
            }

            $("#" + this_id).attr('disabled', false); //Enable Save or Update button
            $(".overlay").remove();
          }
        });
        /* ********************************************************** */

      }) //name end
      .catch(err => {
        toastr['error']("Failed!! Invoice Not Saved! <br/>Please Enter Reference Number");
        failed.currentTime = 0;
        failed.play();
      }); //swal end

  }); //hold_invoice end

  function hold_invoice_list() {
    var base_url = $("#base_url").val().trim();
    $.post(base_url + "pos/hold_invoice_list", {}, function(result) {
      //alert(result);
      var data = jQuery.parseJSON(result)
      $("#hold_invoice_list").html('').html(data['result']);
      $(".hold_invoice_list_count").html('').html(data['tot_count']);
    });
  }

  function hold_invoice_delete(invoice_id) {
    swal({
      title: "Are you sure?",
      icon: "warning",
      buttons: true,
      dangerMode: true,
    }).then((sure) => {
      if (sure) { //confirmation start
        var base_url = $("#base_url").val().trim();
        $.post(base_url + "pos/hold_invoice_delete/" + invoice_id, {}, function(result) {
          result = result.trim();
          if (result == 'success') {
            toastr["success"]("Success! Invoice Deleted!!");
            success.currentTime = 0;
            success.play();
            hold_invoice_list();
          } else {
            toastr['error']("Failed to Delete Invoice! Try again!!");
            failed.currentTime = 0;
            failed.play();
          }
        });
      } //confirmation sure
    }); //confirmation end
  }

  function hold_invoice_edit(id) {

    swal({
      title: "Are you sure?",
      icon: "warning",
      buttons: true,
      dangerMode: true,
    }).then((sure) => {
      if (sure) { //confirmation start
        var base_url = $("#base_url").val().trim();

        $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
        $.post(base_url + "pos/hold_invoice_edit", {
          hold_id: id
        }, function(result) {

          //console.log(result);

          result = result.split("<<<###>>>");
          $('#pos-form-tbody').html('').append(result[0]);
          $('#discount_input1').val(result[1]);
          $('#discount_type1').val(result[2]);
          $('#customer_id').val(result[3]).select2();
          $("#other_charges1").val(result[4]);
          $("#hidden_invoice_id1").val(result[5]);
          $("#hidden_rowcount1").val(parseInt($(".items_table tr").length) - 1);
          final_total();
          get_details(null, true);
          $(".overlay").remove();

        });


      } //confirmation sure
    }); //confirmation end
  }

  function save(print = false, pay_all = false) {
    //$('.make_sale').on("click",function (e) {

    var base_url = $("#base_url").val().trim();

    if ($(".items_table tr").length == 1) {
      toastr["warning"]("Empty Sales List!!");
      return;
    }


    //RETRIVE ALL DYNAMIC HTML VALUES
    var tot_qty = $(".tot_qty1").text();
    var tot_amt = $(".tot_amt1").text();
    var tot_disc = $(".tot_disc1").text();
    var tot_grand = $(".tot_grand1").text();
    var paid_amt = (pay_all) ? tot_grand : $(".sales_div_tot_paid").text();
    var balance = (pay_all) ? 0 : parseFloat($(".sales_div_tot_balance").text());

    /* console.log("tot_grand="+tot_grand);
     console.log("balance="+balance);
     console.log("paid_amt="+paid_amt);
     return;*/
    if ($("#customer_id1").val().trim() == 1 && balance != 0) {
      toastr["warning"]("Walk-in Customer Should Pay Complete Amount!!");
      return;
    }
    if (document.getElementById("sales_id")) {
      var command = 'update';
    } else {
      var command = 'save';
    }
    var this_btn = 'make_sale';

    //swal({ title: "Are you sure?",icon: "warning",buttons: true,dangerMode: true,}).then((sure) => {
    //  if(sure) {//confirmation start


    $("#" + this_btn).attr('disabled', true); //Enable Save or Update button
    //e.preventDefault();
    var data = new Array(2);
    data = new FormData($('#pos-form1')[0]); //form name
    /*Check XSS Code*/
    if (!xss_validation(data)) {
      return false;
    }

    $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
    $.ajax({
      type: 'POST',
      url: base_url + 'pos/pos_save_update?command=' + command + '&tot_qty=' + tot_qty + '&tot_amt=' + tot_amt + '&tot_disc=' + tot_disc + '&tot_grand=' + tot_grand + "&paid_amt=" + paid_amt + '&balance=' + balance + "&pay_all=" + pay_all,
      data: data,
      cache: false,
      contentType: false,
      processData: false,
      success: function(result) {
        //console.log(result);return;
        result = result.trim().split("<<<###>>>");
        console.log("result[0]" + result[0]);
        //return;

        console.log("result[0]=" + result[0]);
        console.log("result[1]=" + result[1]);
        console.log("result[2]=" + result[2]);
        if (result[0]) {

          if (result[0] == "success") {
            var print_done = true;
            if (print) {
              var print_done = window.open(base_url + "pos/print_invoice_pos/" + result[1], "_blank", "scrollbars=1,resizable=1,height=300,width=450");
            }
            if (print_done) {

              if (command == 'update') {
                console.log("inside update");
                window.location = base_url + "sales";
              } else {
                console.log("inside else");
                success.currentTime = 0;
                success.play();
                toastr['success']("Invoice Saved Successfully!");

                //window.location=base_url+"pos";		
                $(".items_table > tbody").empty();
                $(".discount_input").val(0);

                $('#multiple-payments-modal').modal('hide');
                var rc = $("#payment_row_count").val();
                while (rc > 1) {
                  remove_row(rc);
                  rc--;
                }
                console.log('inside form');
                $("#pos-form1")[0].reset();

                $("#customer_id1").val(1).select2();

                final_total();

                get_details(null, true);

                //get_details();
                //hold_invoice_list();
                //window.location=base_url+"pos";

              }

            }

          } else if (result[0] == "failed") {
            toastr['error']("Sorry! Failed to save Record.Try again");
          } else {
            alert(result);
          }
        } // data.result end

        if (result[2]) {
          $("#hold_invoice_list").html('').html(result[2]);
          $(".hold_invoice_list_count").html('').html(result[3]);
        }



        $("." + this_btn).attr('disabled', false); //Enable Save or Update button
        $(".overlay").remove();
      }
    });
    //} //confirmation sure
    //	}); //confirmation end

    //e.preventDefault


    //});
  } //Save End
  function hidePaymentModal() {
    $('#multiple-payments-modal').modal('hide');
  }
  $("#save-item1").on("click", function(e) {
    var base_url = $("#base_url").val().trim();
    //Initially flag set true
    var flag = true;

    function check_field(id) {
      if (
        !$("#" + id)
        .val()
        .trim()
      ) {
        //Also check Others????
        $("#" + id + "_msg")
          .fadeIn(200)
          .show()
          .html("Required Field")
          .addClass("required");
        //$('#'+id).css({'background-color' : '#E8E2E9'});
        flag = false;
      } else {
        $("#" + id + "_msg")
          .fadeOut(200)
          .hide();
        //$('#'+id).css({'background-color' : '#FFFFFF'});    //White color
      }
    }

    //Validate Input box or selection box should not be blank or empty
    check_field("item_name1");
    check_field("category_id1");
    check_field("unit_id1"); //units of measurments
    check_field("price1");
    //check_field("alert_qty");
    check_field("tax_id1");
    check_field("purchase_price1");
    check_field("tax_type1");
    //check_field("profit_margin");
    check_field("sales_price1");

    if (flag == false) {
      toastr["warning"]("You have Missed Something to Fillup!");
      return;
    }

    var this_id = this.id;

    if (this_id == "save-item1") {
      //Save start
      // if (confirm("Do You Wants to Save Record ?")) {
      e.preventDefault();
      data = new FormData($("#items-form1")[0]); //form name
      /*Check XSS Code*/
      if (!xss_validation(data)) {
        return false;
      }

      $(".box").append(
        '<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>'
      );
      $("#" + this_id).attr("disabled", true); //Enable Save or Update button
      $.ajax({
        type: "POST",
        url: base_url + "items/newitems",
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        success: function(result) {
          //alert(result);return;
          if (result == "success") {
            //alert("Record Saved Successfully!");
            window.location = base_url + "items"; //"items-view.php";
            return;
          } else if (result == "failed") {
            toastr["error"]("Sorry! Failed to save Record.Try again!");
            //	return;
          } else {
            toastr["error"](result);
          }
          $("#" + this_id).attr("disabled", false); //Enable Save or Update button
          $(".overlay").remove();
        },
      });
      // }
      return;
      //e.preventDefault
    }
  });

  //CALCULATED PURCHASE PRICE
  function calculate_purchase_price1() {
    var price = isNaN(parseFloat($("#price1").val().trim())) ?
      0 :
      parseFloat($("#price1").val().trim());
    var tax = isNaN(parseFloat($("option:selected", "#tax_id1").attr("data-tax"))) ?
      0 :
      parseFloat($("option:selected", "#tax_id1").attr("data-tax"));
    tax = parseFloat(tax);

    var tax_type = $("#tax_type1").val();
    var purchase_price = parseFloat(0);
    price = parseFloat(price);

    console.log("tax=" + tax);
    if (tax_type == "Inclusive") {
      purchase_price = price;
    } else {
      purchase_price = price + (price * tax) / parseFloat(100);
    }
    //$("#purchase_price").val( (price + (price*tax)/parseFloat(100)).toFixed(decimals));

    $("#purchase_price1").val(purchase_price.toFixed(2));
    //calculate_sales_price();

    //$("#purchase_price").val( (price + (price*tax)/parseFloat(100)).toFixed(2));
    //calculate_sales_price();
  }
  $("#price1").keyup(function(event) {
    calculate_purchase_price1();
  });
  $("#tax_id1").on("change", function(event) {
    calculate_purchase_price1();
  });

  //CALCUALATED SALES PRICE
  function calculate_sales_price1() {
    var purchase_price = isNaN(parseFloat($("#purchase_price1").val().trim())) ?
      0 :
      parseFloat($("#purchase_price1").val().trim());
    var profit_margin = isNaN(parseFloat($("#profit_margin1").val().trim())) ?
      0 :
      parseFloat($("#profit_margin1").val().trim());
    var tax_type = $("#tax_type1").val();

    var sales_price = parseFloat(0);
    if (purchase_price > 0) {
      if (tax_type == "Inclusive") {
        sales_price =
          purchase_price + (purchase_price * profit_margin) / parseFloat(100);
      } else {
        //var price = (isNaN(parseFloat($("#price").val().trim()))) ? 0 :parseFloat($("#price").val().trim());
        sales_price =
          purchase_price + (purchase_price * profit_margin) / parseFloat(100);
      }
    } else {
      sales_price = profit_margin;
    }

    $("#sales_price1").val(sales_price.toFixed(2));
    //calculate_profit_margin();
    calculate_final_price1();
  }
  $("#tax_type1").on("change", function(event) {
    calculate_purchase_price1();
    calculate_final_price1();
  });
  $("#profit_margin1").keyup(function(event) {
    calculate_sales_price1();
  });
  //END
  function calculate_final_price1() {
    var tax_type = $("#tax_type1").val();
    var sales_price = $("#sales_price1").val();
    sales_price = parseFloat(sales_price);
    var tax = isNaN(parseFloat($("option:selected", "#tax_id1").attr("data-tax"))) ?
      0 :
      parseFloat($("option:selected", "#tax_id1").attr("data-tax"));
    tax = parseFloat(tax);
    //console.log("tax_type="+tax_type);
    var tot = tax_type == "Inclusive" ? 0 : calculate_exclusive(sales_price, tax);
    $("#final_price1").val(parseFloat(sales_price) + parseFloat(tot));
  }
  //CALCULATE PROFIT MARGIN PERCENTAGE
  function calculate_profit_margin1() {
    var purchase_price = isNaN(parseFloat($("#purchase_price1").val().trim())) ?
      0 :
      parseFloat($("#purchase_price1").val().trim());
    var sales_price = isNaN(parseFloat($("#sales_price1").val().trim())) ?
      0 :
      parseFloat($("#sales_price1").val().trim());
    var profit_margin = sales_price - purchase_price;
    var profit_margin =
      purchase_price > 0 ?
      (profit_margin / purchase_price) * parseFloat(100) :
      profit_margin;
    $("#profit_margin1").val(profit_margin.toFixed(0));
  }
  $("#sales_price1").keyup(function(event) {
    calculate_profit_margin1();
    calculate_final_price1();
  });






  $('.select_currency').change(function() {
    var currencyCode = $(this).val(); // Get the selected currency code
    var currencyID = $(this).find(':selected').data('id');
    $.ajax({
      url: $("#base_url").val() + 'items/update_currency_session',
      type: 'POST',
      data: {
        currency_code: currencyCode,
        currency_id: currencyID
      },
      success: function(response) {
        window.location.reload();
      },
      error: function(xhr, status, error) {
        console.error(xhr.responseText); // Handle error response
      }
    });
  });
</script>
<script>
  $(".openRestoreModal").click(function() {
    $("#restoreModal").modal('show');
  });
</script>