<?php

namespace Database\Seeders;

use App\Models\LoanApplication;
use App\Models\LoanRepayment;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Carbon\Carbon;

class DemoLoanSeeder extends Seeder
{
    public function run(): void
    {
        // Demo user (create or reuse)
        $user = User::first() ?: User::create([
            'name' => 'Loan Demo',
            'email' => 'loan-demo@example.com',
            'password' => Hash::make('password'),
            'balance' => 0,
        ]);

        // Pending application
        LoanApplication::firstOrCreate(
            ['user_id' => $user->id, 'status' => 'pending', 'loan_amount' => 10000, 'loan_period' => 6],
            [
                'interest_rate'   => 12.00,
                'estimated_total' => (int) round(10000 + (10000 * (12/100) * (6/12))), // simple interest
                'image_path'      => null,
            ]
        );

        // Approved application + sample schedule
        $approved = LoanApplication::firstOrCreate(
            ['user_id' => $user->id, 'status' => 'approved', 'loan_amount' => 20000, 'loan_period' => 12],
            [
                'interest_rate'   => 12.00,
                'estimated_total' => (int) round(20000 + (20000 * (12/100) * (12/12))),
                'image_path'      => null,
            ]
        );

        if ($approved->repayments()->count() === 0) {
            $perMonth = round($approved->estimated_total / $approved->loan_period, 2);
            $start = Carbon::today()->addMonth();
            for ($i = 0; $i < $approved->loan_period; $i++) {
                LoanRepayment::create([
                    'loan_application_id' => $approved->id,
                    'due_date' => $start->copy()->addMonths($i)->toDateString(),
                    'amount'   => $perMonth,
                    'status'   => $i === 0 ? 'paid' : 'due',
                    'paid_at'  => $i === 0 ? Carbon::today() : null,
                ]);
            }
        }

        // Rejected application
        LoanApplication::firstOrCreate(
            ['user_id' => $user->id, 'status' => 'rejected', 'loan_amount' => 5000, 'loan_period' => 3],
            [
                'interest_rate'   => 10.00,
                'estimated_total' => (int) round(5000 + (5000 * (10/100) * (3/12))),
                'image_path'      => null,
            ]
        );
    }
}
