<?php
require_once '../../config.php';
header('Content-Type: application/json');

// 1. Read inputs
$branch_id = isset($_GET['branch_id']) ? intval($_GET['branch_id']) : 0;
$user_id   = isset($_GET['user_id'])   ? intval($_GET['user_id'])   : 0;

// Ensure DB connection exists
if (!isset($conn) || !$conn instanceof mysqli) {
    http_response_code(500);
    echo json_encode(['error' => 'Database connection not available']);
    exit;
}

// 2. Fetch loans with branch interest rate
if ($branch_id > 0) {
    $sql = "
      SELECT l.loan_id, l.loan_amount, l.loan_period,
             l.interest, l.branch_id
      FROM loans l
      JOIN branches b ON l.branch_id = b.branch_id
      WHERE b.user_id = ? AND l.branch_id = ?
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $user_id, $branch_id);
} else {
    $sql = "
      SELECT l.loan_id, l.loan_amount, l.loan_period,
             l.interest, l.branch_id
      FROM loans l
      JOIN branches b ON l.branch_id = b.branch_id
      WHERE b.user_id = ?
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $user_id);
}
$stmt->execute();
$loans = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$records = [];
$total_profit_due = 0.0;

foreach ($loans as $loan) {
    $loan_amount      = floatval($loan['loan_amount']);
    $loan_period      = max(intval($loan['loan_period']), 1);
    // interest stored as decimal (e.g. 0.08 for 8%)
    $rate_per_period  = floatval($loan['interest']);

    // Compute total interest and total due
    $total_interest   = $loan_amount * $rate_per_period * $loan_period;
    $total_due        = $loan_amount + $total_interest;

    // Accumulate overall profit
    $total_profit_due += $total_interest;

    // Scheduled amounts per installment
    $scheduled_installment       = $total_due / $loan_period;
    $scheduled_interest_per_inst = $total_interest / $loan_period;
    $profit_ratio                = $scheduled_interest_per_inst / $scheduled_installment;

    // Fetch repayments for this loan
    $stmt2 = $conn->prepare(
        "SELECT amount_paid, payment_date
         FROM loans_collection
         WHERE loan_id = ?"
    );
    $stmt2->bind_param("i", $loan['loan_id']);
    $stmt2->execute();
    $reps = $stmt2->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt2->close();

    foreach ($reps as $r) {
        $amt    = floatval($r['amount_paid']);
        $profit = $amt * $profit_ratio;
        $records[] = [
            'branch_id'         => intval($loan['branch_id']),
            'loan_id'           => intval($loan['loan_id']),
            'payment_date'      => $r['payment_date'],
            'profit'            => round($profit, 2),
        ];
    }
}

// 4. Totals collected and outstanding
$total_collected   = array_sum(array_column($records, 'profit'));
$total_outstanding = $total_profit_due - $total_collected;

// 5. Inject totals into each record
foreach ($records as &$rec) {
    $rec['total_collected']   = round($total_collected, 2);
    $rec['total_outstanding'] = round($total_outstanding, 2);
}
unset($rec);

// 6. Output JSON
echo json_encode($records, JSON_PRETTY_PRINT);
