<?php
require 'functions.php';
checkLogin();
$db_link = connect();
getGroupID($db_link);
$timestamp = time();

// Get current group's details
$result_group = getGroup($db_link, $_SESSION['group_id']);

// NEW LOAN-Button
if (isset($_POST['newloan'])) {
  // Calculate new Loan Number
  $sql_loanno = "SELECT loan_id FROM group_loans WHERE group_id = '$_SESSION[group_id]'";
  $query_loanno = mysqli_query($db_link, $sql_loanno);
  checkSQL($db_link, $query_loanno);
  $numberofloans = mysqli_num_rows($query_loanno);
  $loan_no = 'L-' . $result_group['group_id'] . '-' . ($numberofloans + 1);

  // Sanitize user input
  $loan_date = strtotime(sanitize($db_link, $_POST['loan_date']));
  $loan_principal = sanitize($db_link, $_POST['loan_principal']);
  $loan_interest = sanitize($db_link, $_POST['loan_interest']);
  $loan_period = sanitize($db_link, $_POST['loan_period']);
  $loan_purpose = sanitize($db_link, $_POST['loan_purpose']);
  $lc1_name = sanitize($db_link, $_POST['lc1_name']);
  $lc1_address = sanitize($db_link, $_POST['lc1_address']);
  $lc1_contact = sanitize($db_link, $_POST['lc1_contact']);


  // Calculate expected total interest, monthly rates, and fees
  $loan_principaldue = round($loan_principal / $loan_period, -3);
  $loan_interesttotal = ceil((($loan_principal / 100 * $loan_interest) * $loan_period) / 50) * 50;
  $loan_interestdue = round($loan_principal / 100 * $loan_interest);
  $loan_repaytotal = $loan_principal + $loan_interesttotal;
  $loan_rate = $loan_principaldue + $loan_interestdue;

// Insert Loan into group_loans
$sql_insert_loan = "INSERT INTO group_loans (group_id, loan_no, loan_date, loan_principal, loan_interest, loan_period, loan_purpose, lc1_name, lc1_address, lc1_contact, loan_created, user_id) VALUES ('$_SESSION[group_id]', '$loan_no', '$loan_date', '$loan_principal', '$loan_interest', '$loan_period', '$loan_purpose', '$lc1_name', '$lc1_address', '$lc1_contact', $timestamp, '$_SESSION[log_id]')";
$query_insert_loan = mysqli_query($db_link, $sql_insert_loan);
if (!$query_insert_loan) {
  echo "Error: " . mysqli_error($db_link);
  exit; // Stop the script execution
} else {
  echo "Query executed successfully";
}

// Retrieve LOAN_ID of newly created loan from group_loans and pass to SESSION variable
$stmt = mysqli_prepare($db_link, "SELECT MAX(loan_id) as max_loan_id FROM group_loans WHERE group_id = ?");
mysqli_stmt_bind_param($stmt, "s", $_SESSION['group_id']);
mysqli_stmt_execute($stmt);
$query_newloanid = mysqli_stmt_get_result($stmt);
$result_newloanid = mysqli_fetch_assoc($query_newloanid);
$_SESSION['loan_id'] = $result_newloanid['max_loan_id'];

header('Location: group_loan_sec.php?loan_id=' . $_SESSION['loan_id']);
exit;
}

?>
<html>
<?php includeHead('New Group Loan', 0) ?>
<script type="text/javascript">
function calc_rate(feerate) {
  var amount, interest, instal, rate;
  amount = (document.getElementById("loan_principal").value * 1);
  interest = (document.getElementById("loan_interest").value * 1);
  instal = (document.getElementById("loan_period").value * 1);
  repaytotal = Math.ceil((amount + (amount / 100 * interest * instal)) / 50) * 50;
  rate = Math.round(repaytotal / instal);
  document.getElementById("loan_repaytotal").value = repaytotal;
  document.getElementById("loan_rate").value = rate;
}

function validate(form) {
  fail = validatePrincipal(form.loan_principal.value)
  fail += validateInstalment(form.loan_period.value)
  fail += validateInterest(form.loan_interest.value)
  fail += validatePurpose(form.loan_purpose.value)
  fail += validateLC1Name(form.lc1_name.value)
  fail += validateLC1Address(form.lc1_address.value)
  fail += validateLC1Contact(form.lc1_contact.value)
  fail += validateDate(form.loan_date.value)
  if (fail == "") return true
  else {
    alert(fail);
    return false
  }
}
</script>
</head>
<body>
<!-- MENU -->
<?php includeMenu(2); ?>
<div id="menu_main">
  <a href="group.php?group=<?php echo $_SESSION['group_id'] ?>">Back</a>
  <a href="group_search.php">Search</a>
  <a href="give_loan.php?group=<?php echo $_SESSION['group_id'] ?>" id="item_selected">New Loan</a>
  <a href="group_new.php">New Group</a>
  <a href="group_act.php">Active Groups</a>
  <a href="group_inact.php">Inactive Groups</a>
</div>
<div class="content_center">
  <p class="heading">New Loan Application for Group <?php echo $result_group['group_name'] . ' (' . $result_group['group_id'] . ')'; ?></p>
  <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" onSubmit="return validate(this)">
    <table id="tb_fields" style="width:85%;">
      <colgroup>
        <col width="15%">
        <col width="35%">
        <col width="15%">
        <col width="35%">
      </colgroup>
      <tr>
        <td style="font-weight:bold;">Principal:</td>
        <td><input type="number" class="defaultnumber" name="loan_principal" id="loan_principal" placeholder="Loan Sum" onChange="calc_rate(<?php echo $_SESSION['fee_loan']; ?>)" /></td>
        <td style="font-weight:bold;">No of installements:</td>
        <td><input type="number" class="defaultnumber" name="loan_period" id="loan_period" placeholder="Number of lnstallements" onChange="calc_rate(<?php echo $_SESSION['fee_loan']; ?>)" /></td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Interest Rate:</td>
        <td><input type="text" name="loan_interest" id="loan_interest" value="<?php echo $_SESSION['fee_loaninterestrate']; ?>" placeholder="% per week/day" onChange="calc_rate(<?php echo $_SESSION['fee_loan']; ?>)" /></td>
        <td style="font-weight:bold;">Purpose:</td>
        <td><input type="text" name="loan_purpose" placeholder="Purpose for the Loan" /></td>
      </tr>
      <tr>
        <td style="font-weight:bold;">LC1 Name:</td>
        <td><input type="text" name="lc1_name" placeholder="LC1 Name" /></td>
        <td style="font-weight:bold;">LC1 Address:</td>
        <td><input type="text" name="lc1_address" placeholder="LC1 Address" /></td>
      </tr>
      <tr>
        <td style="font-weight:bold;">LC1 Contact:</td>
        <td><input type="text" name="lc1_contact" placeholder="LC1 Contact" /></td>
      </tr>
      <tr>
        <td>Monthly/Weekly Installement:</td>
        <td><input type="text" name="loan_rate" id="loan_rate" disabled="disabled" /></td>
        <td>Repay Total:</td>
        <td><input type="text" name="loan_repaytotal" id="loan_repaytotal" disabled="disabled" /></td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Date of Applic.:</td>
        <td> <input type="text" id="datepicker" name="loan_date" placeholder="DD.MM.YYYY" value="<?php echo date("d.m.Y", $timestamp) ?>" /> </td>
      </tr>
      <tr>
        <td class="center" colspan="4"> <input type="submit" name="newloan" value="Continue" /> </td>
      </tr>
    </table>
  </form
  </html>