<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use HasApiTokens;

    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;
    use HasRoles;
    use HasProfilePhoto;

    protected $fillable = [
        'name',
        'apellidoPaterno',
        'apellidoMaterno',
        'email',
        'telefono',
        'direccion',
        'plantel',
        'password',
        'code',
        'status',
        'unsubscribe_token'
    ];


    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_recovery_codes',
        'two_factor_secret',
        'status',
    ];

    protected $appends = [
        'profile_photo_url',
    ];

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    protected function name(): Attribute
    {
        return Attribute::make(
            set: fn ($value) => strtoupper($value)
        );
    }

    protected function apellidoPaterno(): Attribute
    {
        return Attribute::make(
            set: fn ($value) => strtoupper($value)
        );
    }

    protected function apellidoMaterno(): Attribute
    {
        return Attribute::make(
            set: fn ($value) => strtoupper($value)
        );
    }


    // public function note() : HasOne
    // {
    //     //esta funcion es para retornar la relacion de un usario que contenga notas
    //     return $this->hasOne(Note::class);
    // }

    public function notes() : HasMany
    {
        return $this->hasMany(Note::class);
    }

    public function horarios() : HasMany
    {
        return $this->hasMany(Horario::class);
    }

    public function codes() : HasMany
    {
        return $this->hasMany(Code::class);
    }

    public function pagos() : HasMany
    {
        return $this->hasMany(Pago::class);
    }

    public function plantelUsuarios() : BelongsToMany
    {
        return $this->belongsToMany(Plantel::class)->withPivot('plantel_id');
    }

    public function existe($request = null)
    {
        if (!$request) {
            return false;
        }

        return $this->plantelUsuarios()
            ->wherePivot('plantel_id', $request)
            ->exists();
    }


    public function alumnos() : BelongsToMany
    {
        return $this->belongsToMany(Alumno::class);
    }

    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }

    public function sentFriendRequests(): HasMany
    {
        return $this->hasMany(Friendship::class, 'sender_id');
    }

    public function receivedFriendRequests(): HasMany
    {
        return $this->hasMany(Friendship::class, 'receiver_id');
    }

    public function friendshipWith(User $user): ?Friendship
    {
        return Friendship::where(function ($q) use ($user) {
                $q->where('sender_id', $this->id)->where('receiver_id', $user->id);
            })
            ->orWhere(function ($q) use ($user) {
                $q->where('sender_id', $user->id)->where('receiver_id', $this->id);
            })
            ->first();
    }

    public function isFriendWith(User $user): bool
    {
        $friendship = $this->friendshipWith($user);
        return $friendship?->status === 'accepted';
    }

    public function friendIds(): array
    {
        $sent     = Friendship::where('sender_id', $this->id)->where('status', 'accepted')->pluck('receiver_id');
        $received = Friendship::where('receiver_id', $this->id)->where('status', 'accepted')->pluck('sender_id');
        return $sent->merge($received)->unique()->values()->all();
    }

    protected static function booted()
    {
        static::creating(function ($user) {
            $user->unsubscribe_token ??= \Illuminate\Support\Str::uuid();
        });
    }

}
