<?php 
// Calculate monthly interest rate
$monthly_interest_rate = $loan_interest / 100;

// Calculate fixed principal per installment
$fixed_principal = round($loan_principalapproved / ($loan_period * 4));

// Calculate total interest
$total_interest = $loan_principalapproved * ($monthly_interest_rate / 4) * ($loan_period * 4);

// Calculate fixed interest per installment
$fixed_interest = round($total_interest / ($loan_period * 4));

// Calculate Due Dates & Due Payments and insert them into LTRANS
$ltrans_due = $loan_dateout + convertDays(7); // Start with 1 week from loan date
$outstanding_balance = $loan_principalapproved;

for ($i = 1; $i <= $loan_period * 4; $i++) {
    // Fixed principal per installment
    $principal_due = $fixed_principal;

    // Fixed interest per installment
    $interest_due = $fixed_interest;

    // If the principal due exceeds the outstanding balance, set it to the outstanding balance
    if ($principal_due > $outstanding_balance) {
        $principal_due = $outstanding_balance;
    }

    // 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', '$principal_due', '$interest_due', '$_SESSION[log_id]')";
    $query_insert_ltrans = mysqli_query($db_link, $sql_insert_ltrans);
    checkSQL($db_link, $query_insert_ltrans);

    // Update outstanding balance
    $outstanding_balance -= $principal_due;

    // Next due date
    $ltrans_due = $ltrans_due + convertDays(7); // Add 1 week
}
?>
