<?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 Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

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

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'title',
        'first_name',
        'last_name',
        'username',
        'email',
        'password',
        'phone',
        'address',
        'access_start',
        'access_end',
        'is_active',
        'profile_photo_path',
    ];

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

    /**
     * Get the attributes that should be cast.
     *
      * @var list<string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'access_start' => 'date',
        'access_end' => 'date',
        'is_active' => 'boolean'
    ];

    /**
     * Get the user's initials
     */
    public function initials(): string
    {
        /*return Str::of($this->name)
            ->explode(' ')
            ->map(fn (string $name) => Str::of($name)->substr(0, 1))
            ->implode('');*/
        return Str::of('');
    }

    public function groups()
    {
        return $this->belongsToMany(Group::class)
            ->withTimestamps()
            ->using(GroupUser::class);
    }

    public function hasPermissionThroughGroup($permission)
    {
        return $this->groups->flatMap(function ($group) {
            return $group->permissions;
        })->contains('name', $permission);
    }

    public function getAllPermissionsAttribute()
    {
        return $this->getAllPermissions()
            ->merge($this->groups->flatMap->permissions)
            ->unique('id');
    }

    public function hasAnyPermission($permissions): bool
    {
        return $this->hasPermissionTo($permissions) || 
               $this->groups->contains(function ($group) use ($permissions) {
                   return $group->hasAnyPermission($permissions);
               });
    }

    public function getFullNameAttribute()
    {
        return "{$this->title} {$this->first_name} {$this->last_name}";
    }

    // Accesor para la URL completa
    public function getProfilePhotoUrlAttribute()
    {
        return $this->profile_photo ? Storage::url($this->profile_photo) : asset('images/default-user.png');
    }

    public function companies(): BelongsToMany
    {
        return $this->belongsToMany(Company::class, 'company_contacts')
                    ->withPivot('position')
                    ->withTimestamps();
    }

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