<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable implements MustVerifyEmail
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'email',
        'phone',
        'role',
        'password',
        'vacation_mode',
        'can_create_custom_locations',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var list<string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'vacation_mode' => 'boolean',
            'can_create_custom_locations' => 'boolean',
        ];
    }

    // Role helper methods
    public function isAdmin(): bool
    {
        return $this->role === 'admin';
    }

    public function isHost(): bool
    {
        return $this->role === 'host';
    }

    public function isUser(): bool
    {
        return $this->role === 'user';
    }

    // Relationships
    public function listings()
    {
        return $this->hasMany(Listing::class);
    }

    public function bookings()
    {
        return $this->hasMany(Booking::class);
    }

    public function reviews()
    {
        return $this->hasMany(Review::class);
    }

    public function badges()
    {
        return $this->hasMany(HostBadge::class);
    }

    public function activeBadges()
    {
        return $this->badges()->where(function($query) {
            $query->whereNull('expires_at')
                  ->orWhere('expires_at', '>', now());
        });
    }

    public function getHighestBadgeAttribute()
    {
        return $this->activeBadges()
            ->orderByRaw("FIELD(badge_type, 'super_host', 'local_legend', 'top_rated', 'rising_star')")
            ->first();
    }

    public function getTotalReviewsForListingsAttribute()
    {
        return Review::whereIn('listing_id', $this->listings()->pluck('id'))->count();
    }

    public function getAverageRatingForListingsAttribute()
    {
        return Review::whereIn('listing_id', $this->listings()->pluck('id'))->avg('rating') ?? 0;
    }
}
