<?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"> Capital 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">
              <h3>Customer Analysis</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> Customer Analysis
                <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-" />
                </div>


              </div>



              <div class="col-sm-4 pull-right" style="margin-top:22px;">
                <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 class="col-md-12" style="margin-top:22px;">

                <div id="printableArea">
                  <div class="card mb-4">
                    <div class="card-header">Summary Table</div>
                    <div class="card-body">
                      <table class="table table-bordered table-striped">
                        <thead class="table-dark">
                          <tr>
                            <th>#</th>
                            <th>Customer</th>
                            <th>Total Loans</th>
                            <th>Total Loan Amount (Rs.)</th>
                            <th>Total Paid (Rs.)</th>
                            <th>Total Penalties (Rs.)</th>
                            <th>Outstanding (Rs.)</th>
                          </tr>
                        </thead>
                        <tbody>
                          <?php $i = 1;
                          if (isset($customers)): foreach ($customers as $row): ?>
                              <tr>
                                <td><?= $i++; ?></td>
                                <td><?= $row['full_name']; ?></td>
                                <td><?= $row['total_loans']; ?></td>
                                <td class="text-end"><?= number_format($row['total_loan_amount'], 2); ?></td>
                                <td class="text-end text-success"><?= number_format($row['total_paid'], 2); ?></td>
                                <td class="text-end text-danger"><?= number_format($row['total_penalties'], 2); ?></td>
                                <td class="text-end fw-bold"><?= number_format($row['outstanding'], 2); ?></td>
                              </tr>
                          <?php endforeach;
                          endif; ?>
                        </tbody>
                      </table>
                    </div>
                  </div>

                  <!-- CHARTS -->
                  <div class="row">
                    <div class="col-md-8 mb-4">
                      <div class="card">
                        <div class="card-header">Paid vs Outstanding (All Customers)</div>
                        <div class="card-body">
                          <canvas id="barChart"></canvas>
                        </div>
                      </div>
                    </div>
                    <div class="col-md-4 mb-4">
                      <div class="card" id="pieChartCard" style="display:none;">
                        <div class="card-header">Selected Customer Breakdown</div>
                        <div class="card-body">
                          <canvas id="pieChart"></canvas>
                        </div>
                      </div>
                    </div>
                  </div>
                </div><!-- /printableArea -->

              </div>


            </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 src="https://cdn.jsdelivr.net/npm/chart.js"></script>

  <script>
    jQuery(document).ready(function() {


    });




    //-----------------------------------------------------
    $(".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.full_name + "  (" + item.cus_nic + ")";
              return {
                text: text1,
                slug: item.full_name,
                id: item.cus_id
              };
            })
          };
        },
        cache: true
      }
    });
    //-----------------------------------------------------	

  </script>

  <script>
var customers = <?php echo json_encode($customers ?? []); ?>;

// --- Bar Chart (All Customers) ---
var ctxBar = document.getElementById('barChart').getContext('2d');
var barChart = new Chart(ctxBar, {
    type: 'bar',
    data: {
        labels: customers.map(c => c.full_name),
        datasets: [
            {
                label: 'Total Paid',
                data: customers.map(c => parseFloat(c.total_paid) || 0),
                backgroundColor: 'rgba(54,162,235,0.7)'
            },
            {
                label: 'Outstanding',
                data: customers.map(c => parseFloat(c.outstanding) || 0),
                backgroundColor: 'rgba(255,99,132,0.7)'
            }
        ]
    },
    options: {
        responsive: true,
        plugins: { legend: { position: 'top' } }
    }
});

// --- Pie Chart (Selected Customer) ---
var ctxPie = document.getElementById('pieChart').getContext('2d');
var pieChart = new Chart(ctxPie, {
    type: 'pie',
    data: {
        labels: ['Paid', 'Outstanding'],
        datasets: [{
            data: [0, 0],
            backgroundColor: ['#4bc0c0', '#ff9f40']
        }]
    },
    options: { responsive: true, plugins: { legend: { position: 'bottom' } } }
});

// --- On Search Button Click ---
function searchDetails() {
    var cus_id = $('#cus_id').val();
    if (!cus_id) {
        bootbox.alert("Please select a customer!");
        return;
    }

    // Find selected customer from JS array
    var customer = customers.find(c => c.cus_id == cus_id);
    if (customer) {
        pieChart.data.datasets[0].data = [
            parseFloat(customer.total_paid) || 0,
            parseFloat(customer.outstanding) || 0
        ];
        pieChart.update();
        $('#pieChartCard').show();
    } else {
        $('#pieChartCard').hide();
        bootbox.alert("Customer data not found!");
    }
}

// --- Reset Button ---
function searchDetailsReset() {
    $('#cus_id').val(null).trigger('change');
    $('#pieChartCard').hide();
}

// Optional: show Pie chart if preselected customer exists
$(document).ready(function() {
    var preSelId = $('#cus_id').val();
    if(preSelId){
        $('#cus_id').trigger('change');
    }
});
</script>

</body>
<!-- end: BODY -->

</html>