<?php
header("Content-Type: application/json");
include '../config.php';

if (isset($_GET['branch_id'])) {
    $branch_id = intval($_GET['branch_id']);
    
    // Query inaunganisha loans na customers, na inachuja loans ambazo status ni 'Paid'
    $sql = "SELECT 
            l.loan_id,
            c.id as customer_id,
            c.firstname as customer_firstname,
            c.middlename as customer_middlename,
            c.lastname as customer_lastname,
            l.loan_amount,
            l.loan_period,
            l.interest,
            l.status
        FROM loans l
        INNER JOIN customers c ON l.customer_id = c.id
        WHERE l.branch_id = ? AND l.status = 'Paid'";


    if ($stmt = $conn->prepare($sql)) {
        $stmt->bind_param("i", $branch_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $loans = array();
        while ($row = $result->fetch_assoc()) {
            // Pata total ya malipo kwa kutumia loans_collection
            $stmt_payments = $conn->prepare("SELECT COALESCE(SUM(amount_paid), 0) AS total_payments FROM loans_collection WHERE customer_id = ? AND loan_id = ?");
            if ($stmt_payments) {
                $stmt_payments->bind_param("ii", $row['customer_id'], $row['loan_id']);
                $stmt_payments->execute();
                $stmt_payments->bind_result($total_payments);
                $stmt_payments->fetch();
                $stmt_payments->close();
            } else {
                $total_payments = 0;
            }

            // Hesabu interest (loan_amount * interest * loan_period), total_due na remaining
            $calculated_interest = $row['loan_amount'] * $row['interest'] * $row['loan_period'];
            $total_due = $row['loan_amount'] + $calculated_interest;
            $remaining = $total_due - $total_payments;
            
            // Tengeneza jina kamili la mteja (tutafuta middle name ikiwa ipo)
            $fullName = trim($row['customer_firstname'] . ' ' . $row['customer_middlename'] . ' ' . $row['customer_lastname']);
            $row['customer_name'] = $fullName;
            $row['total_payments'] = $total_payments;
            $row['total_due'] = $total_due;
            $row['remaining'] = $remaining;
            $loans[] = $row;
        }
        echo json_encode($loans);
        $stmt->close();
    } else {
        echo json_encode(['error' => 'Query failed: ' . $conn->error]);
    }
} else {
    echo json_encode(['error' => 'branch_id parameter missing']);
}

$conn->close();
?>
