<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class InstallmentSeeder extends Seeder
{
    public function run(): void
    {
        $bookings = DB::table('bookings')->pluck('id')->toArray();
        
        foreach ($bookings as $bookingId) {
            $booking = DB::table('bookings')->where('id', $bookingId)->first();
            $installmentAmount = $booking->installment_amount;
            $installmentCount = rand(5, 24);
            
            for ($i = 1; $i <= $installmentCount; $i++) {
                $dueDate = now()->addMonths($i);
                $status = 'pending';
                $amountPaid = 0;
                $paidAt = null;
                
                // Randomly mark some installments as paid
                if (rand(0, 1) && $i < $installmentCount / 2) {
                    $status = 'paid';
                    $amountPaid = $installmentAmount;
                    $paidAt = $dueDate->subDays(rand(1, 10));
                } elseif ($dueDate < now()) {
                    $status = 'overdue';
                }
                
                DB::table('installments')->insert([
                    'booking_id' => $bookingId,
                    'installment_number' => $i,
                    'installment_type' => ['monthly', 'quarterly', 'yearly', 'custom'][array_rand(['monthly', 'quarterly', 'yearly', 'custom'])],
                    'due_date' => $dueDate,
                    'reminder_date' => $dueDate->subDays(7),
                    'amount' => $installmentAmount,
                    'amount_paid' => $amountPaid,
                    'paid_at' => $paidAt,
                    'status' => $status,
                    'description' => 'Installment ' . $i . ' for booking ' . $bookingId,
                    'reference_no' => 'REF-' . Str::random(8),
                    'created_by' => 1,
                    'updated_by' => 1,
                    'source_ip' => '127.0.0.1',
                    'source_mac' => '00:00:00:00:00:00',
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }
        }
    }
}