<?php
require_once __DIR__ . '/../../public/vendor/autoload.php';

use App\Models\Contribution;
use App\Models\Receipt;
use App\Models\LoanRepayment;
use App\Models\Loan;

$raw = file_get_contents('php://stdin');
if (!$raw) {
    echo "No payload provided on STDIN.\n";
    exit(1);
}

$input = json_decode($raw);
if (!$input || !isset($input->event)) {
    echo "Invalid event\n";
    exit(1);
}

if ($input->event === 'charge.success') {
    $reference = $input->data->reference ?? '';
    $amount = ($input->data->amount ?? 0) / 100;

    $contributionModel = new Contribution();
    $contributions = $contributionModel->raw(
        "SELECT * FROM contributions WHERE gateway_ref = ? AND status = 'pending' ORDER BY id DESC LIMIT 1",
        [$reference]
    );

    if (!empty($contributions)) {
        $c = $contributions[0];
        $newBalance = max(0, ($c->total_amount ?? $amount) - $amount);
        $status = ($newBalance <= 0) ? 'completed' : 'partial';

        $contributionModel->update($c->id, [
            'status' => $status,
            'balance' => $newBalance,
            'gateway_response' => json_encode($input),
        ]);

        if ($c->paid_month && $c->contribution_type_id) {
            $contributionModel->updateBalanceForObligation(
                $c->user_id, $c->contribution_type_id, $c->paid_month
            );
        }

        if ($status === 'completed') {
            $receiptModel = new Receipt();
            $receiptModel->create([
                'contribution_id' => $c->id,
                'receipt_number' => $receiptModel->generateNumber(),
                'issued_date' => date('Y-m-d'),
                'issued_by' => $c->user_id,
            ]);
        }

        echo "Processed contribution reference {$reference}, amount={$amount}\n";
    } elseif (str_starts_with($reference, 'loan_lr_')) {
        $parts = explode('_', $reference);
        $repaymentId = $parts[2] ?? null;
        if ($repaymentId) {
            $loanRepModel = new LoanRepayment();
            $loanRepModel->recordPayment((int)$repaymentId, $amount, 'paystack', $reference, 'Direct test webhook (no audit)');

            $repRow = $loanRepModel->find((int)$repaymentId);
            $loanId = $repRow->loan_id ?? 0;
            $totals = $loanRepModel->getTotalsByLoan($loanId);
            $loanModel = new Loan();
            if ($totals && $totals->total_paid >= $totals->total_due) {
                $loanModel->update($loanId, ['status' => 'completed']);
            }

            echo "Recorded repayment {$repaymentId} amount={$amount}\n";
        } else {
            echo "Invalid loan repayment reference\n";
        }
    } else {
        echo "No matching contribution or loan repayment for reference {$reference}\n";
    }
} else {
    echo "Unhandled event {$input->event}\n";
}
