<?php
require_once __DIR__ . '/../../public/vendor/autoload.php';
use App\Models\LoanType;
use App\Models\Loan;
use App\Models\LoanRepayment;
use App\Config\Database;

$db = Database::getInstance()->getConnection();

// Ensure a loan type
$lt = new LoanType();
$stmt = $db->query("SELECT id FROM loan_types LIMIT 1");
$existing = $stmt->fetch(PDO::FETCH_OBJ);
if ($existing) {
    $loanTypeId = $existing->id;
} else {
    $loanTypeId = $lt->create([ 'name' => 'Test Loan', 'description' => 'Auto-created for tests', 'interest_rate' => 0, 'min_amount' => 0, 'max_amount' => 100000, 'min_duration_months' => 1, 'max_duration_months' => 12, 'is_active' => 1, 'created_at' => date('Y-m-d H:i:s') ]);
}

// Create a loan for user 1
$loanModel = new Loan();
$loanId = $loanModel->create([
    'user_id' => 1,
    'loan_type_id' => $loanTypeId,
    'amount' => 100.00,
    'interest_rate' => 0.00,
    'duration_months' => 1,
    'total_payable' => 100.00,
    'monthly_payment' => 100.00,
    'status' => 'disbursed',
    'purpose' => 'Webhook test',
]);

// Create one repayment
$repModel = new LoanRepayment();
$repaymentId = $repModel->create([
    'loan_id' => $loanId,
    'installment_number' => 1,
    'due_date' => date('Y-m-d'),
    'amount' => 100.00,
    'paid_amount' => 0.00,
    'status' => 'pending'
]);

echo "Created loan #{$loanId}, repayment #{$repaymentId}\n";

// Simulate webhook handling by invoking recordPayment
$paid = $repModel->recordPayment((int)$repaymentId, 100.00, 'paystack', 'loan_lr_' . $repaymentId . '_' . time(), 'Simulated webhook payment');

$after = $repModel->find($repaymentId);
$loanAfter = $loanModel->find($loanId);

echo "Repayment after recording: status={$after->status}, paid_amount={$after->paid_amount}, paid_date={$after->paid_date}\n";
if ($loanAfter) echo "Loan status after recording: {$loanAfter->status}\n";
