<?php
// Calculate expected total interest and weekly rates
$loan_period_weeks = $loan_period * 4; // Calculate total number of weeks
$weekly_interest_rate = ($loan_interest / 100) / 4; // Convert monthly interest rate to weekly interest rate
$loan_inter_total = ceil((($loan_princp_approved * $loan_interest / 100) * $loan_period)/50)*50; // Calculate total interest
$loan_princp_due = round($loan_princp_approved / $loan_period_weeks); // Calculate weekly principal due
$loan_inter_due = round($loan_princp_approved * $weekly_interest_rate); // Calculate weekly interest due

// Check if weekly rates multiplied by number of weeks sums up to the expected total repay amounts exactly. Calculate difference.
$difference_principal = $loan_princp_approved - ($loan_princp_due * $loan_period_weeks);
$difference_interest = $loan_inter_total - ($loan_inter_due * $loan_period_weeks);

// Calculate Due Dates & Due Payments and insert them into LTRANS
$ltrans_due = $loan_dateout + convertDays(7); // Start with 1 week after loan date out
$ltrans_princp_due = $loan_princp_due;
$ltrans_inter_due = $loan_inter_due;
$i = 1;
while ($i <= $loan_period_weeks){
    // Add differences on first iteration.
    if ($i == 1) {
        $ltrans_princp_due = $ltrans_princp_due + $difference_principal / $loan_period_weeks;
        $ltrans_inter_due = $ltrans_inter_due + $difference_interest / $loan_period_weeks;
    }
    // Insert into LTRANS
    $sql_insert_ltrans = "INSERT INTO ltrans (loan_id, ltrans_due, ltrans_principaldue, ltrans_interestdue, user_id) VALUES ('$_SESSION[loan_id]', '$ltrans_due', '$ltrans_princp_due', '$ltrans_inter_due', '$_SESSION[log_id]')";
    $query_insert_ltrans = mysqli_query($db_link, $sql_insert_ltrans);
    checkSQL($db_link, $query_insert_ltrans);
    // Reset both due amounts to standard value after first iteration
    if ($i == 1) {
        $ltrans_princp_due = $loan_princp_due;
        $ltrans_inter_due = $loan_inter_due;
    }
    $ltrans_due = $ltrans_due + convertDays(7); /* Add seconds for 7 days */
    $i++;
}

?>
