<!DOCTYPE html>
<html>

<head>
<!-- TABLES CSS CODE -->
<?php include"comman/code_css_datatable.php"; ?>
</head>

<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">

  <!-- Left side column. contains the logo and sidebar -->
  
  <?php include"sidebar.php"; ?>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <h1>
        <?=$page_title;?>
        <small>View/Search Item Stock</small>
      </h1>
      <ol class="breadcrumb">
        <li><a href="<?php echo $base_url; ?>dashboard"><i class="fa fa-dashboard"></i> Home</a></li>
        <li class="active"><?=$page_title;?></li>
      </ol>
    </section>

    <!-- Main content -->
    <?= form_open('#', array('class' => '', 'id' => 'table_form')); ?>
    <input type="hidden" id='base_url' value="<?=$base_url;?>">
    <section class="content">
      <div class="row">
        <!-- ********** ALERT MESSAGE START******* -->
        <?php include"comman/code_flashdata.php"; ?>
        <!-- ********** ALERT MESSAGE END******* -->
        <div class="col-xs-12">
          <div class="box">
            <div class="box-header with-border">
              <h3 class="box-title"><?=$page_title;?></h3>

              <br>
                <div class="row">
                <div class="col-md-4">
                  <div class="form-group">
                  <div class="d-flex align-items-center" style="display: flex; align-items: center;">
                    <label for="section_id" style="margin-right: 10px; margin-bottom:0; white-space:nowrap;">Section</label>
                    <select class="form-control select2" id="section_id" name="section_id" style="width: 100%;" onkeyup="shift_cursor(event,'mobile')">
                    <?php
                      $query1="select * from db_section where status=1";
                      $q1=$this->db->query($query1);
                      if($q1->num_rows($q1)>0)
                        { 
                        foreach($q1->result() as $res1)
                        {
                        echo "<option value='".$res1->section_id."'>".$res1->section_name ."</option>";
                        }
                      }
                      else
                      {
                        ?>
                    <option value="">No Records Found</option>
                    <?php
                      }
                      ?>
                    </select>
                  </div>
                  </div>
                </div>
                <div class="col-md-4">
                  <div class="form-group">
                  <div style="float: right; padding-left:0; padding-right:0;">
                  <input type="checkbox" id="zero_qty" name="zero_qty" value="Yes" checked> <label for="zero_qty">Drop Zero Quantity </label> &nbsp;&nbsp;&nbsp;&nbsp;
                  <button type="button" class="btn btn-success" onclick="fill_tbData();">Load</button>
                  </div>
                </div>
                </div>
                <div class="col-md-4">
                  <div class="form-group">
                  <button type="button" class="btn btn-info float-right" data-toggle="modal" data-target="#transferModal" id="transfer_stock_btn" >Stock Transfer</button>
                  </div>
                </div>
                </div>

                <!-- Stock Transfer Modal (Bootstrap 4) -->
                <div class="modal fade" id="transferModal" tabindex="-1" role="dialog" aria-labelledby="transferModalLabel" aria-hidden="true">
                <div class="modal-dialog" role="document">
                  <div class="modal-content">
                  <form id="stock_transfer_form" class="form-horizontal" autocomplete="off">
                  <div class="modal-header">
                  <h5 class="modal-title" id="transferModalLabel">Stock Transfer</h5>
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                  </button>
                  </div>
                  <div class="modal-body">
                  <div class="form-group row">
                    <label for="transfer_item" class="col-sm-2 col-form-label">Item</label>
                    <div class="col-sm-4">
                    <select class="form-control select2" id="transfer_item" name="transfer_item" style="width: 100%;" required>
                    <option value="">Select Item</option>
                    <?php
                    $items_q = $this->db->query("SELECT id, item_name, sku FROM db_items WHERE status=1");
                    foreach($items_q->result() as $item){
                    echo "<option value='{$item->id}'>{$item->item_name} ({$item->sku})</option>";
                    }
                    ?>
                    </select>
                    </div>
                    <div class="col-sm-6 text-bold">
                      <span>Showroom :</span> &nbsp; <label id="show_qty"></label> &nbsp;&nbsp;&nbsp;&nbsp; <span>Warehouse :</span> &nbsp; <label id="ware_qty"></label> 
                      <input type="hidden" name="show_qty" id="show_qty_hidden">
                      <input type="hidden" name="ware_qty" id="ware_qty_hidden">
                    </div>
                  </div>
                  <div class="form-group row">
                    <label for="from_section" class="col-sm-2 col-form-label">From </label>
                    <div class="col-sm-4">
                    <select class="form-control select2" id="from_section" name="from_section" style="width: 100%;" required>
                    <option value="">Select Section</option>
                    <?php
                    $sections_q = $this->db->query("SELECT section_id, section_name FROM db_section WHERE status=1");
                    foreach($sections_q->result() as $section){
                    echo "<option value='{$section->section_id}'>{$section->section_name}</option>";
                    }
                    ?>
                    </select>
                    </div>
                    <label for="to_section" class="col-sm-1 col-form-label">To</label>
                    <div class="col-sm-4">
                    <select class="form-control select2" id="to_section" name="to_section" style="width: 100%;" required>
                    <option value="">Select Section</option>
                    <?php
                    $sections_q = $this->db->query("SELECT section_id, section_name FROM db_section WHERE status=1");
                    foreach($sections_q->result() as $section){
                    echo "<option value='{$section->section_id}'>{$section->section_name}</option>";
                    }
                    ?>
                    </select>
                    </div>
                  </div>
                  <div class="form-group row">
                    <label for="transfer_qty" class="col-sm-2 col-form-label">Quantity</label>
                    <div class="col-sm-4">
                    <input type="number" class="form-control" id="transfer_qty" name="transfer_qty" min="1" placeholder="Enter Quantity" required>
                    </div>
                  </div>
                  </div>
                  <div class="modal-footer">
                  <button type="button" class="btn btn-primary" id="btn_saveTransfer">Transfer</button>
                  <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                  </div>
                  </form>
                  </div>
                </div>
                </div>

                
            <!-- /.box-header -->
            <div class="box-body">
              <table id="example2" class="table table-bordered table-striped" width="100%">
                <thead class="bg-primary ">
                <tr>
                  <th class="text-center">#</th>
                  <th>Item Name</th>
                  <th>SKU</th>
                  <th>Stock QTY</th>
                  <?php if(($this->session->userdata('role_id')=='1')||($this->session->userdata('role_id')=='2')){ ?>
                  <th>Cost Price</th>
                  <?php } ?>
                  <th>wholesale Price</th>
                  <th>Retail Price</th>
                  <?php if(($this->session->userdata('role_id')=='1')||($this->session->userdata('role_id')=='2')){ ?>
                    <th><?= $this->lang->line('action'); ?></th>
                  <?php } ?>
                </tr>
                </thead>
                <tbody>
				
                </tbody>
               
              </table>
            </div>
            <!-- /.box-body -->

              <div class="modal fade" id="editModal" tabindex="-1" role="dialog">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4 class="title" id="editModalLabel">Update Stock</h4>
                        </div>
                        <form class="form-horizontal" id="edit_stock-form" onkeypress="return event.keyCode != 13;">
                            <!-- <input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash();?>">
                            <input type="hidden" id="base_url" value="<?php echo $base_url;; ?>"> -->
                            <div class="modal-body">
                              <div class="row">
                                <div class="col-sm-12">
                                  Item Name : <label id="lbl_Item_name"></label><br>
                                  Category : <label id="lbl_Category"></label><br>
                                  Color : <label id="lbl_Color"></label><br>
                                  Size : <label id="lbl_Size"></label><br>
                                  SKU : <label id="lbl_SKU"></label><br>               
                                  <br>
                                </div>
                              </div>
                              <div class="row">
                                <div class="col-sm-6">
                                    <div class="form-group">
                                        <label>Stock Qty</label>                                  
                                        <input type="number" class="form-control" name="e_stockQty" id="e_stockQty" placeholder="Stock Qty" required />
                                    </div>
                                </div>
                                <div class="col-sm-6">
                                    <div class="form-group">
                                        <label>Cost Price</label>                                  
                                        <input type="number" class="form-control" name="e_costPrice" id="e_costPrice" placeholder="Cost Price" required />
                                    </div>
                                </div>
                              </div>
                              <div class="row">
                                <div class="col-sm-4">
                                    <div class="form-group">
                                        <label>Wholesale Price</label>                                  
                                        <input type="number" class="form-control" name="e_salePrice_2" id="e_salePrice_2" placeholder="Sale Price 02" required />
                                    </div>
                                </div>
                                <div class="col-sm-4">
                                    <div class="form-group">
                                        <label>Retail Price</label>                                  
                                        <input type="number" class="form-control" name="e_salePrice_1" id="e_salePrice_1" placeholder="Sale Price 01" required />
                                    </div>
                                </div>
                                <div class="col-sm-4" hidden>
                                    <div class="form-group">
                                        <label>Sale Price 03</label>                                  
                                        <input type="number" class="form-control" name="e_salePrice_3" id="e_salePrice_3" placeholder="Sale Price 03" required />
                                        <input type="hidden" class="form-control" name="e_st_id" id="e_st_id" placeholder="Stock ID" required />
                                        <input type="hidden" class="form-control" name="row_id" id="row_id" placeholder="Stock ID" required />
                                    </div>
                                </div>
                              </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" name="stock_edit" id="stock_edit" class="btn btn-primary">Update</button>
                                <button type="button" class="btn btn-danger" id="m_close" data-dismiss="modal">Close</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
          </div>
          <!-- /.box -->
        </div>
        <!-- /.col -->
      </div>
      <!-- /.row -->
    </section>
    <!-- /.content -->
    <?= form_close();?>
  </div>
  <!-- /.content-wrapper -->
  <?php include"footer.php"; ?>
  <!-- Add the sidebar's background. This div must be placed
       immediately after the control sidebar -->
  <div class="control-sidebar-bg"></div>
</div>
<!-- ./wrapper -->

<!-- SOUND CODE -->
<?php include"comman/code_js_sound.php"; ?>
<!-- TABLES CODE -->
<?php include"comman/code_js_datatable.php"; ?>


<script>
  // Re-initialize select2 when modal is shown
  $('#transferModal').on('shown.bs.modal', function () {
    $(this).find('.select2').select2({
      dropdownParent: $('#transferModal')
    });
  });
</script>

<script>
  $('#transfer_item').on('change', function () {
    var item_id = $(this).val();
    if (item_id) {
      $.ajax({
        url: "<?php echo site_url('stock/get_section_qty'); ?>",
        type: 'POST',
        data: { item_id: item_id },
        dataType: 'json',
        success: function (data) {
          $('#show_qty').text(data.total_qty);
          $('#show_qty_hidden').val(data.total_qty);
          $('#ware_qty_hidden').val(data.ware_total);
          $('#ware_qty').text(data.ware_total);
        },
        error: function (xhr, ajaxOptions, thrownError) {
          console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }
      });
    } else {
      $('#show_qty').text('');
    }
  });
</script>

<script>
  // Validation for transfer_qty based on from_section and to_section
  function validateTransferQty() {
    var from_section = $('#from_section').val();
    var to_section = $('#to_section').val();
    var transfer_qty = parseFloat($('#transfer_qty').val());
    var show_qty = parseFloat($('#show_qty_hidden').val());
    var ware_qty = parseFloat($('#ware_qty_hidden').val());

    // Only validate if both sections are selected and transfer_qty is a number
    if (!from_section || !to_section || isNaN(transfer_qty)) {
      return;
    }

    if (from_section === '1' && to_section === '2') {
      if (transfer_qty > show_qty) {
        swal("Warning", "Transfer quantity cannot exceed Showroom quantity (" + show_qty + ")", "warning");
        $('#transfer_qty').val('');
      }
    } else if (from_section === '2' && to_section === '1') {
      if (transfer_qty > ware_qty) {
        swal("Warning", "Transfer quantity cannot exceed Warehouse quantity (" + ware_qty + ")", "warning");
        $('#transfer_qty').val('');
      }
    }
  }

  $('#transfer_qty').on('change keyup', function () {
    validateTransferQty();
  });
</script>

<script>
  $('#btn_saveTransfer').on('click', function (e) {
    e.preventDefault();
    var transfer_item = $('#transfer_item').val();
    var from_section = $('#from_section').val();
    var to_section = $('#to_section').val();
    var transfer_qty = $('#transfer_qty').val();

    if (transfer_item && from_section && to_section && transfer_qty) {
      $.ajax({
        url: "<?php echo site_url('stock/stock_transfer'); ?>",
        type: 'POST',
        data: {
          transfer_item: transfer_item,
          from_section: from_section,
          to_section: to_section,
          transfer_qty: transfer_qty,
          added_by: '<?php echo $this->session->userdata('user_id'); ?>',
          added_date: '<?php echo date('Y-m-d H:i:s'); ?>'
        },
        dataType: 'json',
        success: function (data) {
          if (data.status === 'success') {
            swal("Success", "Stock transferred successfully!", "success");
            $('#transfer_item').val('').trigger('change');
            $('#from_section').val('');
            $('#to_section').val('');
            $('#transfer_qty').val('');
            $('#show_qty').text('');
            $('#ware_qty').text('');
            $('#transferModal').modal('hide');
            fill_tbData(); // Refresh the stock table
          } else {
            swal("Error", "Failed to transfer stock. Please try again.", "error");
          }
        },
        error: function (xhr, ajaxOptions, thrownError) {
          console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }
      });
    } else {
      swal("Warning", "Please fill all fields correctly.", "warning");
    }
  });
</script>


                
<script>
  function fill_tbData(){
    var filter_none_stock ="";
      var checked = $("#zero_qty").parent('[class*="icheckbox"]').hasClass("checked");
      if(checked) {
        filter_none_stock='yes';
      }else{
        filter_none_stock='no';
      }

      var section_id = $('#section_id').val();

      $.ajax({
        url:"<?php echo site_url('stock/st_details_get')?>",
        type: 'POST',
        data: {filter_none_stock:filter_none_stock, section_id:section_id},
        dataType: 'json',
        success: function (data) {

          var table;
          table = $('#example2').DataTable();
          table.clear(); 
          var indexNo = 1; 
          $.each(data.st_info, function(){
            <?php if(($this->session->userdata('role_id')=='1')||($this->session->userdata('role_id')=='2')){ ?>
             table.row.add([indexNo,this['item_name'],this['sku'], this['stock_qty'], this['cost_price'], this['unit_sales_price_02'], this['unit_sales_price_01'], '<button type="button" class="btn btn-warning btn-icon" onclick="editStock(this)" data-ID="'+this['id']+'" data-RowID="'+(indexNo-1)+'"><i class="fa fa-edit"></i></button>']);
            <?php } ?>
            <?php if(($this->session->userdata('role_id')=='3')){ ?>
             table.row.add([indexNo,this['item_name'],this['sku'], this['stock_qty'], this['unit_sales_price_02'], this['unit_sales_price_01']]);
            <?php } ?>
             indexNo++;
          });
          table.draw();
          
        },
        error: function (xhr, ajaxOptions, thrownError) {
          console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }
      });
  }
</script> 
<script>
    $(document).ready(function(){
      fill_tbData();
    });
</script>
<script>
    $("#e_stockQty").blur(function() {
        this.value = parseFloat(this.value).toFixed(2);
    });
    $("#e_costPrice").blur(function() {
        this.value = parseFloat(this.value).toFixed(2);
    });
    $("#e_salePrice_1").blur(function() {
        this.value = parseFloat(this.value).toFixed(2);
    });
    $("#e_salePrice_2").blur(function() {
        this.value = parseFloat(this.value).toFixed(2);
    });
    $("#e_salePrice_3").blur(function() {
        this.value = parseFloat(this.value).toFixed(2);
    });
</script>

<script>
    function editStock(ctl) {
        var st_ID = $(ctl).attr("data-ID");
        var row_ID = $(ctl).attr("data-RowID");
        $.ajax({
            url:"<?php echo site_url('stock/stock_info_get')?>",
            type: 'post',
            data: {st_ID:st_ID},
            dataType: 'json',
            success: function (data) {
              $('#lbl_Item_name').empty();
              $('#lbl_Category').empty();
              $('#lbl_Color').empty();
              $('#lbl_Size').empty();
              $('#lbl_SKU').empty();              

              $.each(data.st_id_info, function(){
                $('#lbl_Item_name').append(this['item_name']);
                $('#lbl_Category').append(this['category_name']);
                $('#lbl_Color').append(this['color']);
                $('#lbl_Size').append(this['size']);
                $('#lbl_SKU').append(this['sku']);

                $('#e_stockQty').val(this['stock_qty']);
                $('#e_costPrice').val(this['cost_price']);
                $('#e_salePrice_1').val(this['unit_sales_price_01']);
                $('#e_salePrice_2').val(this['unit_sales_price_02']);
                $('#e_salePrice_3').val(this['unit_sales_price_03']);
                $('#e_st_id').val(this['id']);
                $('#row_id').val(row_ID);
              });
              $('#editModal').modal('show');
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });   
    }
</script>
<script>
    $("#stock_edit").click(function(event){  
      event.preventDefault();          
            var e_st_id       = $('#e_st_id').val();
            var e_stockQty     = $('#e_stockQty').val();
            var e_costPrice       = $('#e_costPrice').val();
            var e_salePrice_1          = $('#e_salePrice_1').val();
            var e_salePrice_2   = $('#e_salePrice_2').val();
            var e_salePrice_3 = $('#e_salePrice_3').val();
            var row_id = parseInt($('#row_id').val());

            if (e_st_id.length==""){
                swal("Something Wrong","Please fill in the all fields!!","warning");
            }else{

                $("#stock_edit").attr("disabled", "disabled");

                // var formData = new FormData();

                // formData.append("e_st_id", e_st_id);
                // formData.append("e_stockQty", e_stockQty);
                // formData.append("e_costPrice", e_costPrice);
                // formData.append("e_salePrice_1", e_salePrice_1);
                // formData.append("e_salePrice_2", e_salePrice_2);
                // formData.append("e_salePrice_3", e_salePrice_3);

                $.ajax({                    
                    url:"<?php echo site_url('stock/stock_edit')?>",
                    type: 'post',
                    data: {e_st_id:e_st_id,e_stockQty:e_stockQty,e_costPrice:e_costPrice,e_salePrice_1:e_salePrice_1,e_salePrice_2:e_salePrice_2,e_salePrice_3:e_salePrice_3,},
                    dataType: 'json',
                    success: function (data){
                      //console.log(data);
                        if(data=='success'){
                            swal({
                                title: "Successfully",
                                type: "success",
                                icon: "success",
                                text: "Stock Updated !!" ,
                              })
                              .then((willUpdate) => {
                                if (willUpdate) {
                                  //fill_tbData();
                                  var table;
                                  table = $('#example2').DataTable();
                                  var temp = table.row(row_id).data();
                                  temp[3] = e_stockQty;
                                  temp[4] = e_costPrice;
                                  temp[5] = e_salePrice_2;
                                  temp[6] = e_salePrice_1;
                                  table.row(row_id).data(temp);

                                  $("#m_close").click();
                                }
                            });
                            $("#stock_edit").attr("disabled", false);
                            document.getElementById("edit_stock-form").reset();
                            
                        }else if(data=='failed'){
                            swal('Sorry','Error occured !!','error');
                            $("#stock_edit").attr("disabled", false);
                        } 
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
                        $("#stock_edit").attr("disabled", false);
                    }
                });
            }
            return false;
            $("#stock_edit").attr("disabled", false);
    });
</script>


<!-- <script type="text/javascript">
$(document).ready(function() {
    //datatables
   var table = $('#example2').DataTable({ 

      /* FOR EXPORT BUTTONS START*/
  dom:'<"row margin-bottom-12"<"col-sm-12"<"pull-left"l><"pull-right"fr><"pull-right margin-left-10 "B>>>tip',
 /* dom:'<"row"<"col-sm-12"<"pull-left"B><"pull-right">>> <"row margin-bottom-12"<"col-sm-12"<"pull-left"l><"pull-right"fr>>>tip',*/
      buttons: {
        buttons: [
            {
                className: 'btn bg-red color-palette btn-flat hidden delete_btn pull-left',
                text: 'Delete',
                action: function ( e, dt, node, config ) {
                    multi_delete();
                }
            },
            { extend: 'copy', className: 'btn bg-teal color-palette btn-flat',exportOptions: { columns: [1,2,3,4]} },
            { extend: 'excel', className: 'btn bg-teal color-palette btn-flat',exportOptions: { columns: [1,2,3,4]} },
            { extend: 'pdf', className: 'btn bg-teal color-palette btn-flat',exportOptions: { columns: [1,2,3,4]} },
            { extend: 'print', className: 'btn bg-teal color-palette btn-flat',exportOptions: { columns: [1,2,3,4]} },
            { extend: 'csv', className: 'btn bg-teal color-palette btn-flat',exportOptions: { columns: [1,2,3,4]} },
            { extend: 'colvis', className: 'btn bg-teal color-palette btn-flat',text:'Columns' },  

            ]
        },
        /* FOR EXPORT BUTTONS END */

        "processing": true, //Feature control the processing indicator.
        "serverSide": true, //Feature control DataTables' server-side processing mode.
        "order": [], //Initial no order.
        "responsive": true,
        language: {
            processing: '<div class="text-primary bg-primary" style="position: relative;z-index:100;overflow: visible;">Processing...</div>'
        },
        // Load data for the table's content from an Ajax source
        "ajax": {
            "url": "<?php echo site_url('brands/ajax_list')?>",
            "type": "POST",
            
            complete: function (data) {
             $('.column_checkbox').iCheck({
                checkboxClass: 'icheckbox_square-orange',
                /*uncheckedClass: 'bg-white',*/
                radioClass: 'iradio_square-orange',
                increaseArea: '10%' // optional
              });
             call_code();
              //$(".delete_btn").hide();
             },

        },

        //Set column definition initialisation properties.
        "columnDefs": [
        { 
            "targets": [ 0,5 ], //first column / numbering column
            "orderable": false, //set not orderable
        },
        {
            "targets" :[0],
            "className": "text-center",
        },
        
        ],
    });
    new $.fn.dataTable.FixedHeader( table );
});
</script> -->
<script src="<?php echo $theme_link; ?>js/stock.js"></script>
<!-- Make sidebar menu hughlighter/selector -->
<script>$(".<?php echo basename(__FILE__,'.php');?>-active-li").addClass("active");</script>
</body>
</html>
