<?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">
<!-- SweetAlert2 CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.12/dist/sweetalert2.min.css">
<style>
  .inline-error-message {
    display: none;
    color: #dc3545;
    font-size: 12px;
    margin-top: 6px;
    padding: 8px 10px 8px 28px;
    background-color: #f8d7da;
    border: 1.5px solid #f5c6cb;
    border-left: 4px solid #dc3545;
    border-radius: 3px;
    font-weight: 500;
    position: relative;
    box-shadow: 0 2px 4px rgba(220, 53, 69, 0.15);
  }
  
  .inline-error-message::before {
    content: "⚠";
    position: absolute;
    left: 8px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 14px;
    color: #dc3545;
    font-weight: bold;
  }
  
  .form-control.is-invalid {
    border-color: #dc3545 !important;
    border-width: 1.5px !important;
    box-shadow: 0 0 0 0.3rem rgba(220, 53, 69, 0.25) !important;
    background-color: #fff5f7 !important;
  }
  
  .form-group-styled.error-focused {
    background-color: #fffbfc;
    padding: 10px;
    border-radius: 4px;
    border-left: 3px solid #dc3545;
  }
  
  @keyframes pulse-error {
    0%, 100% {
      box-shadow: 0 0 0 0.3rem rgba(220, 53, 69, 0.25);
    }
    50% {
      box-shadow: 0 0 0 0.6rem rgba(220, 53, 69, 0.35);
    }
  }
</style>

<!-- 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="col-md-12">
                    <div class="row">
                      <div class="col-md-12">
                        <div class="form-group form-group-styled">
                          <label><i class="fa fa-list-alt" style="color: #0275d8; margin-right: 5px;"></i> Select 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 ] ';
                              }
                              $select = (isset($loan_id) && $loan_id == $row['loan_id']) ? 'selected' : '';
                            ?>
                              <option <?= $select; ?> 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="row">
                      <div class="col-md-12">

                        <table class="table table-bordered table-condensed table-hover table-striped dataTable" id="">
                          <thead>
                          </thead>
                          <tbody>

                            <tr>
                              <td width="25%"><strong>Loan Type </strong></td>
                              <td></td>
                            </tr>
                            <tr>
                              <td width="25%"><strong>Payment Term </strong></td>
                              <td></td>
                            </tr>
                            <tr>
                              <td><strong>Loan Date</strong></td>
                              <td></td>
                            </tr>
                            <tr>
                              <td><strong>Route </strong></td>
                              <td></td>
                            </tr>
                            <tr>
                              <td><strong>Customer </strong></td>
                              <td></td>
                            </tr>
                            <tr>
                              <td><strong>Garenter </strong></td>
                              <td></td>
                            </tr>
                            <tr>
                              <td><strong>Interest (%) </strong></td>
                              <td></td>
                            </tr>
                            <tr>
                              <td><strong>No. of Term </strong></td>
                              <td></td>
                            </tr>
                            <tr>
                              <td><strong>Realization Date </strong></td>
                              <td></td>
                            </tr>
                            <tr>
                              <td><strong>Days </strong></td>
                              <td></td>
                            </tr>
                            <tr>
                              <td><strong>Total Amount </strong></td>
                              <td></td>
                            </tr>
                            <tr>
                              <td>&nbsp;</td>
                              <td></td>
                            </tr>


                            <tr>
                              <td><strong>Reschedule Terms </strong></td>
                              <td>
                                <div class="col-md-4">
                                  <div class="form-group form-group-styled">
                                    <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 class="inline-error-message" id="loan_no_of_terms_error"></div>
                                  </div>
                                </div>
                              </td>
                            </tr>
                            <tr>
                              <td><strong>Reschedule Interest (%.)</strong></td>
                              <td>

                                <div class="col-md-4">
                                  <div class="form-group form-group-styled">
                                    <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 class="inline-error-message" id="loan_interest_error"></div>
                                  </div>
                                </div>
                              </td>
                            </tr>

                            <tr>
                              <td><strong>Arrears Terms </strong></td>
                              <td></td>
                            </tr>

                            <tr>
                              <td><strong>Total Outstanding </strong>
                                <input type="hidden" name="total_outstanding" id="total_outstanding" value="0" />
                              </td>
                              <td></td>
                            </tr>
                            <tr>
                              <td><strong>Delay Charge </strong>
                                <input type="hidden" name="delay_charge" id="delay_charge" value="0" />
                              </td>
                              <td></td>
                            </tr>
                            <tr>
                              <td><strong>Total Interest Charges </strong></td>
                              <td><span id="total_interest_charges_txt"></span> <input type="hidden" name="total_interest_charges" id="total_interest_charges" value="0" /></td>
                            </tr>
                            <tr>
                              <td><strong>Reschedule Amount </strong></td>
                              <td id="reschedule_amount"></td>
                            </tr>
                          </tbody>
                        </table>
                      </div>
                    </div>

                    <div class="row">
                      <div class="col-md-12">
                        <div class="form-group">
                          <div class="alert alert-info" style="padding: 10px 15px; margin-bottom: 15px; border-radius: 4px;">
                            <label style="margin-bottom: 0; cursor: pointer; font-size: 14px; font-weight: 500;">
                              <input type="checkbox" id="enable_total_amount" name="enable_total_amount" style="margin-right: 8px; cursor: pointer;"> 
                              <i class="fa fa-edit" style="color: #0275d8;"></i>
                              <span style="color: #004085; vertical-align: middle;">Allow Total Amount Edit</span>
                            </label>
                          </div>
                        </div>
                      </div>

                      <br /><br />
                      <input id="loan_date" type="hidden" name="loan_date">
                      <input id="loan_payment_term" type="hidden" name="loan_payment_term">
                      <input id="loan_type" type="hidden" name="loan_type">
                      <div class="col-md-3">
                        <div class="form-group form-group-styled">
                          <label for="loan_tot_amount">Total Amount *</label>
                          <input style="text-align:right;" type="number" readonly id="loan_tot_amount" name="loan_tot_amount" class="form-control" value="" data-d-group="2" onChange="calculate_payble_abount()">
                          <div class="inline-error-message" id="loan_tot_amount_error"></div>
                        </div>
                      </div>

                      <div class="col-md-2">
                        <div class="form-group form-group-styled">
                          <label for="loan_term_amount"><i class="fa fa-calendar" style="color: #0275d8; margin-right: 5px;"></i>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 form-group-styled">
                          <label for="loan_term_amount"><i class="fa fa-clock-o" style="color: #0275d8; margin-right: 5px;"></i>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 class="col-md-3">
                        <div class="form-group form-group-styled">
                          <label for="loan_term_amount"><i class="fa fa-calculator" style="color: #0275d8; margin-right: 5px;"></i>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>

                  </div>










                  <div class="col-md-12" 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>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="col-md-12" 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="col-md-12" style="margin-right:2%;">
                    <br>
                  </div>

                  <div class="col-md-6" style="margin-right:2%; display:none;">
                    <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> 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> Days : <span id="days_txt"> </span> </p>
                          <p> Loan Date : <span id="loan_date_txt"> </span> </p>
                          <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"> Reschedule <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_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>
        </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>
  <!-- SweetAlert2 JS -->
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.12/dist/sweetalert2.all.min.js"></script>

  <!-- end: JAVASCRIPTS REQUIRED FOR THIS PAGE ONLY -->
  <script>
    $(document).ready(function() {
      // Toggle Total Amount readonly based on checkbox
      $("#enable_total_amount").on("change", function() {
        if ($(this).is(":checked")) {
          $("#loan_tot_amount").removeAttr("readonly");
        } else {
          $("#loan_tot_amount").attr("readonly", "readonly");
        }
      });

      $("#loan_id").on("change", function() {
        var loanId = $(this).val();

        if (loanId) {
          $.ajax({
            url: "<?php echo base_url('loan/get_loan_details_by_id'); ?>",
            type: "GET",
            data: {
              loan_id: loanId
            },
            dataType: "json",
            success: function(data) {
              if (data) {
                // Fill table rows
                $("td:contains('Loan Type')").next().text(data.loan_type || "");
                $("#loan_type").val(data.loan_type || "");
                $("td:contains('Loan Date')").next().text(data.loan_date || "");
                $("#loan_date").val(data.loan_date);
                $("#loan_payment_term").val(data.loan_payment_term);
                $("#loan_interest").val(data.loan_interest);
                $("td:contains('Payment Term')").next().text(data.payment_term_name || "");
                $("td:contains('Route')").next().text(data.route_name || "");
                $("td:contains('Customer')").next().text(data.cus_name || "");
                $("td:contains('Garenter')").next().text(data.gar_name || "");
                $("td:contains('Interest (%)')").next().text(data.loan_interest || "");
                $("td:contains('No. of Term')").next().text(data.loan_no_of_terms || "");
                $("td:contains('Realization Date')").next().text(data.loan_end_date || "");
                $("td:contains('Days')").next().text(data.loan_no_of_days || "");
                $("td:contains('Total Amount')").next().text(data.loan_tot_amount || "");
                $("td:contains('Arrears Terms')").next().text(data.arrears_terms || "");
                $("td:contains('Total Outstanding')").next().text(data.outstanding.toFixed(2) || "");

                $("td:contains('Delay Charge')").next().text(data.delay_charge || "");
                $("#delay_charge").val(data.delay_charge || 0);
                $("td:contains('Reschedule Amount')").next().text(data.reschedule_amount || "");
                $("#total_outstanding").val(data.outstanding || 0);

                // Fill input fields
                $("#loan_tot_amount").val(data.reschedule_amount);
                //$("#loan_no_of_terms").val(data.loan_no_of_terms);
                $("#loan_end_date").val(data.loan_end_date);
                $("#loan_no_of_days").val(data.loan_no_of_days);
                //$("#loan_term_amount").val(data.loan_term_amount);

                // Summary section
                $("#payable_total_amount_txt").text(data.loan_tot_amount);
                $("#no_of_terms_txt").text(data.loan_no_of_terms);
                $("#payable_term_amount_txt").text(data.loan_term_amount);
                $("#days_txt").text(data.loan_no_of_days);
                $("#loan_date_txt").text(data.loan_date);
                $("#realization_date_txt").text(data.loan_end_date);
              }
            }
          });
        }
      });
    });
  </script>

  <script>
    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();
        }
      });


      function calculateLoanDates() {
        var today = new Date();
        var loan_date = today.toISOString().split("T")[0]; // current date
        var no_of_terms = $("#loan_no_of_terms").val();
        var total_outstanding = parseFloat($("#total_outstanding").val()) || 0;
        var delay_charge = parseFloat($("#delay_charge").val()) || 0;
        var loan_interest = parseFloat($("#loan_interest").val()) || 0;
        var loan_payment_term = parseFloat($("#loan_payment_term").val()) || 1;

        if (loan_date !== "" && no_of_terms !== "") {
          $.post("<?php echo base_url('loan/get_reschedule_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);
            var loan_no_of_days = parseFloat(obj.days_count) || 0;

            // Update UI with end date & days
            $("#loan_end_date").val(obj.end_date);
            $("#loan_no_of_days").val(loan_no_of_days);
            $("#realization_date_txt").html(obj.end_date);
            $("#loan_date_txt").html(loan_date);
            $("#days_txt").html(loan_no_of_days);

            // === Calculate Interest Charges ===
            var total_interest_charges = ((total_outstanding * loan_interest / 100) / 30) * loan_no_of_days;
            total_interest_charges = total_interest_charges.toFixed(2);

            $("#total_interest_charges").val(total_interest_charges);
            $("#total_interest_charges_txt").html(total_interest_charges);

            // === Calculate Total Amount ===
            var total_amount = total_outstanding + delay_charge + parseFloat(total_interest_charges);
            total_amount = total_amount.toFixed(2);

            $("#loan_tot_amount").val(total_amount);

            // === Calculate Term Amount ===
            var term_amount = (total_amount / no_of_terms).toFixed(2);
            $("#loan_term_amount").val(term_amount);
            $("#reschedule_amount").html(total_amount);
          });
        }
      }

      // Trigger on terms or interest change
      $("#loan_no_of_terms, #loan_interest").on("input", calculateLoanDates);




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


        if (loan_date !== "" && no_of_terms !== "") {
          $.post("<?php echo base_url('loan/get_reschedule_end_date'); ?>", {
            loan_date: loan_date,
            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_terms;


      // 🔹 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;
        payable_total_amount = loan_tot_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 = loan_tot_amount / 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 = loan_tot_amount / 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 = loan_tot_amount / 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 = term_interest.toFixed(2);
      }
      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) {
          Swal.fire({
            icon: 'warning',
            title: 'Invalid Date',
            text: '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");
    }

    // Scroll to first error field
    function scrollToFirstError() {
      var firstError = $('.is-invalid').first();
      if (firstError.length) {
        $('html, body').animate({
          scrollTop: firstError.offset().top - 120
        }, 400, 'swing', function() {
          // Add focus highlight after scrolling
          firstError.focus();
          firstError.css('outline', '2px solid #dc3545');
          setTimeout(function() {
            firstError.css('outline', 'none');
          }, 2000);
        });
      }
    }

    // Clear inline error messages
    function clearInlineErrors() {
      $('#loan_no_of_terms').removeClass('is-invalid').closest('.form-group-styled').removeClass('error-focused');
      $('#loan_no_of_terms_error').hide().text('');
      
      $('#loan_interest').removeClass('is-invalid').closest('.form-group-styled').removeClass('error-focused');
      $('#loan_interest_error').hide().text('');
      
      $('#loan_tot_amount').removeClass('is-invalid').closest('.form-group-styled').removeClass('error-focused');
      $('#loan_tot_amount_error').hide().text('');
    }

    // Show inline error message
    function showInlineError(fieldId, errorMessage) {
      var $field = $('#' + fieldId);
      var $errorDiv = $('#' + fieldId + '_error');
      var $formGroup = $field.closest('.form-group-styled');
      
      $field.addClass('is-invalid').focus();
      $formGroup.addClass('error-focused');
      $errorDiv.text(errorMessage).show();
      
      // Add pulse animation
      $field.css('animation', 'pulse-error 0.6s ease-in-out');
      setTimeout(function() {
        $field.css('animation', 'none');
      }, 600);
    }

    // Validation function for reschedule form
    function validateRescheduleForm() {
      clearInlineErrors();
      
      var loanId = $("#loan_id").val();
      var loanNoOfTerms = $("#loan_no_of_terms").val();
      var loanInterest = $("#loan_interest").val();
      var loanTotalAmount = $("#loan_tot_amount").val();
      var hasErrors = false;

      // Validate loan selection
      if (!loanId || loanId === "") {
        Swal.fire({
          icon: 'warning',
          title: 'Loan Required',
          text: 'Please select a loan to reschedule.'
        });
        return false;
      }

      // Validate Reschedule Terms
      if (!loanNoOfTerms || loanNoOfTerms === "" || isNaN(loanNoOfTerms) || parseFloat(loanNoOfTerms) <= 0) {
        showInlineError('loan_no_of_terms', 'Please enter a valid number of terms (must be greater than 0).');
        hasErrors = true;
      }

      // Validate Reschedule Interest (%)
      if (!loanInterest || loanInterest === "" || isNaN(loanInterest) || parseFloat(loanInterest) < 0) {
        showInlineError('loan_interest', 'Please enter a valid interest rate (must be >= 0).');
        hasErrors = true;
      }

      // Validate Total Amount
      if (!loanTotalAmount || loanTotalAmount === "" || isNaN(loanTotalAmount) || parseFloat(loanTotalAmount) <= 0) {
        showInlineError('loan_tot_amount', 'Please enter a valid total amount (must be greater than 0).');
        hasErrors = true;
      }

      if (hasErrors) {
        return false;
      }

      return true;
    }

    // Clear errors when user starts correcting fields
    $('#loan_no_of_terms').on('input', function() {
      if ($(this).val() !== '') {
        $(this).removeClass('is-invalid');
        $('#loan_no_of_terms_error').hide();
      }
    });

    $('#loan_interest').on('input', function() {
      if ($(this).val() !== '') {
        $(this).removeClass('is-invalid');
        $('#loan_interest_error').hide();
      }
    });

    $('#loan_tot_amount').on('input', function() {
      if ($(this).val() !== '') {
        $(this).removeClass('is-invalid');
        $('#loan_tot_amount_error').hide();
      }
    });

    //save invoice header
    $("#loan_inv_hdr").click(function() {
      // Validate form before submission
      if (!validateRescheduleForm()) {
        return false;
      }

      scrollToFirstError();
      
      $("#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_reschedule_save", fields)
        .done(function(data) {
          var obj = jQuery.parseJSON(data);

          if (obj.error == 0) {
            Swal.fire({
              icon: 'success',
              title: 'Success!',
              text: 'Loan successfully rescheduled.',
              confirmButtonColor: '#3085d6'
            });
            // Redirect to reschedule history or loan details
             window.location.href =
               "<?php echo base_url(); ?>loan/loan_details/" + obj.loan_id;
          }

          if (obj.error == 1) {
            $("#loan_inv_hdr").prop("disabled", false);
            $("#loan_inv_hdr").val("Reschedule");
            Swal.fire({
              icon: 'error',
              title: 'Error!',
              text: obj.msg,
              confirmButtonColor: '#d33'
            });
          }
        });
    });




    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) {
            Swal.fire({
              icon: 'success',
              title: 'Success!',
              text: 'Record successfully saved.',
              confirmButtonColor: '#3085d6'
            }).then(function() {
              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');
            Swal.fire({
              icon: 'error',
              title: 'Error!',
              text: obj.msg,
              confirmButtonColor: '#d33'
            });
          }
        });
    });

    $("#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.full_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_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
      }
    });
    //-----------------------------------------------------	
    function test() {



    }
  </script>

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

</html>