<?php
header("Content-Type: application/json");
include_once("../../config.php"); // ← $conn is your mysqli connection

// Expect: ?branch_id=…&user_id=…&loan_id=…
if (
    isset($_GET['branch_id']) &&
    isset($_GET['user_id']) &&
    isset($_GET['loan_id'])
) {
    $branch_id   = intval($_GET['branch_id']);
    $customer_id = intval($_GET['user_id']);
    $loan_id     = intval($_GET['loan_id']);

    // 1) Pull all collections for exactly this branch_id + customer_id + loan_id
    $sqlCollections = "
        SELECT 
            id,
            customer_id,
            loan_id,
            branch_id,
            amount_paid,
            payment_method,
            payment_date
        FROM loans_collection
        WHERE branch_id = $branch_id
          AND customer_id = $customer_id
          AND loan_id = $loan_id
        ORDER BY payment_date ASC
    ";
    $resultCollections = mysqli_query($conn, $sqlCollections);
    $collections = [];

    if ($resultCollections) {
        while ($row = mysqli_fetch_assoc($resultCollections)) {
            $row['amount_paid'] = floatval($row['amount_paid']);
            $collections[] = $row;
        }
    }

    // → If no matching collections, just return an empty receipts array
    if (empty($collections)) {
        echo json_encode(["receipts" => []]);
        exit;
    }

    // 2) Fetch customer info
    $sqlCustomer = "
        SELECT id, firstname, middlename, lastname, phone
        FROM customers
        WHERE id = $customer_id
        LIMIT 1
    ";
    $resultCustomer = mysqli_query($conn, $sqlCustomer);
    $customer = mysqli_fetch_assoc($resultCustomer);

    // 3) Fetch loan info (loan_amount, loan_period, interest, etc.)
    $sqlLoan = "
        SELECT
            loan_id,
            customer_id,
            branch_id,
            loan_amount,
            loan_period,
            interest
        FROM loans
        WHERE loan_id = $loan_id
          AND customer_id = $customer_id
        LIMIT 1
    ";
    $resultLoan = mysqli_query($conn, $sqlLoan);
    $loan = mysqli_fetch_assoc($resultLoan);

    if (!$loan) {
        echo json_encode(["receipts" => []]);
        exit;
    }

    // 4) Use interest from loan table (not branch)
    $loan_amount = floatval($loan['loan_amount']);
    $loan_period = intval($loan['loan_period']);
    $interest    = floatval($loan['interest']);

    // 5) Compute totalDue = loan_amount * (1 + interest * loan_period)
    $totalDue = $loan_amount * (1 + ($interest * $loan_period));

    // 6) Walk through $collections in ascending payment_date order, build currentRemainingDue
    $cumulative = 0.0;
    foreach ($collections as &$col) {
        $cumulative += floatval($col['amount_paid']);
        $col['currentRemainingDue'] = $totalDue - $cumulative;
    }
    unset($col);

    $totalCollected = $cumulative;
    $remainingDue   = $totalDue - $totalCollected;

    // 7) Build receipt object
    $receipt = [
        "customer"       => $customer,
        "phone"          => ($customer['phone'] ?? ""),
        "loanAmount"     => $loan_amount,
        "interest"       => $interest,
        "totalDue"       => $totalDue,
        "totalCollected" => $totalCollected,
        "remainingDue"   => $remainingDue,
        "collections"    => $collections
    ];

    echo json_encode(["receipts" => [$receipt]]);
    exit;

} else {
    echo json_encode(["receipts" => []]);
    exit;
}
?>
