<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class UserBonus extends Model
{
    protected $fillable = [
        'user_id', 'promotion_id', 'code', 'type', 'name',
        'bonus_amount', 'wagering_multiplier', 'wagered_amount',
        'required_wagering', 'max_bet_while_active',
        'status', 'expires_at', 'completed_at', 'forfeited_at',
    ];
    protected $casts = [
        'expires_at' => 'datetime', 'completed_at' => 'datetime', 'forfeited_at' => 'datetime',
        'bonus_amount' => 'float', 'wagering_multiplier' => 'float',
        'wagered_amount' => 'float', 'required_wagering' => 'float',
    ];

    public function user() { return $this->belongsTo(User::class); }
    public function promotion() { return $this->belongsTo(Promotion::class); }

    public function wageringProgress(): float
    {
        if ($this->required_wagering <= 0) return 100;
        return min(100, round(($this->wagered_amount / $this->required_wagering) * 100, 1));
    }

    public function isExpired(): bool
    {
        return $this->expires_at && $this->expires_at->isPast();
    }

    public function addWagering(float $amount): void
    {
        $this->increment('wagered_amount', $amount);
        $this->refresh();
        if ($this->wagered_amount >= $this->required_wagering && $this->status === 'active') {
            $this->update(['status' => 'completed', 'completed_at' => now()]);
        }
    }
}
