<?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. Helper: allocate principal vs interest per repayment
function allocatePayment($loan_amount, $interest, $payment, $loan_period) {
    // total interest over full term
    $total_interest          = $loan_amount * $interest * $loan_period;
    // total due = principal + total_interest
    $total_due               = $loan_amount + $total_interest;
    // per‐period installment
    $scheduled_installment   = $total_due / $loan_period;
    // interest component per period
    $scheduled_interest      = $total_interest / $loan_period;
    // principal component per period
    $scheduled_principal     = $loan_amount / $loan_period;
    // ratios for splitting any payment
    $profit_ratio            = $scheduled_interest / $scheduled_installment;
    $principal_ratio         = $scheduled_principal / $scheduled_installment;

    return [
        'profit_paid'    => $payment * $profit_ratio,
        'principal_paid' => $payment * $principal_ratio,
    ];
}

// 3. Fetch loans with per‐loan interest
if ($branch_id > 0) {
    $sql = "
      SELECT l.loan_id, l.loan_amount, l.loan_period, l.interest
      FROM loans l
      JOIN branches b ON l.branch_id = b.branch_id
      WHERE l.branch_id = ? AND b.user_id = ?
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $branch_id, $user_id);
} else {
    $sql = "
      SELECT l.loan_id, l.loan_amount, l.loan_period, l.interest
      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();

// 4. Initialize totals and daily breakdown
$total_principal_disbursed = 0.0;
$total_principal_repaid   = 0.0;
$total_interest_repaid    = 0.0;
$daily = [];  // ['YYYY-MM-DD' => ['principal'=>x, 'interest'=>y]]

// 5. Process each loan and its repayments
foreach ($loans as $loan) {
    $loan_id    = intval($loan['loan_id']);
    $amt        = floatval($loan['loan_amount']);
    $period     = max(intval($loan['loan_period']), 1);
    // interest stored as decimal (e.g. 0.08 for 8%)
    $interest   = floatval($loan['interest']);

    $total_principal_disbursed += $amt;

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

    foreach ($reps as $r) {
        $paid = floatval($r['amount_paid']);
        $date = $r['payment_date'];

        $alloc = allocatePayment($amt, $interest, $paid, $period);
        $total_principal_repaid += $alloc['principal_paid'];
        $total_interest_repaid  += $alloc['profit_paid'];

        if (!isset($daily[$date])) {
            $daily[$date] = ['principal' => 0.0, 'interest' => 0.0];
        }
        $daily[$date]['principal'] += $alloc['principal_paid'];
        $daily[$date]['interest']  += $alloc['profit_paid'];
    }
}

// 6. Calculate overall totals
$outstanding_principal = $total_principal_disbursed - $total_principal_repaid;
$all_collection        = $total_principal_repaid + $total_interest_repaid;

// 7. Build and output response
$records = [];
foreach ($daily as $dt => $vals) {
    $records[] = [
        'payment_date'               => $dt,
        'daily_principal_repaid'     => round($vals['principal'], 2),
        'daily_interest_repaid'      => round($vals['interest'], 2),
        'total_principal_disbursed'  => round($total_principal_disbursed, 2),
        'total_principal_repaid'     => round($total_principal_repaid, 2),
        'total_interest_repaid'      => round($total_interest_repaid, 2),
        'outstanding_principal'      => round($outstanding_principal, 2),
        'all_collection'             => round($all_collection, 2),
    ];
}

echo json_encode($records, JSON_PRETTY_PRINT);
