<?php $this->load->view("common/header"); ?>
<!-- Bootstrap Datepicker CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">

<!-- 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">
      <!-- start: PANEL CONFIGURATION MODAL FORM -->
      <div class="modal fade" id="panel-config" tabindex="-1" role="dialog" aria-hidden="true">
        <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">Panel Configuration</h4>
            </div>
            <div class="modal-body"> Here will be a configuration form </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal"> Close </button>
              <button type="button" class="btn btn-primary"> Save changes </button>
            </div>
          </div>
          <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
      </div>
      <!-- /.modal -->
      <!-- 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="<?php echo base_url('loan'); ?>"> Loans </a> </li>
              <li class="active">New Loan></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>


            <!-- end: PAGE TITLE & BREADCRUMB -->
          </div>
        </div>
        <!-- start grid -->

        <!-- sart tab -->
        <?php $config = array('role' => 'form', 'class' => 'form-horizontal', 'id' => 'loan_item_save', 'name' => 'loan_item_save');
        echo form_open_multipart("#", $config); ?>
        <!-- start: INLINE TABS PANEL -->
        <div class="panel panel-default">
          <div class="panel-heading"> <i class="fa fa-reorder"></i>
            <div> Loan Information </div>
            <div class="panel-tools"> <a class="btn btn-xs btn-link panel-collapse collapses" href="#"> </a> <a class="btn btn-xs btn-link panel-refresh" href="#"> <i class="fa fa-refresh"></i> </a> <a class="btn btn-xs btn-link panel-expand" href="#"> <i class="fa fa-resize-full"></i> </a> <a class="btn btn-xs btn-link panel-close" href="#"> <i class="fa fa-times"></i> </a> </div>
          </div>
          <div class="panel-body">
            <div class="clearfix"> </div>
            <!--start header details details-->
            <div class="col-md-12">
              <div class="panel panel-default">

                <div class="panel-heading" style="font-weight: 500;"> Schedule of payments </div>
                <div class="panel-body">

                  <div class="row">
                    <div class="col-md-2">
                      <label>Loan Type *</label>
                      <div class="form-group"><input type="radio" checked name="loan_type" value="Passive" id="loan_type_passive">
                        <label for="loan_type_passive">Passive</label>
                        <input type="radio" name="loan_type" value="Normal" id="loan_type_normal">
                        <label for="loan_type_normal">Normal</label>
                      </div>
                    </div>

                    <div class="col-md-2">
                      <label>Loan Date *</label>
                      <?php $nowdate = date("Y-m-d H:i:s"); ?>
                      <div class="input-group">
                        <input id="loan_date" type="text" autocomplete="off" data-date-format="dd-mm-yyyy" data-date-viewmode="years" class="form-control date-picker" name="loan_date" value=" <?php echo date('d-m-Y'); ?>">
                        <span class="input-group-addon"> <i class="fa fa-calendar"></i> </span>
                      </div>
                    </div>

                    <div class="col-md-2">
                      <div class="form-group">
                        <label for="loan_payment_term">Payment Term * </label>
                        <select id="loan_payment_term" class="form-control search-select" name="loan_payment_term">
                          <?php
                          foreach ($payment_term_list as $row) {
                            $sel = '';
                          ?>
                            <option value="<?php echo $row['id']; ?>"><?php echo $row['payment_term_name']; ?></option>
                          <?php }  ?>
                        </select>
                      </div>
                    </div>

                    <div class="col-sm-2">
                      <div class="form-group">
                        <label>Route * </label>
                        <select id="route_id" class="form-control search-select" name="route_id">
                          <option value="">- select route - </option>
                          <?php foreach ($routes_list as $row) { ?>
                            <option value="<?php echo $row['route_id']; ?>"> <?php echo $row['route_name']; ?> </option>
                          <?php } ?>
                        </select>
                      </div>
                    </div>

                    <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>

                  <div class="row">
                    <div class="col-md-2">
                      <div class="form-group">
                        <label for="loan_interest">Interest (%) * </label>
                        <input style="text-align:right;" type="number" id="loan_interest" name="loan_interest" class="form-control" value="" data-d-group="2" onChange="calculate_payble_abount()">
                      </div>
                    </div>

                    <div class="col-md-2">
                      <div class="form-group">
                        <label for="bkng_head_count">No. of Term * </label>
                        <input style="text-align:right;" type="number" id="loan_no_of_terms" name="loan_no_of_terms" class="form-control" value="" data-d-group="2" onChange="calculate_payble_abount()">
                      </div>
                    </div>

                    <div class="col-md-2">
                      <div class="form-group">
                        <label for="loan_term_amount">Realization Date </label>
                        <input style="text-align:right;" type="text" value="" class="form-control" name="loan_end_date" id="loan_end_date" readonly="">
                      </div>
                    </div>
                    <div class="col-md-2">
                      <div class="form-group">
                        <label for="loan_term_amount">Days </label>
                        <input style="text-align:right;" type="text" value="" class="form-control" name="loan_no_of_days" id="loan_no_of_days" readonly="">
                      </div>
                    </div>

                    <div class="col-md-2" style="display:none">
                      <div class="form-group">
                        <label for="loan_interest_type">Interest Type </label>
                        <select id="loan_interest_type" class="form-control search-select" name="loan_interest_type">
                          <option value="1">Standard Type</option>
                        </select>
                      </div>
                    </div>

                    <div style="display: none;" class="col-md-4">
                      <div class="form-group">
                        <label for="g_cus_id">Garenter </label>
                        <input type="hidden" id="g_cus_id" name="g_cus_id" class="js-data-g_cus_id-ajax form-control" style="padding:0px 0px; border: none; box-shadow: none" placeholder="-Select Garenter-" />
                        <!-- <a id="modal_ajax_customers_btn_garanter" style="cursor:pointer;"><i style="float: left;position: absolute;margin-left: 7px;margin-top: 5px;" class="fa fa-2x fa-plus-circle addIcon" id="addIcon"></i></a> -->
                      </div>
                    </div>
                  </div>

                  <div class="row">

                    <div class="col-md-3">
                      <div class="col-md-12">
                        <div class="form-group">
                          <label for="menu_id">Total Amount * </label>
                          <input style="text-align:right;" type="number" id="loan_tot_amount" name="loan_tot_amount" class="form-control" value="" data-d-group="2" onChange="calculate_payble_abount()">
                        </div>
                      </div>
                    </div>
                    <div class="col-md-3">
                      <div class="form-group">
                        <label for="loan_term_amount">Term Amount * </label>
                        <input style="text-align:right;" type="text" value="" class="form-control" name="loan_term_amount" id="loan_term_amount" readonly>
                      </div>
                    </div>
                    <div class="col-md-2">
                      <div class="form-group"> <br>
                        <input type="checkbox" name="reduce_from_cheque" value="1" id="reduce_from_cheque">
                        Reduce from Cheqe Date<br>
                        <input type="checkbox" name="panalty_enable" value="1" checked id="panalty_enable">
                        Panelty Enable<br>
                      </div>
                    </div>
                    <div class="col-md-2">
                      <div class="form-group">
                        Panalty % <input type="number" name="panalty_presentage" value="0.1" id="panalty_presentage">

                        Due % <input type="number" name="due_presentage" value="0.3" id="due_presentage">
                      </div>
                    </div>
                  </div>


                  <div class="row" id="cheque_section" style="display:none; margin-top:20px;">
                    <div class="panel panel-default">
                      <div class="panel-heading">Cheque Details</div>
                      <div class="panel-body">
                        <table class="table table-bordered" id="cheque_table">
                          <thead>
                            <tr>
                              <th>Cheque Date</th>
                              <th>Realization Date</th>
                              <th>Cheque Amount</th>
                              <th>Bank</th>
                              <th>Branch</th>
                              <th>Days</th>
                              <th>Charges</th>
                              <th>Action</th>
                            </tr>
                          </thead>
                          <tbody></tbody>
                        </table>

                        <button type="button" id="add_cheque_row" class="btn btn-success">
                          <i class="fa fa-plus"></i> Add Cheque
                        </button>
                      </div>
                    </div>
                  </div>



                  <div class="row" style="margin-right:2%;">
                    <div class="col-md-12" style="margin-right:2%;">
                      <label for="note">Note </label>
                      <textarea id="note" name="note" class="form-control"></textarea>
                    </div>
                  </div>

                  <div class="row">

                    <div class="col-md-4">
                      <div class="form-group">
                        <label for="loan_interest">Marketing Officer </label>
                        <select id="marketing_officer_id" class="form-control search-select" name="marketing_officer_id">
                            <option value="0">-Select--</option>
                          <?php
                          if($marketing_officer_list){
                          foreach ($marketing_officer_list as $rmol) {
                            $sel = '';
                          ?>
                            <option value="<?php echo $rmol->user_id; ?>"><?php echo $rmol->user_first_name ?></option>
                          <?php } } ?>
                        </select>
                        
                      </div>
                    </div>
                    <div class="col-md-3">
                      <div class="form-group">
                        <label for="loan_term_amount">Commission percentage * </label>
                        <input style="text-align:right;" type="text" placeholder="0.00" class="form-control" name="marketing_officer_discount" id="marketing_officer_discount" >
                      </div>
                    </div>
                  </div> 

                  <div class="col-md-12" style="margin-right:2%;">
                    <br>
                  </div>
                  <div class="col-md-6" style="margin-right:2%;">
                    <div class="col-md-8" style="margin-right:2%; ">
                      <div class="form-group" style="border: thin solid black;">
                        <div class="col-md-12"> <br>
                          <p><strong><u> Summary </u> </strong> </p>
                          <p> Total Amount : <span id="payable_total_amount_txt"> </span> </p>
                          <p id="no_of_terms_txt_p"> No of Terms : <span id="no_of_terms_txt"> </span> </p>
                          <p style="display:none;"> Payable Term Amount : <span id="payable_term_amount_txt"> </span> </p>
                          <p> Total Charges : <span id="total_charges_txt"> </span> </p>
                          <p> Pay Amount : <span id="pay_amount_txt"> </span> </p>
                          <p id="days_txt_p"> Days : <span id="days_txt"> </span> </p>
                          <p id="loan_date_txt_p"> Loan Date : <span id="loan_date_txt"> </span> </p>
                          <p id="realization_date_txt_p"> Realization Date : <span id="realization_date_txt"> </span> </p>
                          <br>
                        </div>
                      </div>
                    </div>
                  </div>



                  <div class="col-md-3 pull-right" style="margin-right:2%;">
                    <div class="form-group">

                      <input name="service_type" type="hidden" value="">
                      <a href="#" class="btn btn-primary show-tab pull-right" id="loan_inv_hdr"> Proceed <i class="fa fa-arrow-circle-right"></i> </a>

                      <?php if (isset($vcl_srvs_inv_header) && $vcl_srvs_inv_header) { ?>
                        <a href="#" class="btn btn-primary show-tab pull-right" id="loan_inv_hdr_update"> Update Loan Details <i class="fa fa-save"></i> </a>
                      <?php } ?>

                      <button type="reset" class="btn btn-danger show-tab pull-right" id="reset_form"> Cancel</button>
                    </div>
                  </div>

                </div>


                <input type="hidden" id="loan_payable_total_amount" name="loan_payable_total_amount" value="" readonly />
                <input type="hidden" id="loan_id" name="loan_id" value="" readonly />
                <input type='hidden' id="loan_ref" name="loan_ref" value="" readonly />
                <input type='hidden' id="total_interest" name="total_interest" value="" readonly />
                <input type='hidden' id="term_intrerest" name="term_intrerest" value="" readonly />
                <input id="warehouse_id" name="warehouse_id" type="hidden" value="<?php echo $this->session->userdata('ss_warehouse_id'); ?>">

              </div>
            </div>


            <div class="col-md-12" style="margin-right:2%;">
              <div class="form-group"><br>
                Customer History
                <div class="panel-body">
                  <div id="error"></div>
                  <table class="table table-bordered table-condensed table-hover table-striped dataTable" id="products_table">
                    <thead>
                      <tr>
                        <th></th>
                        <th>Reference<br>
                          No.</th>
                        <th>Customer</th>
                        <th>Loan Date <br />
                          (yyyy-mm-dd)</th>
                        <th>Payment<br>
                          Term</th>
                        <th>No. of<br>
                          Months</th>
                        <th>Term<br>
                          Amount </th>
                        <th>Monthlly <br>
                          Interest </th>
                        <th>Status</th>
                        <th>Capital Amount</th>
                        <th>Paid( Loan )</th>
                        <th>Balance ( Loan )</th>
                        <th>Action</th>
                      </tr>
                    </thead>
                    <tfoot>
                      <tr>
                        <th></th>
                        <th>Reference No.</th>
                        <th>Customer</th>
                        <th>Loan Date</th>
                        <th>Payment <br>
                          Term</th>
                        <th>No. of<br>
                          Months</th>
                        <th>Term <br>
                          Amount </th>
                        <th>Monthlly <br>
                          Interest </th>
                        <th>Status</th>
                        <th>Paid</th>
                        <th>Total Amount</th>
                        <th>Balance</th>
                        <th>Action</th>
                      </tr>
                    </tfoot>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!--end header details details-->
    </form>
    <!-- end tab -->


  </div>
  <!-- end: PAGE -->
  </div>

  <!-- end: MAIN CONTAINER -->
  <!-- start: FOOTER -->
  <div class="footer clearfix">
    <div class="footer-inner"> <?php echo date("Y"); ?> &copy; Financial Management System by sallelanka solutions. </div>
    <div class="footer-items"> <span class="go-top"><i class="clip-chevron-up"></i></span> </div>
  </div>
  <!-- end: FOOTER -->
  <!-- start: RIGHT SIDEBAR -->
  <div id="page-sidebar"> <a class="sidebar-toggler sb-toggle" href="#"><i class="fa fa-indent"></i></a>
    <div class="sidebar-wrapper">
      <ul class="nav nav-tabs nav-justified" id="sidebar-tab">
        <li class="active"> <a href="#users" role="tab" data-toggle="tab"><i class="fa fa-users"></i></a> </li>
        <li> <a href="#favorites" role="tab" data-toggle="tab"><i class="fa fa-heart"></i></a> </li>
        <li> <a href="#settings" role="tab" data-toggle="tab"><i class="fa fa-gear"></i></a> </li>
      </ul>
    </div>
  </div>

  <!-- 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>

  <!-- end: RIGHT SIDEBAR -->
  <!-- start: MAIN JAVASCRIPTS -->
  <?php $this->load->view("common/footer"); ?>

  <!-- end: MAIN JAVASCRIPTS -->
  <script src="<?php echo asset_url(); ?>js/form-validation-loan_add.js"></script>
  <script src="<?php echo asset_url(); ?>js/loan_add.js?v=13"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
  <!-- Bootstrap Datepicker JS -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>

  <!-- end: JAVASCRIPTS REQUIRED FOR THIS PAGE ONLY -->
  <script>
  
  $(document).on('click', '.remove-cheque', function() {
      let row = $(this).closest('tr');

      // Destroy Select2 instances to prevent memory leaks
      row.find('.bank_select.search-select').select2('destroy');
      row.find('.branch_select.search-select').select2('destroy');

      row.remove();

      // Optional: recalculate totals after removing a cheque
      calculate_payble_abount();
    });
    
    $(document).on('change', '.bank_select', function() {
      let bankId = $(this).val();
      let row = $(this).closest('tr');
      let branchSelect = row.find('.branch_select');

      // Show loading
      branchSelect.html('<option value="">Loading...</option>').trigger('change');

      if (bankId) {
        $.ajax({
          url: "<?= base_url('loan/get_branches_by_bank') ?>",
          type: "POST",
          data: {
            bank_id: bankId
          },
          dataType: "json",
          success: function(data) {
            let html = '<option value="">Select Branch</option>';
            $.each(data, function(i, row) {
              html += `<option value="${row.id}">
                                ${row.branch_name} (${row.branch_code})
                             </option>`;
            });

            // Update options
            branchSelect.html(html);

            // THIS IS THE KEY FIX
            branchSelect.trigger('change'); // Correct way to refresh Select2 after replacing options
          },
          error: function() {
            branchSelect.html('<option value="">Error loading branches</option>').trigger('change');
          }
        });
      } else {
        branchSelect.html('<option value="">Select Branch</option>').trigger('change');
      }
    });
  
    let holidays = [];

    $.getJSON("<?= base_url('loan/get_holidays'); ?>", function(data) {
      holidays = data; // array of holiday dates in DD/MM/YYYY
    });

    $(document).on("change", ".cheque_date", function() {
      const $row = $(this).closest("tr");
      const chequeDateStr = $(this).val();
      const chequeDate = moment(chequeDateStr, "DD/MM/YYYY", true);

      if (!chequeDate.isValid()) {
        $row.find(".realize_date").val("").trigger("change");
        return;
      }

      // Realization date = cheque date + 2 WORKING days
      const realizeDate = addWorkingDays(chequeDate, 2);

      // set and trigger change so your other listeners run
      $row.find(".realize_date")
        .val(realizeDate.format("DD/MM/YYYY"))
        .trigger("change"); // triggers your calculateChequeRow listener
    });


    function addWorkingDays(startMoment, daysToAdd) {
      let d = startMoment.clone();
      let added = 0;

      // If start date itself is weekend/holiday, move to next working day
      while (d.day() === 0 || d.day() === 6 || holidays.includes(d.format("DD/MM/YYYY"))) {
        d.add(1, 'days');
      }

      // Now start counting working days
      while (added < daysToAdd) {
        d.add(1, 'days'); // move to next day
        const fmt = d.format("DD/MM/YYYY");
        const dow = d.day();
        if (dow === 0 || dow === 6 || holidays.includes(fmt)) continue; // skip non-working day
        added++;
      }

      return d;
    }




    $(document).on("change", "input[name='loan_type']", function() {
      let selectedType = $(this).val(); // remember which was selected
      resetLoanForm();
      // restore the selected radio after reset
      $("input[name='loan_type'][value='" + selectedType + "']").prop("checked", true);
    });

    function resetLoanForm() {
      // reset the main form (except loan_type)
      $("#loan_item_save")[0].reset();

      // clear hidden fields
      $("#loan_id, #loan_ref, #loan_payable_total_amount, #total_interest, #term_intrerest").val("");

      // clear select2 customers
      $(".js-data-cus_id-ajax, .js-data-g_cus_id-ajax").val(null).trigger("change");

      // clear cheque table
      $("#cheque_table tbody").empty();
      $("#cheque_section").hide();

      // clear summary text
      $("#payable_total_amount_txt, #no_of_terms_txt, #payable_term_amount_txt, #total_charges_txt, #pay_amount_txt, #days_txt, #loan_date_txt, #realization_date_txt").html("");

      // clear dates
      $("#loan_end_date, #loan_no_of_days").val("");

      // enable buttons again
      $("#loan_inv_hdr, #loan_inv_hdr_update").prop("disabled", false).val("Proceed");
    }


    jQuery(document).ready(function() {

      // Cheque & Realization Dates
      $(document).on("focus", ".cheque_date, .realize_date", function() {
        $(this).datepicker({
          format: "dd/mm/yyyy",
          autoclose: true,
          todayHighlight: true
        });
      });

      $("#loan_payment_term").on("change", function() {
        if ($(this).val() === "4") { // assuming 4 = CHEQUE
          $("#cheque_section").show();
          $("#no_of_terms_txt_p").hide();
          $("#days_txt_p").hide();
          $("#loan_date_txt_p").hide();
          $("#realization_date_txt_p").hide();
          calculate_payble_abount();
        } else {
          $("#cheque_section").hide();
          $("#cheque_table tbody").empty(); // clear if not cheque
          calculate_payble_abount();
          $("#no_of_terms_txt_p").show();
          $("#days_txt_p").show();
          $("#loan_date_txt_p").show();
          $("#realization_date_txt_p").show();
        }
      });

      let chequeRowIndex = 0;

      $("#add_cheque_row").click(function() {
        chequeRowIndex++;
        let row = `
    <tr>
      <td>
        <input type="text" name="cheques[${chequeRowIndex}][cheque_date]" 
               class="form-control cheque_date" placeholder="dd/mm/yyyy" autocomplete="off" required>
      </td>
      <td>
        <input type="text" name="cheques[${chequeRowIndex}][realize_date]" 
               class="form-control realize_date" placeholder="dd/mm/yyyy" autocomplete="off" required>
      </td>
      <td>
        <input type="number" step="0.01" name="cheques[${chequeRowIndex}][cheque_amount]" 
               class="form-control cheque_amount" required>
      </td>
      
      <!-- Bank -->
        <td>
            <select name="cheques[${chequeRowIndex}][bank_id]"
                    class="form-control bank_select search-select"
                    required>
                <option value="">Select Bank</option>
                <?php foreach ($banks as $bank) { ?>
                    <option value="<?= $bank->bank_id ?>">
                        <?= $bank->bank_name ?>
                    </option>
                <?php } ?>
            </select>
        </td>

        <!-- Branch -->
        <td>
            <select name="cheques[${chequeRowIndex}][branch_id]"
                    class="form-control branch_select"
                    required>
                <option value="">Select Branch</option>
            </select>
        </td>
      <td>
        <input type="text" name="cheques[${chequeRowIndex}][days]" 
               class="form-control days" readonly>
      </td>
      <td>
        <input type="text" name="cheques[${chequeRowIndex}][charges]" 
               class="form-control charges" readonly>
      </td>
      <td>
        <button type="button" class="btn btn-danger btn-sm remove-cheque">
          <i class="fa fa-trash"></i>
        </button>
      </td>
    </tr>
  `;
        $("#cheque_table tbody").append(row);
        
        // Initialize Select2 on the newly added row's selects
        let $newRow = $("#cheque_table tbody tr:last");

        $newRow.find(".bank_select.search-select").select2({
          placeholder: "Select Bank",
          allowClear: true
        });

        $newRow.find(".branch_select.search-select").select2({
          placeholder: "Select Branch",
          allowClear: true
        });

      });





      // remove row
      $(document).on("click", ".remove-cheque", function() {
        $(this).closest("tr").remove();
      });


      // recalc whenever cheque amount, realization date or loan interest changes
      $(document).on("keyup change input", ".cheque_amount, .realize_date, #loan_interest", function() {
        let row = $(this).closest("tr");

        calculateChequeRow(row);
      });


      $("#loan_no_of_terms").on("input", function() {
        var loan_date = $("#loan_date").val();
        var no_of_terms = $(this).val();
        var loan_payment_term = $('#loan_payment_term').val();

        if (loan_date !== "" && no_of_terms !== "") {
          $.post("<?php echo base_url('loan/get_end_date'); ?>", {
            loan_date: loan_date,
            loan_payment_term: loan_payment_term,
            no_of_terms: no_of_terms
          }, function(response) {
            var obj = JSON.parse(response);
            $("#loan_end_date").val(obj.end_date);
            $("#loan_no_of_days").val(obj.days_count);
            $("#realization_date_txt").html(obj.end_date);
            $("#loan_date_txt").html(loan_date);
            $("#days_txt").html(obj.days_count);
          });
        }
      });

      $("#loan_date").on("change", function() {
        var loan_date = $(this).val();
        var no_of_terms = $('#loan_no_of_terms').val();
        var loan_payment_term = $('#loan_payment_term').val();

        if (loan_date !== "" && no_of_terms !== "") {
          $.post("<?php echo base_url('loan/get_end_date'); ?>", {
            loan_date: loan_date,
            loan_payment_term: loan_payment_term,
            no_of_terms: no_of_terms
          }, function(response) {
            var obj = JSON.parse(response);
            $("#loan_end_date").val(obj.end_date);
            $("#loan_no_of_days").val(obj.days_count);
            $("#realization_date_txt").html(obj.end_date);
            $("#loan_date_txt").html(loan_date);
            $("#days_txt").html(obj.days_count);
          });
        }
        if (loan_date !== "") {
          $("#loan_date_txt").html(loan_date);
        }

      });


      calculate_payble_abount();
      calculateExtraItemTotal();
      $("#loan_payment_term").on("change", function() {
        if ($(this).val() === "4") {
          $("#cheque_p_day_div").show();
          calculate_payble_abount();
        } else {
          $("#cheque_p_day_div").hide();
          calculate_payble_abount();
        }
      });
    });

    function calculate_payble_abount() {

      var loan_tot_amount = parseFloat($('#loan_tot_amount').val());
      var loan_interest = parseFloat($('#loan_interest').val());
      var loan_no_of_terms = parseFloat($('#loan_no_of_terms').val()); //no of months or days
      var loan_payment_term = parseFloat($('#loan_payment_term').val());
      var loan_payment_term_day = parseFloat($('#loan_payment_term_qty').val());
      var loan_type = $("input[name='loan_type']:checked").val();
      var loan_no_of_days = parseFloat($('#loan_no_of_days').val());

      if (!$.isNumeric(loan_tot_amount)) loan_tot_amount = 0;
      if (!$.isNumeric(loan_interest)) loan_interest = 0;
      if (!$.isNumeric(loan_no_of_terms)) loan_no_of_terms = 0;

      var payable_total_amount = 0;
      var payable_term_amount = 0;
      var total_interest = 0;
      var term_interest = 0;
      var no_of_terms = loan_no_of_days;


      // 🔹 Passive Loan Calculation
      if (loan_type === "Passive") {
        no_of_terms = loan_no_of_terms;

        term_interest = loan_tot_amount / loan_no_of_terms;
        total_interest = (loan_tot_amount * loan_interest) / 100;

        // round term interest to 2 decimals
        term_interest = parseFloat(term_interest.toFixed(2));


        // Payable per term = Divide total payable by no of terms
        payable_term_amount = ((loan_tot_amount * (loan_interest / 100)) / 30) * loan_no_of_days;

        // Special adjustment rule (25 -> 1, 50 -> 2, 75 -> 3...)
        var multiplier = Math.ceil(loan_no_of_terms / 25);
        total_interest = ((loan_tot_amount * loan_interest) / 100) * multiplier;
        // Payable total = Amount - Total Charges
        payable_total_amount = loan_tot_amount - payable_term_amount;

        if (loan_payment_term == 4) {
          let totalAmount = 0;
          let totalCharges = 0;
          let noOfTerms = 0;

          $("#cheque_table tbody tr").each(function() {
            let amount = parseFloat($(this).find(".cheque_amount").val()) || 0;
            let charge = parseFloat($(this).find(".charges").val()) || 0;

            if (amount > 0) {
              totalAmount += amount;
              totalCharges += charge;
              noOfTerms++;
            }
          });
          // assign to your variables
          payable_total_amount = totalAmount - totalCharges;
          payable_term_amount = totalCharges;
          total_interest = totalCharges;
          term_interest = (noOfTerms > 0 ? totalCharges / noOfTerms : 0);
          no_of_terms = noOfTerms;
          loan_tot_amount = totalAmount;
          $('#loan_tot_amount').val(loan_tot_amount);
          $('#loan_no_of_terms').val(no_of_terms);
        }

      } else {
        // 🔹 Normal Loan (your existing conditions)
        if (loan_payment_term == 1) {
          var int_pre = (loan_interest / 100);
          var one_day_int_pre = (int_pre / 30);
          var total_interest_value = (one_day_int_pre * loan_tot_amount) * loan_no_of_terms;
          payable_total_amount = total_interest_value + loan_tot_amount;
          payable_term_amount = payable_total_amount / loan_no_of_terms;
          total_interest = total_interest_value;
          term_interest = total_interest / loan_no_of_terms;
        }

        if (loan_payment_term == 2) {
          var term_in_month_original = (loan_no_of_terms / 4).toFixed(2);
          var term_in_month_rounded = Math.round(term_in_month_original);
          var diff = term_in_month_original - term_in_month_rounded;
          if (diff > 0) {
            term_in_month_rounded = term_in_month_rounded + 1;
          }
          term_interest = (loan_tot_amount * loan_interest) / 100;
          term_interest = term_interest / loan_no_of_terms;
          total_interest = ((loan_tot_amount * loan_interest) / 100) * term_in_month_rounded;
          payable_total_amount = total_interest + loan_tot_amount;
          payable_term_amount = (payable_total_amount / loan_no_of_terms).toFixed(2);
        }

        if (loan_payment_term == 3) {
          term_interest = (loan_tot_amount * loan_interest) / 100;
          term_interest = term_interest / loan_no_of_terms;
          total_interest = ((loan_tot_amount * loan_interest) / 100) * loan_no_of_terms;
          payable_total_amount = total_interest + loan_tot_amount;
          payable_term_amount = (payable_total_amount / loan_no_of_terms).toFixed(2);
        }

        if (loan_payment_term == 4) {

          var int_pre = (loan_interest / 100);
          var one_day_int_pre = (int_pre / 30);
          var total_interest_value = (one_day_int_pre * loan_tot_amount) * loan_no_of_terms;
          payable_total_amount = total_interest_value + loan_tot_amount;
          payable_term_amount = payable_total_amount / loan_no_of_terms;
          total_interest = total_interest_value;

        }
      }


      // 🔹 Update UI
      if ($.isNumeric(payable_total_amount)) {
        $('#payable_total_amount_txt').text(loan_tot_amount.toFixed(2));
        $('#pay_amount_txt').text(formatDecimal(payable_total_amount));
        $('#loan_payable_total_amount').val(payable_total_amount);
      }
      if ($.isNumeric(no_of_terms)) {
        $('#no_of_terms_txt').text(no_of_terms + " terms");
      }
      if ($.isNumeric(payable_term_amount)) {
        $('#payable_term_amount_txt').text(formatDecimal(payable_term_amount));
        document.getElementById('loan_term_amount').value = formatDecimal(term_interest);
      }
      if ($.isNumeric(payable_term_amount)) {
        $('#total_charges_txt').html(formatDecimal(payable_term_amount));
      }
      if ($.isNumeric(term_interest)) {
        $('#term_intrerest').val(formatDecimal(term_interest));
      }
    }

    function formatDecimal(number, decimals = 2) {
      number = parseFloat(number);
      if (isNaN(number)) return (0).toFixed(decimals);

      return number
        .toFixed(decimals) // round to decimals
        .replace(/\B(?=(\d{3})+(?!\d))/g, ","); // add commas
    }


    function calculateChequeRow(row) {
      let loanDateStr = $("#loan_date").val();
      let interest = parseFloat($("#loan_interest").val()) || 0;

      let loanDate = moment(loanDateStr, "DD/MM/YYYY");
      let realizeDateStr = row.find(".realize_date").val();
      let amount = parseFloat(row.find(".cheque_amount").val()) || 0;
      //alert(amount);
      // --- Days = 30,60,90… rule ---
      let rowIndex = row.index(); // 0-based
      let days = 0;


      // --- weekend check ---
      if (realizeDateStr) {
        let realizeDate = moment(realizeDateStr, "DD/MM/YYYY");
        if (loanDate.isValid() && realizeDate.isValid()) {
          days = realizeDate.diff(loanDate, "days");
          if (days < 0) days = 0;
          if (days >= 27 && days < 31) {
            days = 30;
          }
        }
        let dayOfWeek = realizeDate.day();
        if (dayOfWeek === 0 || dayOfWeek === 6) {
          alert("Realization Date cannot be Saturday or Sunday!");
          row.find(".realize_date").val("");
          row.find(".charges").val("");
          return;
        }
      }

      row.find(".days").val(days);

      // --- charges calculation ---
      if (amount > 0 && interest > 0) {
        let charges = ((amount * (interest / 100)) / 30) * days;
        row.find(".charges").val(charges.toFixed(2));
      } else {
        row.find(".charges").val("0.00");
      }

      calculate_payble_abount();
    }





    function load_interest_rate(id) {
      var x = document.getElementById("loan_interest");
      x.remove(x.selectedIndex);
      $.post("<?php echo  base_url(); ?>loan/get_all_interest_by_payment_term_id?R=" + id, function(data) {
        var sel = $("#loan_interest");
        sel.empty();
        $("#loan_interest").append('<option value="" selected> - select interest -</option>');
        $.each(data, function(i, item) {
          $("#loan_interest").append('<option value="' + i + '">' + item + '</option>');
        })
      }, "json");
    }

    //save invoice header
    // save invoice header
    $("#loan_inv_hdr").click(function() {
      // Example: assuming you have select inputs for customer and guarantor
      var customerId = $("#cus_id").val();
      var guarantorId = $("#g_cus_id").val(); // check your field id, maybe `#guarantor_id`

      // Validate Customer vs Guarantor
      if (customerId && guarantorId && customerId === guarantorId) {
        bootbox.alert("Customer and Guarantor cannot be the same person!");
        return false; // stop form submission
      }

      $("#loan_inv_hdr").prop("disabled", true);
      $("#loan_inv_hdr").val("Please wait..");
      var fields = $("#loan_item_save").serialize();

      $.post("<?php echo base_url(); ?>loan/loan_header_save", fields)
        .done(function(data) {
          var obj = jQuery.parseJSON(data);
          if (obj.error == 0) {
            alert("Record successfully saved");
            if (obj.is_cheque_req == 1) {
              sendUrl =
                "<?php echo base_url(); ?>loan/add_cheque_for_loan/" +
                obj.loan_id;
            } else {
              sendUrl =
                "<?php echo base_url(); ?>loan/loan_details/" +
                obj.loan_id;
            }
            //window.location.href = sendUrl;
          }
          if (obj.error == 1) {
            $("#loan_inv_hdr").prop("disabled", false);
            $("#loan_inv_hdr").val("Next");
            bootbox.alert(obj.msg, function() {});
          }
        });
    });



    function load_customer_old_recod(cus_id) {
      $('#products_table').DataTable({
        "ajax": "<?php echo base_url('loan/get_list_loan_by_customer?cus_id=') ?>" + cus_id,
        "bDestroy": true,
        "iDisplayLength": 50,
        "order": [
          [0, "desc"]
        ]
      });

    } 

    //update invoice header
    $("#loan_inv_hdr_update").click(function() {
      $("#loan_inv_hdr").prop("disabled", true);
      $("#loan_inv_hdr").val('Please wait..');
      var fields = $("#loan_item_save").serialize();
      $.post("<?php echo base_url(); ?>loan/loan_header_update", fields)
        .done(function(data) {
          var obj = jQuery.parseJSON(data);
          if (obj.error == 0) {
            alert("Recode successfully saved");
            if (obj.is_cheque_req == 1) {
              sendUrl = '<?php echo base_url(); ?>loan/add_cheque_for_loan/' + obj.loan_id;
            } else {
              sendUrl = '<?php echo base_url(); ?>loan/loan_details/' + obj.loan_id;
            }
            window.location.href = sendUrl;
            //location.reload();
          }
          if (obj.error == 1) {
            $("#loan_inv_hdr").prop("disabled", false);
            $("#loan_inv_hdr").val('Next');
            bootbox.alert(obj.msg, function() {});
            $("#loan_inv_hdr").prop("disabled", false);
            $("#loan_inv_hdr").val('Next');
            //$table_name	
          }
        });
    });

    $("#reduce_from_cheque").click(function() {
      if (document.getElementById('reduce_from_cheque').checked) {
        // $("#cheque_p_day_div").hide();
        calculate_payble_abount();
      } else { //$("#cheque_p_day_div").show();
        calculate_payble_abount();
      }
    });


    //-----------------------------------------------------
    $(".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
      }
    });
    //-----------------------------------------------------	

    //-----------------------------------------------------




    $(".js-data-g_cus_id-ajax").select2({
      ajax: {
        url: "<?php echo base_url('customers/filter_guarantor') ?>",
        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.name + "  (" + item.phone + ")";
              return {
                text: text1,
                slug: item.name,
                id: item.id
              };
            })
          };
        },
        cache: true
      }
    });
    //-----------------------------------------------------	
    function test() {



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

</html>