<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Storage;

class User extends Authenticatable
{
    use HasFactory, Notifiable, SoftDeletes;

    protected $fillable = [
        'company_id','name','username','email','designation','password',
        'phone','avatar','is_admin','is_active','force_password_change',
    ];

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

    protected $casts = [
        'is_admin'              => 'boolean',
        'is_active'             => 'boolean',
        'force_password_change' => 'boolean',
        'last_login_at'         => 'datetime',
        'password_changed_at'   => 'datetime',
    ];

    // Per-request permission cache to avoid repeated DB hits
    private array $_permCache = [];

    // ── Relationships ─────────────────────────────────────────────────────────
    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'user_roles');
    }

    // ── Permission Check (cached per request) ─────────────────────────────────
    public function hasPermission(string $module, string $action): bool
    {
        if ($this->is_admin) return true;

        $key = "{$module}.{$action}";
        if (isset($this->_permCache[$key])) {
            return $this->_permCache[$key];
        }

        $result = $this->roles()
            ->with('permissions')
            ->get()
            ->flatMap(fn($role) => $role->permissions)
            ->contains(fn($perm) => $perm->module === $module && $perm->action === $action);

        return $this->_permCache[$key] = $result;
    }

    public function hasRole(string $roleName): bool
    {
        return $this->roles()->where('name', $roleName)->exists();
    }

    // ── Scopes ────────────────────────────────────────────────────────────────
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    // ── Accessors ─────────────────────────────────────────────────────────────
    public function getAvatarUrlAttribute(): string
    {
        if ($this->avatar && Storage::disk('public')->exists($this->avatar)) {
            $version = Storage::disk('public')->lastModified($this->avatar);

            return asset('storage/' . $this->avatar) . '?v=' . $version;
        }

        return 'https://ui-avatars.com/api/?name=' . urlencode($this->name)
            . '&color=1B4F8A&background=EBF3FB&size=64';
    }

    public function getDisplayDesignationAttribute(): string
    {
        if (filled($this->designation)) {
            return $this->designation;
        }

        if ($this->is_admin) {
            return 'Administrator';
        }

        $role = $this->roles()->orderBy('name')->value('name');

        return $role ?: 'User';
    }
}
