<?php

namespace Database\Seeders;

use App\Models\Loan;
use App\Models\User;
use Illuminate\Database\Seeder;

class LoanSeeder extends Seeder
{
    public function run(): void
    {
        $employees = User::where('type', 'employee')->limit(5)->get();
        $admin = User::where('type', 'super-admin')->first();

        $loanData = [
            ['amount' => 5000, 'installment' => 500, 'status' => 'approved', 'remarks' => 'Approved for home renovation'],
            ['amount' => 2000, 'installment' => 200, 'status' => 'pending', 'remarks' => 'Pending for medical emergency'],
            ['amount' => 3000, 'installment' => 300, 'status' => 'rejected', 'remarks' => 'Rejected due to insufficient tenure'],
            ['amount' => 1000, 'installment' => 100, 'status' => 'approved', 'remarks' => 'Approved for furniture purchase'],
            ['amount' => 500, 'installment' => 50, 'status' => 'pending', 'remarks' => 'Awaiting manager review'],
        ];

        foreach ($employees as $index => $employee) {
            if (isset($loanData[$index])) {
                Loan::updateOrCreate(
                    ['employee_id' => $employee->id, 'total_amount' => $loanData[$index]['amount']],
                    [
                        'loan_date' => now()->subMonths(1),
                        'installment_amount' => $loanData[$index]['installment'],
                        'start_month' => now()->format('Y-m'),
                        'remaining_balance' => $loanData[$index]['amount'],
                        'status' => $loanData[$index]['status'],
                        'approved_by' => $loanData[$index]['status'] === 'approved' ? $admin->id : null,
                        'approved_at' => $loanData[$index]['status'] === 'approved' ? now()->subMonths(1) : null,
                        'remarks' => $loanData[$index]['remarks'],
                    ]
                );
            }
        }
    }
}
