<?php
// database/factories/PaymentFactory.php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

class PaymentFactory extends Factory
{
    public function definition(): array
    {
        $statuses = ['pending', 'waiting_confirmation', 'confirmed', 'failed', 'refunded'];
        $status = $this->faker->randomElement($statuses);
        
        return [
            'order_id' => \App\Models\Order::factory(),
            'payment_method_id' => \App\Models\PaymentMethod::factory(),
            'amount' => function (array $attributes) {
                $order = \App\Models\Order::find($attributes['order_id']);
                return $order ? $order->final_amount : $this->faker->numberBetween(50000, 500000);
            },
            'status' => $status,
            'proof_image' => $status === 'waiting_confirmation' 
                ? $this->faker->imageUrl(400, 300, 'business', true, 'payment')
                : null,
            'payment_date' => $status === 'confirmed' 
                ? $this->faker->dateTimeBetween('-1 month', 'now')
                : null,
            'confirmed_by' => $status === 'confirmed'
                ? \App\Models\User::where('role', 'employee')->inRandomOrder()->first()->id ?? null
                : null,
            'confirmed_at' => $status === 'confirmed'
                ? $this->faker->dateTimeBetween('-1 month', 'now')
                : null,
            'reference_number' => $this->faker->optional(0.7)->bothify('REF###???##'),
            'notes' => $this->faker->optional(0.2)->sentence(),
            'created_at' => $this->faker->dateTimeBetween('-6 months', 'now'),
            'updated_at' => now(),
        ];
    }
    
    public function confirmed(): static
    {
        return $this->state(fn (array $attributes) => [
            'status' => 'confirmed',
            'payment_date' => now(),
            'confirmed_at' => now(),
            'confirmed_by' => \App\Models\User::where('role', 'employee')->inRandomOrder()->first()->id,
        ]);
    }
    
    public function waitingConfirmation(): static
    {
        return $this->state(fn (array $attributes) => [
            'status' => 'waiting_confirmation',
            'proof_image' => $this->faker->imageUrl(),
        ]);
    }
}