<!DOCTYPE html>
<html>

<head>
  <!-- TABLES CSS CODE -->
  <?php include "comman/code_css_form.php"; ?>
  <!-- </copy> -->
</head>

<body class="hold-transition skin-blue sidebar-mini">
  <div class="wrapper">

    <?php include "sidebar.php"; ?>
    <?php
    if (!isset($loan_authority)) {
      $loan_authority = $account = $loan_reason = $referance = $loan_type = $amount = $interest = $payment_type = $duration = $per_month = $payable_amount = $statuss = $notes = $date = $q_idd = "";
    }

    ?>

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
      <!-- Content Header (Page header) -->
      <section class="content-header">
        <h1>
          <?= $page_title; ?>
          <small>Add/Update Loan</small>
        </h1>
        <ol class="breadcrumb">
          <li><a href="<?php echo $base_url; ?>dashboard"><i class="fa fa-dashboard"></i> Home</a></li>
          <li><a href="<?php echo $base_url; ?>loan\/view">Loan List</a></li>
          <li class="active"><?= $page_title; ?></li>
        </ol>
      </section>

      <!-- Main content -->
      <section class="content">
        <div class="row">
          <!-- right column -->
          <div class="col-md-3">
            <?php require_once 'sub_sidemenu_management.php'; ?>
          </div> 
          <div class="col-md-9">
            <!-- Horizontal Form -->
            <div class="box box-info ">
              <div class="box-header with-border">
                <h3 class="box-title">Please Enter Valid Data</h3>
              </div>
              <!-- /.box-header -->
              <!-- form start -->
              <form id="loan-form">
                <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
                <input type="hidden" id="base_url" value="<?php echo $base_url;; ?>">
                <div class="box-body">
                  <?php
                  $query = $this->db->get('db_authority');
                  $loan_authorities =  $query->result();
                  ?>
                  <div class="col-sm-6">
                    <label for="loan_authority" class="control-label">Loan Authority</label>
                    <div class="form-group">
                      <select name="loan_authority" class="form-control" id="loan_authority">
                        <option selected disabled>--select loan authority--</option>
                        <?php
                        foreach ($loan_authorities as $loanAuthority) {
                        ?>
                          <option value="<?= $loanAuthority->id ?>" <?= ($loan_authority == $loanAuthority->id) ? 'selected' : '' ?>><?= $loanAuthority->authority_name ?></option>
                        <?php
                        }
                        ?>
                      </select>
                      <span id="loan_authority_msg" style="display:none" class="text-danger"></span>
                    </div>
                  </div>
                  <?php
                  $query = $this->db->get('db_account');
                  $accounts =  $query->result();
                  ?>
                  <div class="col-sm-6">
                    <label for="account" class="control-label">Account</label>
                    <div class="form-group">
                      <select name="account" class="form-control" id="account">
                        <option selected disabled>--select loan account--</option>
                        <?php
                        foreach ($accounts as $Acc) {
                        ?>
                          <option value="<?= $Acc->id ?>" <?= ($account == $Acc->id) ? 'selected' : '' ?>><?= $Acc->bank_name ?></option>
                        <?php
                        }
                        ?>
                      </select>
                      <span id="account_msg" style="display:none" class="text-danger"></span>
                    </div>
                  </div>
                  <div class="col-sm-6">
                    <label for="loan_reason" class="control-label">Loan Reason<label class="text-danger">*</label></label>
                    <div class="form-group">
                      <input type="text" class="form-control" id="loan_reason" name="loan_reason" placeholder="Account number here.." value="<?= $loan_reason ?>">
                      <span id="loan_reason_msg" style="display:none" class="text-danger"></span>
                    </div>
                  </div>
                  <div class="col-sm-6">
                    <label for="" class="control-label">referance<label class="text-danger">*</label></label>
                    <div class="form-group">
                      <input type="number" class="form-control" id="referance" name="referance" placeholder="Account number here.." value="<?= $referance ?>">
                      <span id="referance_msg" style="display:none" class="text-danger"></span>
                    </div>
                  </div>
                  <?php
                  $query = $this->db->get('db_suppliers');
                  $loadTypes =  $query->result();
                  ?>
                  <div class="col-sm-6">
                    <label for="loan_type" class="control-label">Loan Type</label>
                    <div class="form-group">
                      <select name="loan_type" class="form-control" id="loan_type">
                        <option selected disabled>--select loan account--</option>
                        <?php
                        foreach ($loadTypes as $load_Type) {
                        ?>
                          <option value="<?= $load_Type->id ?>" <?= ($loan_type == $load_Type->id) ? 'selected' : '' ?>><?= $load_Type->supplier_code ?></option>
                        <?php
                        }
                        ?>
                      </select>
                      <span id="loan_type_msg" style="display:none" class="text-danger"></span>
                    </div>
                  </div>

                  <div class="col-sm-6">
                    <label for="paymentType" class="control-label">Payment Type</label>
                    <div class="form-group">
                      <select name="payment_type" class="form-control" id="payment_type" onblur="calculatePayable()">
                        <option selected disabled>--select loan Payment Type--</option>
                        <option value="daily" <?= ($payment_type == 'daily') ? 'selected' : '' ?>>Daily</option>
                        <option value="monthly" <?= ($payment_type == 'monthly') ? 'selected' : '' ?>>Monthly</option>
                        <option value="yearly" <?= ($payment_type == 'yearly') ? 'selected' : '' ?>>Yearly</option>
                      </select>
                      <span id="payment_type_msg" style="display:none" class="text-danger"></span>
                    </div>
                  </div>
                  <div class="col-sm-6">
                    <label for="amount" class="control-label">Amount<label class="text-danger">*</label></label>
                    <div class="form-group">
                      <input type="number" class="form-control" id="amount" onblur="calculatePayable()" name="amount" placeholder="Account number here.." value="<?= $amount ?>">
                      <span id="amount_msg" style="display:none" class="text-danger"></span>
                    </div>
                  </div>
                  <div class="col-sm-6">
                    <label for="interest" class="control-label">Interest (%)<label class="text-danger">*</label></label>
                    <div class="form-group">
                      <input type="number" class="form-control" id="interest" onblur="calculatePayable()" name="interest" placeholder="Enter an interest rate in percentage.." value="<?= $interest ?>">
                      <span id="interest_msg" style="display:none" class="text-danger"></span>
                    </div>
                  </div>
                  <div class="col-sm-6">
                    <label for="duration" class="control-label">Duration<label class="text-danger">*</label></label>
                    <div class="form-group">
                      <input type="number" class="form-control" id="duration" name="duration" onblur="calculatePayable()" placeholder="Enter an duration rate in percentage.." value="<?= $duration ?>">
                      <span id="duration_msg" style="display:none" class="text-danger"></span>
                    </div>
                  </div>
                  <div class="col-sm-6">
                    <label for="per_month" class="control-label">Per Day<label class="text-danger">*</label></label>
                    <div class="form-group">
                      <input type="text" class="form-control" id="per_month" name="per_month" value="<?= $per_month ?>" disabled>
                      <span id="per_month_msg" style="display:none" class="text-danger"></span>
                    </div>
                  </div>
                  <div class="col-sm-3">
                    <label for="payable_amount" class="control-label">Payable Amount<label class="text-danger">*</label></label>
                    <div class="form-group">
                      <input type="text" class="form-control" id="payable_amount" name="payable_amount" value="<?= $payable_amount ?>" disabled>
                      <span id="payable_amount_msg" style="display:none" class="text-danger"></span>
                    </div>
                  </div>

                  <div class="col-sm-3">
                    <label for="date" class="control-label">Date</label>
                    <div class="form-group">
                      <div class="input-group date">
                        <div class="input-group-addon">
                          <i class="fa fa-calendar"></i>
                        </div>
                        <input type="text" class="form-control pull-right datepicker" id="date" name="date" value="<?= $date; ?>">
                      </div>
                    </div>
                  </div>
                  <div class="col-sm-6">
                    <div class="form-group">
                      <label for="status" class="control-label">Status </label>
                      <select name="status" class="form-control" id="status">
                        <option selected disabled>--select status--</option>
                        <option value="1" <?= ($statuss == '1' ? 'selected' : '') ?>>Active</option>
                        <option value="0" <?= ($statuss == '0' ? 'selected' : '') ?>>Inactive</option>
                      </select>
                      <span id="status_msg" style="display:none" class="text-danger"></span>
                    </div>
                  </div>
                  <div class="col-sm-12">
                    <div class="form-group">
                      <label for="note" class="control-label">Note</label>
                      <textarea type="text" class="form-control" id="note" name="note" rows="5" placeholder="Write your note here"><?= $notes ?></textarea>
                      <span id="note_msg" style="display:none" class="text-danger"></span>
                    </div>
                  </div>
                </div>
                <!-- /.box-footer -->
                <div class="box-footer">
                  <div class="col-sm-8 col-sm-offset-2 text-center">
                    <!-- <div class="col-sm-4"></div> -->
                    <?php
                    if ($loan_authority != "") {
                      $btn_name = "Update";
                      $btn_id = "update";
                    ?>
                      <input type="hidden" name="q_id" id="q_id" value="<?php echo $q_idd; ?>" />
                    <?php
                    } else {
                      $btn_name = "Save";
                      $btn_id = "save";
                    }

                    ?>

                    <div class="col-md-3 col-md-offset-3">
                      <button type="button" id="<?php echo $btn_id; ?>" class=" btn btn-block btn-success" title="Save Data"><?php echo $btn_name; ?></button>
                    </div>
                    <div class="col-sm-3">
                      <a href="<?= base_url('dashboard'); ?>">
                        <button type="button" class="col-sm-3 btn btn-block btn-warning close_btn" title="Go Dashboard">Close</button>
                      </a>
                    </div>
                  </div>
                </div>
                <!-- /.box-footer -->
              </form>
            </div>
            <!-- /.box -->

          </div>
          <!--/.col (right) -->
        </div>
        <!-- /.row -->

      </section>
      <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->

    <?php include "footer.php"; ?>


    <!-- Add the sidebar's background. This div must be placed
       immediately after the control sidebar -->
    <div class="control-sidebar-bg"></div>
  </div>
  <!-- ./wrapper -->
  <!-- SOUND CODE -->
  <?php include "comman/code_js_sound.php"; ?>
  <!-- TABLES CODE -->
  <?php include "comman/code_js_form.php"; ?>

  <script src="<?php echo $theme_link; ?>js/loan.js"></script>
  <!-- Make sidebar menu hughlighter/selector -->
  <script>
    $(".<?php echo basename(__FILE__, '.php'); ?>-active-li").addClass("active");
  </script>
  <script>
    function calculatePayable() {
      // Get input values
      let amount = Number(document.getElementById('amount').value);
      let interest = Number(document.getElementById('interest').value);
      let duration = Number(document.getElementById('duration').value);
      let paymentType = document.getElementById('payment_type').value;
      let perMonthField = document.getElementById('per_month');
      let payableAmountField = document.getElementById('payable_amount');

      console.log("Amount:", amount);
      console.log("Interest:", interest);
      console.log("Duration:", duration);
      console.log("Payment Type:", paymentType);

      // Calculate payable amount based on input values
      let totalInterestAmount = 0;
      let monthlyPayment = 0;
      let interestRate = interest / 100;
      let numOfYears = 0;
      if (interest && duration) {
        if (paymentType === 'daily') {
          numOfYears = duration / 365;
          // Disable per_month and payable_amount fields
          perMonthField.disabled = true;
          payableAmountField.disabled = true;
        } else {
          numOfYears = duration;
          // Enable per_month and payable_amount fields
          perMonthField.disabled = true;
          payableAmountField.disabled = true;
        }
        // Calculation for non-daily payment types
        monthlyPayment = Number((((interestRate / 12) * amount) / (1 - Math.pow(1 + interestRate / 12, numOfYears * -12))).toFixed(2));
        totalInterestAmount = Number((monthlyPayment * (numOfYears * 12) - amount).toFixed(2));
        let payableAmount = Number((amount + totalInterestAmount).toFixed(2));

        // Update the payable amount field
        payableAmountField.value = payableAmount;

        // Calculate per-month payment if payment type is not daily
        // if (paymentType !== 'daily') {
          let perMonth = Number((payableAmount / (numOfYears * 12)).toFixed(2));
          perMonthField.value = perMonth;
          console.log("Per Day Payment:", perMonth); // Updated log message
        // } else {
        //   perMonthField.value = ''; // Clear the value if payment type is daily
        // }

        console.log("Monthly Payment:", monthlyPayment);
        console.log("Total Interest Amount:", totalInterestAmount);
        console.log("Payable Amount:", payableAmount);
      }
    }

    // Call calculatePayable() function whenever payment type changes
    document.getElementById('payment_type').addEventListener('change', calculatePayable);

    // Call calculatePayable() once initially
    calculatePayable();
  </script>

</body>

</html>