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

// Pata parameters kutoka kwa query string
$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$branch_id = isset($_GET['branch_id']) ? intval($_GET['branch_id']) : 0;

// SQL query yenye join kati ya meza na filtering kwa branches ambazo user_id yao ni sawa na yako
$sql = "SELECT 
            lc.id, 
            lc.customer_id, 
            lc.loan_id, 
            lc.branch_id, 
            lc.amount_paid, 
            lc.payment_method, 
            lc.payment_date, 
            c.firstname, 
            c.middlename, 
            c.lastname, 
            b.branch_name 
        FROM loans_collection lc 
        JOIN customers c ON lc.customer_id = c.id 
        JOIN branches b ON lc.branch_id = b.branch_id 
        WHERE b.user_id = ?";

if ($branch_id != 0) {
    $sql .= " AND lc.branch_id = ?";
}

// Tayarisha statement bila PDO; tumia mysqli_prepare na bind parameters
if ($branch_id != 0) {
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "ii", $user_id, $branch_id);
} else {
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "i", $user_id);
}

mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

$collections = array();
while ($row = mysqli_fetch_assoc($result)) {
    $collections[] = $row;
}

echo json_encode($collections);
?>
