<?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) {
    // NOTE: tumeongeza l.branch_id ndani ya SELECT
    $sql = "SELECT 
                l.loan_id,
                l.branch_id,
                c.id AS customer_id,
                c.firstname,
                c.middlename,
                c.lastname,
                l.loan_amount,
                l.loan_period,
                l.interest,
                l.loan_date,
                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 IS NULL";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $branch_id, $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    // NOTE: pia tumeongeza l.branch_id hapa ndani ya SELECT
    $sql = "SELECT 
                l.loan_id,
                l.branch_id,
                c.id AS customer_id,
                c.firstname,
                c.middlename,
                c.lastname,
                l.loan_amount,
                l.loan_period,
                l.interest,
                l.loan_date,
                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 IS NULL";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
}

$loans = [];
while ($row = $result->fetch_assoc()) {
    // 1) Jumla ya malipo yaliyofanyika
    $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();

    // 2) Kalkulatia interest na taarifa nyingine
    $calculated_interest = $row['loan_amount'] * $row['interest'] * $row['loan_period'];
    $total_due  = $row['loan_amount'] + $calculated_interest;
    $remaining  = $total_due - $total_payments;

    // 3) Nijumuishe customer_name, total_payments, total_due, remaining, na tuache branch_id kama inavyotoka DB
    $row['customer_name']   = trim("{$row['firstname']} {$row['middlename']} {$row['lastname']}");
    $row['total_payments']  = $total_payments;
    $row['total_due']       = $total_due;
    $row['remaining']       = $remaining;
    // Hakuna haja ya $row['branch_id']—ila tu tumechukua kwenye SELECT, itarudi moja kwa moja

    $loans[] = $row;
}

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

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