<?php

namespace App\Models;

use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable implements FilamentUser
{
    use HasApiTokens, HasFactory, Notifiable;

    protected $fillable = [
        'phone', 'name', 'email', 'photo_path', 'role', 'rating_avg',
        'strike_count', 'is_verified', 'is_suspended', 'is_admin', 'trip_credits',
        'lang', 'emergency_contact_phone', 'fcm_token', 'phone_verified_at', 'password',
    ];

    public function canAccessPanel(Panel $panel): bool
    {
        if ($this->is_suspended) return false;

        // Admins get full access
        if ($this->is_admin) return true;

        // Drivers with a password set can access the shared panel (limited view)
        return in_array($this->role, ['driver', 'both']) && !is_null($this->password);
    }

    public function isAdmin(): bool
    {
        return (bool) $this->is_admin;
    }

    public function isDriver(): bool
    {
        return in_array($this->role, ['driver', 'both']);
    }

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

    protected function casts(): array
    {
        return [
            'phone_verified_at' => 'datetime',
            'password' => 'hashed',
            'is_verified' => 'boolean',
            'is_suspended' => 'boolean',
            'rating_avg' => 'decimal:2',
        ];
    }

    public function vehicles(): HasMany
    {
        return $this->hasMany(Vehicle::class);
    }

    public function tripsAsDriver(): HasMany
    {
        return $this->hasMany(Trip::class, 'driver_id');
    }

    public function bookingsAsRider(): HasMany
    {
        return $this->hasMany(Booking::class, 'rider_id');
    }

    public function strikes(): HasMany
    {
        return $this->hasMany(Strike::class);
    }

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

    public function reviewsGiven(): HasMany
    {
        return $this->hasMany(Review::class, 'reviewer_id');
    }

    public function reviewsReceived(): HasMany
    {
        return $this->hasMany(Review::class, 'reviewee_id');
    }

    public function tripCreditsLog(): HasMany
    {
        return $this->hasMany(TripCreditsLog::class);
    }

    public function creditPurchases(): HasMany
    {
        return $this->hasMany(\App\Models\CreditPurchase::class);
    }
}
