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

if (isset($_GET['branch_id'])) {
    $branch_id = intval($_GET['branch_id']);
    
    // Tunaangalia interest kutoka table ya loans (l.interest) - hatujashirikisha branches tena
    $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_date,
                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 IS NULL";

    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
            $total_payments = 0;
            $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();
            }

            // Tumia interest kutoka loans table (l.interest)
            $interest = isset($row['interest']) ? floatval($row['interest']) : 0.0;
            $loan_amount = isset($row['loan_amount']) ? floatval($row['loan_amount']) : 0.0;
            $loan_period = isset($row['loan_period']) ? intval($row['loan_period']) : 0;

            // Hesabu interest (loan_amount * interest * loan_period), total_due na remaining
            $calculated_interest = $loan_amount * $interest * $loan_period;
            $total_due = $loan_amount + $calculated_interest;
            $remaining = $total_due - floatval($total_payments);

            // Tengeneza jina kamili (trim ili kuondoa spaces ziwepo)
            $fullName = trim($row['customer_firstname'] . ' ' . $row['customer_middlename'] . ' ' . $row['customer_lastname']);
            $row['customer_name'] = $fullName;
            $row['total_payments'] = floatval($total_payments);
            $row['calculated_interest'] = $calculated_interest;
            $row['total_due'] = $total_due;
            $row['remaining'] = $remaining;

            $loans[] = $row;
        }

        echo json_encode($loans, JSON_NUMERIC_CHECK);
        $stmt->close();
    } else {
        echo json_encode(['error' => 'Query failed: ' . $conn->error]);
    }
} else {
    echo json_encode(['error' => 'branch_id parameter missing']);
}

$conn->close();
?>
