<?php

namespace App\Models;

use Database\Factories\UserFactory;
use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable implements FilamentUser
{
    /** @use HasFactory<UserFactory> */
    use HasFactory, Notifiable, HasApiTokens, HasRoles;

    protected $fillable = [
        'name', 'username', 'email', 'password', 'avatar', 'phone',
        'date_of_birth', 'balance', 'is_active',
        'email_notifications', 'promotional_offers', 'security_alerts',
        'currency', 'language', 'vip_tier', 'vip_points',
    ];

    protected $hidden = ['password', 'remember_token'];

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'balance' => 'decimal:2',
            'is_active' => 'boolean',
            'email_notifications' => 'boolean',
            'promotional_offers' => 'boolean',
            'security_alerts' => 'boolean',
            'date_of_birth' => 'date',
        ];
    }

    public function canAccessPanel(Panel $panel): bool
    {
        if ($panel->getId() !== 'admin') {
            return false;
        }

        if (! $this->is_active) {
            return false;
        }

        return $this->hasAnyRole(['admin', 'agent'])
            || $this->email === 'admin@vvmj8.com';
    }

    public function bets()
    {
        return $this->hasMany(Bet::class);
    }

    public function transactions()
    {
        return $this->hasMany(Transaction::class);
    }

    public function posTerminals()
    {
        return $this->hasMany(PosTerminal::class, 'agent_id');
    }

    public function posSales()
    {
        return $this->hasMany(PosSale::class, 'agent_id');
    }

    public function posPurchases()
    {
        return $this->hasMany(PosSale::class, 'customer_user_id');
    }

    public function getWinRateAttribute(): float
    {
        $total = $this->bets()->whereIn('status', ['won', 'lost'])->count();
        if ($total === 0) return 0;
        $won = $this->bets()->where('status', 'won')->count();
        return round(($won / $total) * 100, 1);
    }

    public function getTotalStakedAttribute(): float
    {
        return $this->bets()->sum('stake');
    }

    public function getTotalWonAttribute(): float
    {
        return $this->bets()->where('status', 'won')->sum('actual_payout');
    }
}
