<?php $this->load->view("common/header"); ?>

<!-- end: CSS REQUIRED FOR THIS PAGE ONLY -->
<!-- end: HEAD -->
<!-- start: BODY -->

<body>
  <!-- start: HEADER -->
  <div class="navbar navbar-inverse navbar-fixed-top">
    <!-- start: TOP NAVIGATION CONTAINER -->
    <div class="container">
      <div class="navbar-header">
        <!-- start: RESPONSIVE MENU TOGGLER -->
        <button data-target=".navbar-collapse" data-toggle="collapse" class="navbar-toggle" type="button"> <span class="clip-list-2"></span> </button>
        <!-- end: RESPONSIVE MENU TOGGLER -->
        <!-- start: LOGO -->
        <?php $this->load->view("common/logo"); ?>
        <!-- end: LOGO -->
      </div>
      <div class="navbar-tools">
        <!-- start: TOP NAVIGATION MENU -->
        <?php $this->load->view("common/notifications.php"); ?>
        <!-- end: TOP NAVIGATION MENU -->
      </div>
    </div>
    <!-- end: TOP NAVIGATION CONTAINER -->
  </div>
  <!-- end: HEADER -->
  <!-- start: MAIN CONTAINER -->
  <div class="main-container">
    <div class="navbar-content">
      <!-- start: SIDEBAR -->
      <?php $this->load->view("common/navigation"); ?>
      <!-- end: SIDEBAR -->
    </div>
    <!-- start: PAGE -->
    <div class="main-content">
      <!-- end: SPANEL CONFIGURATION MODAL FORM -->
      <div class="container">
        <!-- start: PAGE HEADER -->
        <div class="row">
          <div class="col-sm-12">
            <!-- start: PAGE TITLE & BREADCRUMB -->
            <ol class="breadcrumb">
              <li> <a href="<?php echo base_url('dashboard'); ?>"> Dashboard </a> </li>
              <li> <a href="#"> Loan Reports </a> </li>
              <li class="active"> Collection Report (Loan Wise)</li>
              <li class="search-box">
                <form class="sidebar-search">
                  <div class="form-group">
                    <input type="text" placeholder="Start Searching...">
                    <button class="submit"> <i class="clip-search-3"></i> </button>
                  </div>
                </form>
              </li>
            </ol>
            <div class="page-header">
              <h3>Collection Report (Loan Wise)</h3>
            </div>
            <p>Please use the table below to navigate or filter the results. </p>
          </div>
        </div>
        <!-- end: PAGE HEADER -->
        <!-- start: PAGE CONTENT 
                    <!-- start grid -->
        <div class="row">
          <div class="col-md-12">
            <!-- start: DYNAMIC TABLE PANEL -->
            <div class="panel panel-default">
              <div class="panel-heading"> <i class="fa fa-external-link-square"></i> Collection Report (Loan Wise)
                <div class="panel-tools" style="top:2px;">
                  <!--------------------->

                  <!--------------------->
                </div>
              </div>
            </div>
            <div class="panel-body">
              <div class="col-md-4">
                <div class="form-group">
                  <label for="loan_interest">Customer </label>
                  <input type="hidden" id="cus_id" name="cus_id" class="js-data-cus_id-ajax form-control" style="padding:0px 0px; border: none; box-shadow: none" placeholder="-Select Customer-" onChange="load_customer_old_recod(this.value);" />
                </div>
              </div>
              <div class="col-md-5">
                <div class="form-group">
                  <label>Loan * </label>
                  <select id="loan_id" class="form-control search-select" name="loan_id">
                    <option value="">- Select Loan -</option>
                    <?php foreach ($loan_details as $row) {
                      if ($row['is_closed'] == 0) {
                        $st = ' [ ongoing ] ';
                      } else {
                        $st = ' [ closed ] ';
                      }
                    ?>
                      <option value="<?php echo $row['loan_id']; ?>"> <?php echo $row['loan_ref'] . " [ Rs.  " . $row['loan_tot_amount'] . " ]  - " . $row['cus_name'] . " - " . $row['cus_nic'] . " " . $st; ?></option>
                    <?php } ?>
                  </select>
                </div>
              </div>
            </div>




            <div class="col-sm-3 pull-right">
              <div class="form-group">
                <label for="s2id_autogen1">&nbsp;<br>
                </label>
                <input type="submit" name="add_category" value="Search" class="btn btn-primary" onClick="searchDetails()">
                &nbsp;&nbsp;
                <input type="submit" name="add_category" value="Reset" class="btn btn-danger" onClick="searchDetailsReset()">
              </div>
            </div>
            <div>
              <div id="printableArea">
                <div class="page-header">
                  <table class="table table-bordered table-condensed table-hover table-striped dataTable" id="">
                    <thead>
                    </thead>
                    <tbody>
                      <tr>
                        <td></td>
                        <td class="text-right">From Date: <span id="f-date-txt">Lording....</span>, To Date: <span id="t-date-txt">Lording....</span></td>
                      </tr>
                      <tr>
                        <th width="50%">Loan Amount</th>
                        <td width="50%">
                          <div id="instalment_amount">Lording....</div>
                        </td>
                      </tr>
                      <tr>
                        <th>Term</th>
                        <td>
                          <div id="capial_amount">Lording....</div>
                        </td>
                      </tr>
                      <tr style="display: none;">
                        <th>Interest %</th>
                        <td>
                          <div id="interest_amount">Lording....</div>
                        </td>
                      </tr>
                      <tr>
                        <th>Delay charge</th>
                        <td>
                          <div id="panalty_c">Lording....</div>
                        </td>
                      </tr>
                        <th>Received excess</th>
                        <td>
                          <div id="excess_c">Lording....</div>
                        </td>
                      </tr>
                      
                    </tbody>
                    
                  </table>



                </div>
              </div>

              <table class="table table-bordered table-condensed table-hover table-striped dataTable" id="warehouse_table">
                <thead>
                  <tr>
                    <th>Date</th>
                    <th>Collect By</th>
                    <th>Recivied <br>
                      Amount</th>
                    <th>Status</th>
                  </tr>
                </thead>
                <tfoot>
                  <tr>
                    <th>Date</th>
                    <th>Collect By</th>
                    <th>Recivied <br>
                      Amount</th>
                    <th>Status</th>
                  </tr>
                </tfoot>
              </table>
            </div>
          </div>
        </div>
        <!-- end: DYNAMIC TABLE PANEL -->
      </div>
    </div>

    <!-- end grid -->

  </div>
  <!-- end: PAGE -->
  </div>
  <!-- end: MAIN CONTAINER -->
  <!-- start: FOOTER -->
  <div class="footer clearfix">
    <div class="footer-inner"> <?php echo date("Y"); ?> © A.S.S.K Loan Management System </div>
    <div class="footer-items"> <span class="go-top"><i class="clip-chevron-up"></i></span> </div>
  </div>
  <!-- end: FOOTER -->
  <!-- start: RIGHT SIDEBAR -->
  <!-- end: RIGHT SIDEBAR -->
  <div id="event-management" class="modal fade" tabindex="-1" data-width="760" style="display: none;">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> &times; </button>
          <h4 class="modal-title">Event Management</h4>
        </div>
        <div class="modal-body"></div>
        <div class="modal-footer">
          <button type="button" data-dismiss="modal" class="btn btn-light-grey"> Close </button>
          <button type="button" class="btn btn-danger remove-event no-display"> <i class='fa fa-trash-o'></i> Delete Event </button>
          <button type='submit' class='btn btn-success save-event'> <i class='fa fa-check'></i> Save </button>
        </div>
      </div>
    </div>
  </div>

  <!-- start ajax model -->
  <div id="ajax-modal" class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1" style="display: none;"></div>
  <!-- end ajax model -->

  <!-- start: MAIN JAVASCRIPTS -->
  <?php $this->load->view("common/footer"); ?>
  <!-- end: MAIN JAVASCRIPTS -->
  <script type="text/javascript" src="<?php echo asset_url(); ?>js/jquery.dataTables.min.js"></script>
  <script type="text/javascript" src="<?php echo asset_url(); ?>js/dataTables.bootstrap.min.js"></script>
  <script type="text/javascript" src="<?php echo base_url('thems/js/bootbox.min.js'); ?>"></script>
  <script src="<?php echo asset_url(); ?>js/jquery-ui.js"></script>
  <script src="<?php echo asset_url(); ?>js/moment-with-locales.js"></script>
  <script type="text/javascript" src="<?php echo asset_url(); ?>js/bootstrap-datetimepicker.js"></script>
  <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/buttons/1.2.3/js/dataTables.buttons.min.js">
  </script>
  <script type="text/javascript" language="javascript" src="//cdn.datatables.net/buttons/1.2.3/js/buttons.print.min.js">
  </script>
  <script type="text/javascript" language="javascript" src="//cdn.datatables.net/buttons/1.2.3/js/buttons.flash.min.js">
  </script>
  <script type="text/javascript" language="javascript" src="//cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js">
  </script>
  <script type="text/javascript" language="javascript" src="//cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/pdfmake.min.js">
  </script>
  <script type="text/javascript" language="javascript" src="//cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/vfs_fonts.js">
  </script>
  <script type="text/javascript" language="javascript" src="//cdn.datatables.net/buttons/1.2.3/js/buttons.html5.min.js">
  </script>
  <script type="text/javascript" language="javascript" src="//cdn.datatables.net/buttons/1.2.3/js/buttons.print.min.js"></script>
  <script>
    jQuery(document).ready(function() {
      //TableData.init();
      //loadGrid();

      // When customer is selected => load loans
      $('#cus_id').on('change', function() {

        let cus_id = $(this).val();

        if (!cus_id) {
          Swal.fire({
            icon: 'warning',
            title: 'No Customer Selected',
            text: 'Please select a customer.',
          });
          return;
        }

        $.post("<?php echo base_url('reports_loan/get_loans_by_customer'); ?>", {
          cus_id: cus_id
        }, function(data) {

          let obj = JSON.parse(data);

          if (obj.status === false) {
            $('#loan_id').html('<option value="">- Select Loan -</option>');
            Swal.fire({
              icon: 'info',
              title: 'No Loans Found',
              text: 'This customer has no loans.',
            });
            return;
          }

          // ✅ Clear loan dropdown
          $('#loan_id').empty();
          $('#loan_id').append('<option value="">- Select Loan -</option>');

          // ✅ Add loans
          $.each(obj.data, function(i, row) {
            let status = row.is_closed == 0 ? ' [ ongoing ] ' : ' [ closed ] ';
            let opt = `<option value="${row.loan_id}">
                ${row.loan_ref} [ Rs. ${row.loan_tot_amount} ] - ${row.cus_name} - ${row.cus_nic} ${status}
            </option>`;
            $('#loan_id').append(opt);
          });

          Swal.fire({
            icon: 'success',
            title: 'Loans Loaded',
            timer: 1000,
            showConfirmButton: false
          });

        });

      });



      var date = new Date();
      var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);

      var currentDate = new Date();
      var tomorrow = new Date();
      $('#srh_to_date').datetimepicker({
        defaultDate: currentDate,
        format: "YYYY-MM-DD"
      });
      $('#srh_from_date').datetimepicker({
        defaultDate: firstDay,
        format: "YYYY-MM-DD"
      });

      //TableData.init();
      load_cash_instalment_summary();
      loadGrid();
      $("#route_id").select2();

      $(".js-data-cus_id-ajax").select2({
        ajax: {
          url: "<?php echo base_url('customers/filter_customer') ?>",
          dataType: 'json',
          delay: 250,
          data: function(query) {
            if (!query)
              query = '';
            return {
              search_string: query,
              format: 'json'
            };
          },
          results: function(data) {
            return {
              results: $.map(data, function(item) {
                var text1 = item.business_name + "  (" + item.cus_nic + ")";
                return {
                  text: text1,
                  slug: item.full_name,
                  id: item.cus_id
                };
              })
            };
          },
          cache: true
        }
      });

    });



    function load_cash_instalment_summary() {

      var loan_id = $('#loan_id').val();
      var srh_from_date = $('#srh_from_date').val();
      var srh_to_date = $('#srh_to_date').val();


      $.post("<?php echo base_url(); ?>reports_loan/get_loan_installment_summary_loan_wise", {
          loan_id: loan_id,
          srh_from_date: srh_from_date,
          srh_to_date: srh_to_date
        })
        .done(function(data) {
          var obj = jQuery.parseJSON(data);

          $('#instalment_amount').text(accounting.formatMoney(obj.loan_received, "", 2, ",", "."));
          $('#capial_amount').text(accounting.formatMoney(obj.capital_received, "", 2, ",", "."));
          $('#interest_amount').text(accounting.formatMoney(obj.loan_interest_recived, "", 2, ",", "."));
          $('#panalty_c').text(accounting.formatMoney(obj.panalty_received, "", 2, ",", "."));
          $('#due_c').text(accounting.formatMoney(obj.due_received, "", 2, ",", "."));
          $('#total_r_c').text(accounting.formatMoney(obj.pymnt_amount, "", 2, ",", "."));
          $('#excess_c').text(accounting.formatMoney(obj.excess_received, "", 2, ",", "."));

          //loadGrid();// load customer data
        });
    }



    function printDiv(divName) {
      var printContents = document.getElementById(divName).innerHTML;
      var originalContents = document.body.innerHTML;

      document.body.innerHTML = printContents;

      window.print();

      document.body.innerHTML = originalContents;
    }

    function searchDetailsReset() {
      $('#srh_to_date').val('');
      $('#srh_from_date').val('');
    }

    function searchDetails() {
      load_cash_instalment_summary();
      loadGrid();
      //loadGridSalesReturn();
    }

    function loadGrid() {
      var loan_id = $('#loan_id').val();
      //var loan_payment_term=$('#loan_payment_term').val();
      var srh_from_date = $('#srh_from_date').val();
      var srh_to_date = $('#srh_to_date').val();



      $('#warehouse_table').DataTable({

        dom: 'Blfrtip',
        buttons: [{
            extend: 'print',
            text: 'Print',
            footer: true
          },
          {
            extend: 'excel',
            text: 'Save as Excel',
            footer: true
          },
          {
            extend: 'pdf',
            text: 'Save as Pdf',
            footer: true
          },
        ],
        "ajax": {
          'type': 'POST',
          'url': '<?php echo base_url('reports_loan/get_loan_installment_list_loan_wise'); ?>',
          'data': {
            loan_id: loan_id,
            srh_from_date: srh_from_date,
            srh_to_date: srh_to_date
          }
        },
        "bDestroy": true,
        "iDisplayLength": 10,
        "bDestroy": true,
        "iDisplayLength": 20,
        "order": [
          [1, "desc"]
        ],
        "fnFooterCallback": function(nRow, aaData, iStart, iEnd, aiDisplay) {

          /* var pq = 0, sq = 0, bq = 0, pa = 0, grand_tot = 0, tech_tot = 0, parts_tot=0 , ser_tot=0;
				//alert(aaData.length);
				var ser_tot3=0;
				var ser_tot2=0;
				var ser_tot1=0;
				var ser_tot4=0;
				var ser_tot5=0;
				//var sales_rtn=0;
                for (var i = 0; i < aaData.length; i++) 
				{
					ser_tot1 += parseFloat(aaData[[i]][6]);
					ser_tot2 += parseFloat(aaData[[i]][7]);
					ser_tot3 += parseFloat(aaData[[i]][8]);	
					ser_tot4 += parseFloat(aaData[[i]][9]);
					ser_tot5 += parseFloat(aaData[[i]][10]);					
                }	
				 var nCells = nRow.getElementsByTagName('th');
				nCells[6].innerHTML = '<div class="text-right">'+accounting.formatMoney(ser_tot1, "", 2, ",", ".")+' </div>';
				nCells[7].innerHTML = '<div class="text-right">'+accounting.formatMoney(ser_tot2, "", 2, ",", ".")+' </div>';
				nCells[8].innerHTML = '<div class="text-right">'+accounting.formatMoney(ser_tot3, "", 2, ",", ".")+' </div>';
				nCells[9].innerHTML = '<div class="text-right">'+accounting.formatMoney(ser_tot4, "", 2, ",", ".")+' </div>';
				nCells[10].innerHTML = '<div class="text-right">'+accounting.formatMoney(ser_tot5, "", 2, ",", ".")+' </div>';	*/

        }
      });

    }

    function fbs_click(url) {
      var srh_from_date = $('#srh_from_date').val();
      var srh_to_date = $('#srh_to_date').val();
      var srh_warehouse_id = $('#srh_warehouse_id').val();
      u = location.href;
      t = document.title;
      url = '<?php echo base_url(); ?>' + 'reports/print_sale?srh_warehouse_id=' + srh_warehouse_id + '&srh_from_date=' + srh_from_date + '&srh_to_date=' + srh_to_date;
      window.open(url, 'sharer', 'toolbar=0,status=0,width=750,height=436, left=10, top=10,scrollbars=yes');
      return false;
    }
  </script>
</body>
<!-- end: BODY -->

</html>