<?php
include '../../config.php';

$branch_id = isset($_GET['branch_id']) ? intval($_GET['branch_id']) : null;
$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;

if ($branch_id !== null && $branch_id > 0) {
    $sql = "SELECT 
                l.loan_id,
                c.id AS customer_id,
                c.firstname,
                c.middlename,
                c.lastname,
                l.loan_amount,
                l.loan_period,
                l.interest,
                l.status
            FROM loans l
            INNER JOIN customers c ON l.customer_id = c.id
            INNER JOIN branches b ON l.branch_id = b.branch_id
            WHERE l.branch_id = ? AND b.user_id = ? AND l.status = 'Paid'";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $branch_id, $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $sql = "SELECT 
                l.loan_id,
                c.id AS customer_id,
                c.firstname,
                c.middlename,
                c.lastname,
                l.loan_amount,
                l.loan_period,
                l.interest,
                l.status
            FROM loans l
            INNER JOIN customers c ON l.customer_id = c.id
            INNER JOIN branches b ON l.branch_id = b.branch_id
            WHERE b.user_id = ? AND l.status = 'Paid'";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
}

$loans = [];
while ($row = $result->fetch_assoc()) {
    // jumlisha malipo
    $stmt_payments = $conn->prepare("
        SELECT COALESCE(SUM(amount_paid), 0) AS total_payments 
        FROM loans_collection 
        WHERE customer_id = ? AND loan_id = ?
    ");
    $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();

    // hesabu interest na balance
    $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
    $row['customer_name'] = trim($row['firstname'] . ' ' . $row['middlename'] . ' ' . $row['lastname']);
    $row['total_payments'] = $total_payments;
    $row['total_due'] = $total_due;
    $row['remaining'] = $remaining;

    $loans[] = $row;
}

if (isset($stmt)) {
    $stmt->close();
}
$conn->close();

header('Content-Type: application/json');
echo json_encode($loans);
?>
