<!DOCTYPE html>
<html>

<head>
<!-- TABLES CSS CODE -->
<?php include"comman/code_css_datatable.php"; ?>
 <link rel="stylesheet" href="<?php echo $theme_link; ?>sweetalert/sweetalert.css">
 <script src="<?php echo $theme_link; ?>js/sweetalert.min.js"></script>
</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 Suppliers</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>
    <div class="pay_now_modal">
    </div>
    <div class="pay_return_due_modal">
    </div>
    <!-- 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>
              <?php if($CI->permissions('suppliers_add')) { ?>
              <div class="box-tools">
                <a class="btn btn-block btn-info" href="<?php echo $base_url; ?>suppliers/add">
                <i class="fa fa-plus"></i> <?= $this->lang->line('new_supplier'); ?></a>
              </div>
              <?php } ?>
            </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">
                    <input type="checkbox" class="group_check checkbox" >
                  </th>
                  <th><?= $this->lang->line('supplier_id'); ?></th>
                  <th><?= $this->lang->line('supplier_name'); ?></th>
                  <th><?= $this->lang->line('mobile'); ?></th>
                  <th><?= $this->lang->line('email'); ?></th>
                  <th>Total Due</th>
                  <th><?= $this->lang->line('purchase_return_due'); ?></th>
                  <th><?= $this->lang->line('status'); ?></th>
                  <th><?= $this->lang->line('action'); ?></th>
                </tr>
                </thead>
                <tbody>
				
                </tbody>
               <tfoot>
                  <tr class="bg-gray">
                      <th colspan="5" style="text-align:right">Total</th>
                      <th></th>
                      <th></th>
                      <th></th><!-- 7 -->
                      <th></th><!-- 8 -->
                  </tr>
              </tfoot>
              </table>
            </div>
            <!-- /.box-body -->
          </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"; ?>
<!-- bootstrap datepicker -->
<script src="<?php echo $theme_link; ?>plugins/datepicker/bootstrap-datepicker.js"></script>
<script type="text/javascript">
  //Date picker
    $('.datepicker').datepicker({
      autoclose: true,
    format: 'dd-mm-yyyy',
     todayHighlight: true
    });
</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,5,6,7]} },
            { extend: 'excel', className: 'btn bg-teal color-palette btn-flat',exportOptions: { columns: [1,2,3,4,5,6,7]} },
            { extend: 'pdf', className: 'btn bg-teal color-palette btn-flat',exportOptions: { columns: [1,2,3,4,5,6,7]} },
            { extend: 'print', className: 'btn bg-teal color-palette btn-flat',exportOptions: { columns: [1,2,3,4,5,6,7]} },
            { extend: 'csv', className: 'btn bg-teal color-palette btn-flat',exportOptions: { columns: [1,2,3,4,5,6,7]} },
            { 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.
        "order": [5, "desc"],
        // "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('suppliers/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,8 ], //first column / numbering column
            "orderable": false, //set not orderable
        },
        {
            "targets" :[0],
            "className": "text-center",
        },
        {
            "targets" :[5],
            "className": "text-right",
        },
        
        ],
        /*Start Footer Total*/
        "footerCallback": function ( row, data, start, end, display ) {
            var api = this.api(), data;
            // Remove the formatting to get integer data for summation
            var intVal = function ( i ) {
                return typeof i === 'string' ?
                    i.replace(/[\$,]/g, '')*1 :
                    typeof i === 'number' ?
                        i : 0;
            };
          
            var purchase_due = api
                .column( 5, { page: 'none'} )
                .data()
                .reduce( function (a, b) {
                    return intVal(a) + intVal(b);
                }, 0 );
            var purchase_return_due = api
                .column( 6, { page: 'none'} )
                .data()
                .reduce( function (a, b) {
                    return intVal(a) + intVal(b);
                }, 0 );
            //$( api.column( 0 ).footer() ).html('Total');
            $( api.column( 5 ).footer() ).html(app_number_format(purchase_due));
            $( api.column( 6 ).footer() ).html(app_number_format(purchase_return_due));
        },
        /*End Footer Total*/
    });
    new $.fn.dataTable.FixedHeader( table );
});
</script>

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

<script>
  function cheque_list_now(supplier_id) {
    $.ajax({
      url: "<?php echo site_url('suppliers/get_cheque_list')?>",
      type: 'POST',
      data: {supplier_id: supplier_id},
      dataType: 'json',
      success: function(data) {
        var modal_content = '<div class="modal fade" id="chequeListModal" tabindex="-1" role="dialog">';
        modal_content += '<div class="modal-dialog modal-lg" role="document">';
        modal_content += '<div class="modal-content">';
        modal_content += '<div class="modal-header">';
        modal_content += '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
        modal_content += '<h4 class="modal-title">Own Cheque Payments</h4>';
        modal_content += '</div>';
        modal_content += '<div class="modal-body">';
        modal_content += '<table class="table table-bordered table-striped">';
        modal_content += '<thead><tr><th>Cheque No</th><th>Cheque Date</th><th>Amount</th><th>Bank</th><th>Status</th><th>Action</th></tr></thead>';
        modal_content += '<tbody>';
        
        if(data.cheques && data.cheques.length > 0) {
          $.each(data.cheques, function(index, cheque) {
            modal_content += '<tr>';
            modal_content += '<td>' + cheque.cheque_no + '</td>';
            modal_content += '<td>' + cheque.cheque_date + '</td>';
            modal_content += '<td>' + parseFloat(cheque.amount).toFixed(2) + '</td>';
            modal_content += '<td>' + cheque.bank + '</td>';
            modal_content += '<td>' + cheque.status + '</td>';
            modal_content += '<td><button class="btn btn-sm btn-primary" onclick="processPayment(' + cheque.id + ', ' + supplier_id + ')">Process Payment</button></td>';
            modal_content += '</tr>';
          });
        } else {
          modal_content += '<tr><td colspan="6" class="text-center">No cheques available for payment</td></tr>';
        }
        
        modal_content += '</tbody></table>';
        modal_content += '</div>';
        modal_content += '<div class="modal-footer">';
        modal_content += '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>';
        modal_content += '</div>';
        modal_content += '</div></div></div>';
        
        $('body').append(modal_content);
        $('#chequeListModal').modal('show');
        
        $('#chequeListModal').on('hidden.bs.modal', function () {
          $(this).remove();
        });
      },
      error: function(xhr, ajaxOptions, thrownError) {
        console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
      }
    });
  }

  function processPayment(cheque_id, supplier_id) {
    swal({
      title: 'Are you sure?',
      text: 'Do you want to process this cheque payment?',
      icon: 'warning',
      buttons: {
        cancel: 'Cancel',
        confirm: 'OK'
      }
    }).then(function(isConfirm) {
      if (isConfirm) {
        $.ajax({
          url: "<?php echo site_url('suppliers/process_cheque_payment')?>",
          type: 'POST',
          data: {cheque_id: cheque_id, supplier_id: supplier_id},
          dataType: 'json',
          success: function(response) {
            if(response.success) {
              swal('Success!', 'Payment processed successfully', 'success');
              $('#chequeListModal').modal('hide');
              fill_tbData(); // Refresh the table
            } else {
              swal('Error!', 'Error processing payment: ' + response.message, 'error');
            }
          },
          error: function(xhr, ajaxOptions, thrownError) {
            swal('Error!', 'Error processing payment', 'error');
            console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
          }
        });
      }
    });
  }
</script>

<script>
  function fill_tbData(){
      $.ajax({
        url:"<?php echo site_url('suppliers/ajax_list')?>",
        type: 'get',
        // data: {from_date:from_date,to_date:to_date},
        dataType: 'json',
        success: function (data) {
          var table;
          table = $('#example2').DataTable();
          table.clear();
          
          $.each(data.sup_info, function(){
            var s_id = parseInt(this['id']);
      
            if(s_id==1){
              var row1 = '<span class="text-blue">NA</span>';	
              var disable = 'disabled';
            }
            else{
              var disable = '';
              var row1 = '<input type="checkbox" name="checkbox[]" '+disable+' value='+s_id+' class="checkbox column_checkbox" >';
            }  
            var cus_status = parseInt(this['status']);

            if(cus_status==1){ 
			 			  var str= "<span onclick='update_status("+s_id+",0)' id='span_"+s_id+"'  class='label label-success' style='cursor:pointer'>Active </span>";
            }else{ 
						  var str = "<span onclick='update_status("+s_id+",1)' id='span_"+s_id+"'  class='label label-danger' style='cursor:pointer'> Inactive </span>";
					  }
                
            var str2 = '';
					  str2 += '<div class="btn-group" title="View Account"><a class="btn btn-primary btn-o dropdown-toggle" data-toggle="dropdown" href="#">Action <span class="caret"></span></a><ul role="menu" class="dropdown-menu dropdown-light pull-right">';
            <?php if($CI->permissions('suppliers_edit')) { ?>
                str2 +='<li><a title="Edit Record ?" href="suppliers/update/'+s_id+'"><i class="fa fa-fw fa-edit text-blue"></i>Edit</a></li>';
            <?php } ?>
            <?php if($CI->permissions('purchase_payment_add')) { ?>
								str2 +='<li><a title="Pay Opening Balance & Purchase Due Payments" class="pointer" onclick="pay_now('+s_id+')" ><i class="fa fa-fw fa-money text-blue"></i>Pay Due Payments</a></li>';
            <?php } ?>
            <?php if($CI->permissions('purchase_payment_add')) { ?>
								str2 +='<li><a title="Own Cheque Payments" class="pointer" onclick="cheque_list_now('+s_id+')" ><i class="fa fa-fw fa-money text-blue"></i>Own Cheque Payments</a></li>';
            <?php } ?>
            <?php if($CI->permissions('purchase_return_payment_add')) { ?>
								str2 +='<li><a title="Pay Return Due" class="pointer" onclick="pay_return_due('+s_id+')" > <i class="fa fa-fw fa-money text-blue"></i>Pay Return Due</a></li>';
            <?php } ?>
            <?php if($CI->permissions('suppliers_edit')) { ?>
              if(s_id!=1){
                str2 +='<li><a style="cursor:pointer" title="Delete Record ?" onclick="delete_suppliers('+s_id+')"><i class="fa fa-fw fa-trash text-red"></i>Delete</a></li></ul></div>';
              }
            <?php } ?>
             
            var opening_balance = this['opening_balance'];
            if (opening_balance === null) {
              opening_balance = 0;
            } else {
              opening_balance = parseFloat(this['opening_balance']);
            }

            var purchase_due = this['purchase_due'];
            if (purchase_due === null) {
              purchase_due = 0;
            } else {
              purchase_due = parseFloat(this['purchase_due']);
            }

            var purchase_return_due = this['purchase_return_due'];
            if (purchase_return_due === null) {
              purchase_return_due = 0;
            } else {
              purchase_return_due = parseFloat(this['purchase_return_due']).toFixed(2);
            }

            var supplier_code = this['supplier_code']; 
            var supplier_name = this['supplier_name']; 
            var mobile = this['mobile']; 
            var email = this['email'];

            $.ajax({
              url:"<?php echo site_url('suppliers/get_paid_amount')?>",
              type: 'post',
              data: {s_id:s_id},
              dataType: 'json',
              success: function (data) {          
                var sum_of_ob_paid = parseFloat(data.sum_of_ob_paid);
                // alert(sum_of_ob_paid);
                var supplier_balance_due = opening_balance - sum_of_ob_paid;

              	var tot_due = purchase_due+supplier_balance_due;

                table.row.add([row1,supplier_code,supplier_name,mobile,email, tot_due.toFixed(2),purchase_return_due.toFixed(2), str, str2]);
                table.draw();
              }
            });
          });
        },
        error: function (xhr, ajaxOptions, thrownError) {
          console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }
      });
  }
</script>

<script src="<?php echo $theme_link; ?>js/suppliers.js"></script>

<!-- Make sidebar menu hughlighter/selector -->
<script>$(".<?php echo basename(__FILE__,'.php');?>-active-li").addClass("active");</script>

<script>
  function displayChqArea(ctl){
   
    var p_type = $("#payment_type").val();
    //alert(p_type);
    if(p_type=="Cheque"){
      $("#chqArea").attr("hidden",false);
    }else{
      $("#chequeNo").val("");
      $("#chequeDate").val("");
      $("#chequeClearance").val("");
      $("#chequeBank").val("");

      $("#chqArea").attr("hidden",true);
    }
  }
</script>

<script>
  function checkAvailabilityChk() {
    var chequeNo    = $('#chequeNo').val();
      jQuery.ajax({
        url:"<?php echo site_url('sales/check_chkNo')?>",
        data:{chequeNo:chequeNo},
        type: "POST",
        success:function(data){
          var c_count = parseInt(data);
          if(c_count>0){
          $('#chequeNo').val("");
          $("#error_chk").html("This cheque no. already exists.");
          }else{
          $("#error_chk").html("");
          }
        },
        error:function (){}
    });
  }
</script>

</body>
</html>
