<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

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

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'partner_id', // <-- Permite asignación masiva
        'is_active', // <-- Permite edición desde formularios
    ];

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

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'is_active' => 'boolean', // <-- Cast automático
        ];
    }

    public function partner()
    {
        return $this->belongsTo(Partner::class);
    }

    public function partnerInvites()
    {
        return $this->hasMany(PartnerInvite::class, 'user_id', 'id');
    }

    public function partners()
    {
        return $this->belongsToMany(Partner::class, 'partner_invites', 'user_id', 'partner_id')
            ->wherePivot('status', 'accepted');
    }

    public function allPartners()
    {
        return $this->belongsToMany(Partner::class, 'partner_invites', 'user_id', 'partner_id');
    }

    public function hasPartner($partnerId): bool
    {
        return $this->partners()->where('partner_id', $partnerId)->exists();
    }

    public function getPartnerIds(): array
    {
        return $this->partners()->pluck('partners.id')->toArray();
    }

    public function getPrimaryPartnerId()
    {
        return $this->partner_id;
    }

    public function getAllPartnerIds(): array
    {
        $primaryPartner = $this->getPrimaryPartnerId();
        $additionalPartners = $this->getPartnerIds();
        
        $allPartners = array_merge([$primaryPartner], $additionalPartners);
        return array_filter($allPartners); // Remover nulls
    }

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

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

    public function hasPermission(string $permissionName): bool
    {
        // Super admin tiene todos los permisos
        if ($this->hasRole('super-admin')) {
            return true;
        }
        return $this->roles()
            ->whereHas('permissions', function ($query) use ($permissionName) {
                $query->where('name', $permissionName);
            })
            ->exists();
    }

    public function isSuperAdmin(): bool
    {
        return $this->hasRole('super-admin');
    }

    public function isPartnerAdmin(): bool
    {
        return $this->hasRole('partner-admin');
    }
}
