<?php

namespace App\Models;

use App\Models\MemberPoint;
use Database\Factories\UserFactory;
use Filament\Models\Contracts\FilamentUser;
use Filament\Panel;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;

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

    protected $fillable = [
        'name', 'email', 'password',
        'phone', 'address', 'division_id',
        'status', 'inactive_reason', 'last_activity_date',
    ];

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

    protected $casts = [
        'email_verified_at'  => 'datetime',
        'password'           => 'hashed',
        'last_activity_date' => 'date',
    ];

    public function division(): BelongsTo
    {
        return $this->belongsTo(Division::class);
    }

    public function activities(): BelongsToMany
    {
        return $this->belongsToMany(Activity::class, 'activity_member')
            ->withPivot('status', 'notes');
    }

    public function statusLogs(): HasMany
    {
        return $this->hasMany(MemberStatusLog::class, 'member_id');
    }

    public function cashRecords(): HasMany
    {
        return $this->hasMany(CashRecord::class, 'created_by');
    }

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

    public function totalPoints(): int
    {
        return $this->points()->sum('points');
    }

    public function canAccessPanel(Panel $panel): bool
    {
        return $this->status === 'aktif';
    }

    public function canImpersonate(): bool
    {
        return $this->hasRole('super_admin');
    }

    public function canBeImpersonated(): bool
    {
        return ! $this->hasRole('super_admin');
    }
}
