<?php

namespace App\Models;

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

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

    protected $fillable = [
        'name', 'email', 'password', 'company', 'phone', 'country', 'state', 'address',
        'is_admin', 'is_active', 'last_login_at', 'last_login_ip', 'avatar', 'preferences',
    ];

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

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'is_admin' => 'boolean',
            'is_active' => 'boolean',
            'last_login_at' => 'datetime',
            'locked_until' => 'datetime',
            'preferences' => 'array',
        ];
    }

    public function licenses()
    {
        return $this->hasMany(License::class);
    }

    public function orders()
    {
        return $this->hasMany(Order::class);
    }

    public function invoices()
    {
        return $this->hasMany(Invoice::class);
    }

    public function downloads()
    {
        return $this->hasMany(Download::class);
    }

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

    public function supportTickets()
    {
        return $this->hasMany(SupportTicket::class);
    }

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

    public function preferredCurrencyCode(): ?string
    {
        return ($this->preferences ?? [])['currency'] ?? null;
    }

    public function setCurrencyPreference(string $code): void
    {
        $prefs             = $this->preferences ?? [];
        $prefs['currency'] = strtoupper($code);
        $this->update(['preferences' => $prefs]);
    }
}
