<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Content-Type: application/json');
require_once '../../config.php';

$customer_id = isset($_GET['customer_id'])
    ? intval($_GET['customer_id'])
    : (isset($_POST['customer_id']) ? intval($_POST['customer_id']) : 0);

if ($customer_id <= 0) {
    echo json_encode([
        "success" => false,
        "message" => "Missing or invalid customer_id"
    ]);
    exit;
}

$sql = "
  SELECT
    lc.id,
    lc.loan_id,
    lc.amount_paid,
    lc.payment_method,
    lc.payment_date,
    l.loan_amount,
    l.loan_period,
    b.interest
  FROM loans_collection lc
  JOIN loans l ON lc.loan_id = l.loan_id
  JOIN branches b ON l.branch_id = b.branch_id
  WHERE lc.customer_id = ?
  ORDER BY lc.payment_date ASC
";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    echo json_encode(["success" => false, "message" => "DB prepare failed"]);
    exit;
}

$stmt->bind_param('i', $customer_id);
$stmt->execute();
$result = $stmt->get_result();

$cumulative = [];
$collections = [];

while ($row = $result->fetch_assoc()) {
    $loanId     = (int)$row['loan_id'];
    $principal  = (float)$row['loan_amount'];
    $interest   = (float)$row['interest'];
    $period     = (int)$row['loan_period'];

    $total_due  = $principal + ($principal * $interest * $period);

    if (!isset($cumulative[$loanId])) {
        $cumulative[$loanId] = 0;
    }

    $paid = (float)$row['amount_paid'];
    $prev_paid = $cumulative[$loanId];
    $prev_remaining = $total_due - $prev_paid;

    $cumulative[$loanId] += $paid;
    $after_remaining = $total_due - $cumulative[$loanId];
    if ($after_remaining < 0) {
        $after_remaining = 0;
    }

    $collections[] = [
        "id" => (int)$row['id'],
        "loan_id" => $loanId,
        "amount_paid" => round($paid, 2),
        "payment_method" => $row['payment_method'],
        "payment_date" => $row['payment_date'],
        "total_due" => round($total_due, 2),
        "previous_remaining" => round($prev_remaining, 2),
        "remaining_due" => round($after_remaining, 2),
    ];
}

$stmt->close();
$conn->close();

echo json_encode([
    "success" => true,
    "collections" => $collections
]);
