<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class User extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable, HasApiTokens, SoftDeletes, LogsActivity;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'email',
        'phone',
        'password',
        'role_id',
        'is_owner',
        'last_login_at',
        'last_login_ip',
        'last_login_user_agent',
        'two_factor_enabled',
        'two_factor_secret',
        'password_changed_at',
        'force_password_change',
        'login_attempts',
        'locked_until',
        'remember_token',
        'deactivated_at'
    ];

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

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'is_owner' => 'boolean',
            'last_login_at' => 'datetime',
            'locked_until' => 'datetime',
            'password_changed_at' => 'datetime',
            'two_factor_enabled' => 'boolean',
            'force_password_change' => 'boolean',
            'deactivated_at' => 'datetime'
        ];
    }

    /**
     * Get the options for the activity log.
     *
     * @return \Spatie\Activitylog\LogOptions
     */
    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logAll()
            ->dontSubmitEmptyLogs();
    }

    public function role()
    {
        return $this->belongsTo(Role::class);
    }

    public function isAdmin(): bool
    {
        return $this->role?->isAdmin() ?? false;
    }

    public function isOperation(): bool
    {
        return $this->role?->isOperation() ?? false;
    }

    public function isCustomer(): bool
    {
        return $this->role?->isCustomer() ?? false;
    }

    public function isOwner(): bool
    {
        return $this->is_owner;
    }

    public function hasDashboardAccess(): bool
    {
        return $this->isAdmin() || $this->isOperation();
    }

    public function hasRole($roles): bool
    {
        if (is_array($roles)) {
            return in_array($this->role->slug, $roles);
        }
        return $this->role->slug === $roles;
    }

    public function incrementLoginAttempts(): void
    {
        $this->login_attempts++;
        
        // Lock account after 5 failed attempts
        if ($this->login_attempts >= 5) {
            $this->locked_until = Carbon::now()->addMinutes(30);
        }
        
        $this->save();
    }

    public function isLocked(): bool
    {
        return $this->locked_until && $this->locked_until > now();
    }

    public function requiresPasswordChange(): bool
    {
        return $this->force_password_change || 
               ($this->password_changed_at && $this->password_changed_at->diffInDays(now()) > 90);
    }

    public function updateLastLogin(Request $request): void
    {
        $this->update([
            'last_login_at' => now(),
            'last_login_ip' => $request->ip(),
            'last_login_user_agent' => $request->userAgent(),
        ]);
    }
}
