<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

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

    protected function nombres(): Attribute
    {
        return new Attribute(
            set: fn($value) => $value ? mb_strtoupper($value) : null
        );
    }

    protected function apellidos(): Attribute
    {
        return new Attribute(
            set: fn($value) => $value ? mb_strtoupper($value) : null
        );
    }

    protected function nombreCompleto(): Attribute
    {
        return new Attribute(
            set: fn($value) => $value ? mb_strtoupper($value) : null
        );
    }

    protected $fillable = [
        'nombres',
        'apellidos',
        'nombre_completo',
        'ci',
        'celular',
        'username',
        'email',
        'password',
        'habilitado',
        'rol_id',
    ];

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

    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
        'habilitado' => 'boolean',
    ];

    public function scopeSrol($query, $value, $prefijo = '')
    {
        if ($value) {
            return $query->where($prefijo . 'rol_id', $value);
        }

        return $query;
    }

    public function scopeSterm($query, $value, $prefijo = '')
    {
        $columns = ['nombre_completo', 'celular', 'email', 'ci'];

        if ($value) {
            $words_search = explode(' ', $value);

            return $query->where(function ($query) use ($columns, $prefijo, $words_search) {
                foreach ($words_search as $word) {
                    $query->where(function ($query) use ($columns, $prefijo, $word) {
                        foreach ($columns as $column) {
                            $query->orWhere($prefijo . $column, 'LIKE', '%' . $word . '%');
                        }
                    });
                }
            });
        }

        return $query;
    }

    public function rol()
    {
        return $this->belongsTo(Role::class, 'rol_id');
    }

    public function estudiante()
    {
        return $this->hasOne(Estudiante::class, 'user_id');
    }

    public function cursos()
    {
        return $this->hasMany(Curso::class, 'docente_id');
    }

    public function hasRole($role)
    {
        return $this->rol && $this->rol->name === $role;
    }

    public function evaluaciones()
    {
        return $this->hasMany(Evaluacion::class, 'docente_id');
    }
}
