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

// Pata branch_id kutoka GET parameter
$branch_id = isset($_GET['branch_id']) ? intval($_GET['branch_id']) : 0;
if ($branch_id <= 0) {
    echo json_encode(['error' => 'Invalid branch id']);
    exit;
}

// Query ili kupata collections zote za branch hiyo bila filtering ya tarehe
$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,
            c.phone
        FROM loans_collection lc
        INNER JOIN customers c ON lc.customer_id = c.id
        WHERE lc.branch_id = ?";

if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param("i", $branch_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $collections = [];
    while ($row = $result->fetch_assoc()) {
        $collections[] = $row;
    }
    $stmt->close();
    
    echo json_encode([
        'status' => 'success',
        'data' => $collections
    ]);
} else {
    echo json_encode(['error' => 'Query failed']);
}
?>
