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

<body>
  <div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
      <div class="navbar-header">
        <button data-target=".navbar-collapse" data-toggle="collapse" class="navbar-toggle" type="button"> <span class="clip-list-2"></span> </button>
        <?php $this->load->view("common/logo"); ?>
      </div>
      <div class="navbar-tools">
        <?php $this->load->view("common/notifications.php"); ?>
      </div>
    </div>
  </div>
  <div class="main-container">
    <div class="navbar-content">
      <?php $this->load->view("common/navigation"); ?>
    </div>
    <div class="main-content">
      <div class="container">
        <div class="row">
          <div class="col-sm-12">
            <ol class="breadcrumb">
              <li> <a href="<?php echo base_url('dashboard'); ?>"> Dashboard </a> </li>
              <li> <a href="#"> Reports </a> </li>
              <li class="active"> Recovery Report </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">
              <h1>Recovery Report</h1>
            </div>
            <p>Please use the table below to navigate or filter the results.</p>
          </div>
        </div>
        <div class="row">
          <div class="col-md-12">
            <div class="panel panel-default">
              <div class="panel-heading"> <i class="fa fa-external-link-square"></i> Recovery Report
                <div class="panel-tools" style="top:2px;"></div>
              </div>
              <div class="panel-body">
                <div id="error"></div>
                <div class="col-md-12">
                  <div class="panel panel-default">
                    <div style="font-weight: 700;" class="panel-heading"></div>
                    <div class="panel-body">
                      <form method="post" action="<?php echo base_url('reports_loan/recovery_report'); ?>">
                        <div class="col-sm-3">
                          <div class="form-group">
                            <label>Marketing Officer </label>
                            <select id="user_id" class="form-control" name="user_id">
                              <option value="">All Marketing Officers</option>
                              <?php foreach ($user_list as $row): ?>
                                <option value="<?php echo $row->user_id; ?>" <?php echo $row->user_id == $selected_collector ? 'selected' : ''; ?>>
                                  <?php echo $row->user_first_name . " - " . $row->user_group_name; ?>
                                </option>
                              <?php endforeach; ?>
                            </select>
                          </div>
                        </div>
                        <div class="col-sm-3">
                          <div class="form-group"> <label>Route </label> 
                          <select id="route_id" class="form-control" name="route_id">
                              <option value="">All Routes</option> 
                              <?php foreach ($route_list as $row): ?> 
                                <option value="<?php echo $row['route_id']; ?>" 
                                <?php echo $row['route_id'] == $selected_route ? 'selected' : ''; ?>> 
                                <?php echo $row['route_name']; ?> 
                              </option> 
                              <?php endforeach; ?>
                            </select> 
                          </div>
                        </div>
                        <div class="col-sm-3">
                          <div class="form-group">
                            <label>Date </label>
                            <input id="srh_from_date" name="srh_from_date" type='text' class="form-control date" value="<?php echo $selected_date; ?>" data-bv-field="date" />
                          </div>
                        </div>
                        <div class="col-sm-4 pull-right">
                          <div class="form-group">
                            <label for="s2id_autogen1">&nbsp;<br><br></label>
                            <input type="submit" name="add_category" value="Search" class="btn btn-primary">
                            <input type="button" value="Reset" class="btn btn-danger" onclick="searchDetailsReset()">
                          </div>
                        </div>
                      </form>
                    </div>
                  </div>
                  <div id="printableArea">
                    <div class="page-header">
                      <table class="table table-bordered table-condensed table-striped table-hover dataTable">
                        <tbody>
                          <tr>
                            <td>
                              <h4>Recovery Report</h4> [ User - <span id="user_display"><?php echo $selected_collector && isset($user_list[array_search($selected_collector, array_column($user_list, 'user_id'))]) ? $user_list[array_search($selected_collector, array_column($user_list, 'user_id'))]->user_first_name : 'All Collectors'; ?></span> |
                              Date: <span id="f-date-txt"><?php echo $selected_date; ?></span>]
                            </td>
                          </tr>
                          <tr style="display:none;">
                            <td width="25%"><strong>Total Outstanding</strong></td>
                            <td width="25%"><strong><span id="total_outstanding">Rs. <?php echo number_format($summary['total_outstanding'] ?? 0, 2); ?></span></strong></td>
                          </tr>
                          <tr style="display:none;">
                            <td width="25%">Total Arrears</td>
                            <td width="25%"><span id="total_arrears">Rs. <?php echo number_format($summary['total_arrears'] ?? 0, 2); ?></span></td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  </div>
                  <table class="table table-bordered table-condensed table-hover dataTable" id="warehouse_table">
                    <thead>
                      <tr>
                        <th>#</th>
                        <th>Reference No</th>
                        <th>Customer Name</th>
                        <th>Loan date</th>
                        <th>Due date</th>
                        <th>⁠Total Outstanding</th>
                        <th>Arrears</th>
                        <th>⁠No of missing</th>
                        <th>⁠No of less payment</th>
                        <th>No of Installments paid</th>
                        <th>⁠No of pendin installments</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php if (!empty($report)): ?>
                        <?php $i = 1;
                        foreach ($report as $row): ?>
                          <tr>
                            <td><?php echo $i++; ?></td>
                            <td><?php echo $row['loan_number'] ?? 'N/A'; ?></td>
                            <td><?php echo $row['customer_name'] ?? 'N/A'; ?></td>
                            <td class="text-right"><?php echo $row['loan_date']; ?></td>
                            <td class="text-right"><?php echo $row['next_due_date']; ?></td>
                            <td class="text-right"><?php echo number_format($row['total_outstanding'] ?? 0, 2); ?></td>
                            <td class="text-right"><?php echo number_format($row['arrears'] ?? 0, 2); ?></td>
                            <td class="text-right"><?php echo $row['missing_days'] ?? 0; ?></td>
                            <td class="text-right"><?php echo $row['no_of_less_payments'] ?? 0; ?></td>
                            <td class="text-right"><?php echo $row['loan_no_of_terms'] ?? 0; ?></td>
                            <td class="text-right"><?php echo $row['pending_installments'] ?? 0; ?></td>
                          </tr>
                        <?php endforeach; ?>
                      <?php else: ?>
                        <tr>
                          <td colspan="10">No recovery data available for the selected criteria.</td>
                        </tr>
                      <?php endif; ?>
                    </tbody>
                    <tfoot>
                      <tr>
                        <th colspan="5">Total</th>
                        <th id="outstanding_tot_t" class="text-right">Rs. <?php echo number_format(array_sum(array_column($report ?? [], 'total_outstanding')), 2); ?></th>
                        <th id="arrears_tot_t" class="text-right">Rs. <?php echo number_format(array_sum(array_column($report ?? [], 'arrears')), 2); ?></th>
                        <th></th>
                        <th></th>
                        <th></th>
                      </tr>
                    </tfoot>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="footer clearfix">
      <div class="footer-inner"> <?php echo date("Y"); ?> &copy; 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>
    <?php $this->load->view("common/footer"); ?>
    <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" src="<?php echo asset_url(); ?>js/bootbox.min.js"></script>
    <script type="text/javascript" src="<?php echo asset_url(); ?>js/accounting.js"></script>
    <script type="text/javascript" src="<?php echo asset_url(); ?>js/accounting.min.js"></script>
    <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="https://cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.print.min.js"></script>
    <script>
      function searchDetailsReset() {
        $('#srh_from_date').val('');
        $('#user_id').val('');
        window.location.href = '<?php echo base_url('reports_loan/recovery_report'); ?>';
      }

      function searchDetails() {
        const reportData = <?php echo json_encode($report ?? []); ?>;
        $('#warehouse_table').DataTable({
          dom: 'Blfrtip',
          buttons: [{
            extend: 'print',
            text: 'Print',
            title: 'Recovery Report',
            footer: true,
            exportOptions: {
              columns: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
            },
            customize: function(win) {
              $(win.document.body).prepend($('#printableArea').clone());
              $(win.document.body).find('table').addClass('table table-bordered table-condensed table-striped table-hover');
              $(win.document.body).css('font-size', '12px');
              $(win.document.body).find('th, td').css('padding', '8px');
              $(win.document.body).find('h4').css('margin-top', '0');
            }
          }],
          data: reportData,
          columns: [{
              data: null,
              render: function(data, type, row, meta) {
                return meta.row + 1;
              }
            },
            {
              data: 'customer_name',
              render: function(data) {
                return data || 'N/A';
              }
            },
            {
              data: 'loan_number',
              render: function(data) {
                return data || 'N/A';
              }
            },
            {
              data: 'total_outstanding',
              render: function(data) {
                return accounting.formatMoney(data || 0, "Rs. ", 2, ",", ".");
              }
            },
            {
              data: 'arrears',
              render: function(data) {
                return accounting.formatMoney(data || 0, "Rs. ", 2, ",", ".");
              }
            },
            {
              data: 'missing_days',
              render: function(data) {
                return data || 0;
              }
            },
            {
              data: null,
              render: function(data) {
                return (data.loan_date || 'N/A') + ' / ' + (data.next_due_date || 'N/A');
              }
            },
            {
              data: 'no_of_less_payments',
              render: function(data) {
                return data || 0;
              }
            },
            {
              data: 'loan_no_of_terms',
              render: function(data) {
                return data || 0;
              }
            },
            {
              data: 'pending_installments',
              render: function(data) {
                return data || 0;
              }
            }
          ],
          bDestroy: true,
          iDisplayLength: 20,
          order: [
            [1, "asc"]
          ],
          footerCallback: function(row, data, start, end, display) {
            var api = this.api();
            var outstanding_total = api.column(3).data().reduce(function(a, b) {
              return a + (parseFloat(b) || 0);
            }, 0);
            var arrears_total = api.column(4).data().reduce(function(a, b) {
              return a + (parseFloat(b) || 0);
            }, 0);
            $(api.column(3).footer()).html('Rs. ' + accounting.formatMoney(outstanding_total, "", 2, ",", "."));
            $(api.column(4).footer()).html('Rs. ' + accounting.formatMoney(arrears_total, "", 2, ",", "."));
          }
        });

        $('#f-date-txt').text($('#srh_from_date').val() || '<?php echo $selected_date; ?>');
        $('#user_display').text($('#user_id option:selected').text() || 'All Collectors');
        $('#route_display').text(reportData.length > 0 ? (reportData[0].route_id || 'N/A') : 'N/A');
        $('#total_outstanding').text('Rs. ' + accounting.formatMoney(<?php echo $summary['total_outstanding'] ?? 0; ?>, "", 2, ",", "."));
        $('#total_arrears').text('Rs. ' + accounting.formatMoney(<?php echo $summary['total_arrears'] ?? 0; ?>, "", 2, ",", "."));
      }

      jQuery(document).ready(function() {
        $('#srh_from_date').datetimepicker({
          defaultDate: new Date(),
          format: "YYYY-MM-DD"
        });
        <?php if (!empty($report)): ?>
          searchDetails();
        <?php endif; ?>
      });

      $(document).on('click', 'tr', function(event) {
        $('tr').css('background-color', 'inherit');
        $(this).css('background-color', '#0F6');
      });
    </script>
</body>

</html>