<?php

namespace App\Models;

use App\Enums\Gender;
use App\Traits\HasApiTokenAuth;
use App\Traits\HasRoles;
use App\Traits\QueryScopeTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;

class Teacher extends Model
{
    use HasFactory, HasApiTokenAuth, HasRoles, QueryScopeTrait;

    protected $fillable = [
        'document_number',
        'names',
        'paternal_surname',
        'maternal_surname',
        'gender',
        'birth_date',
        'email',
        'phone_number',
        'photo_profile',
        'active',
        'password',
    ];

    // Columnas donde se puede buscar (texto general)
    public array $searchable = ['document_number', 'names', 'paternal_surname', 'maternal_surname', 'email'];

    // Columnas por las que se puede ordenar
    public array $sortable = ['id', 'document_number', 'names', 'paternal_surname', 'maternal_surname', 'email'];

    // Relaciones que se pueden incluir
    public array $allowedIncludes = [];

    // Columnas por las que se puede filtrar específicamente
    public array $filterable = ['document_number', 'names', 'paternal_surname', 'maternal_surname', 'email'];

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

    protected $appends = ['user_type', 'photo_profile_url'];

    protected $casts = [
        'token_expires_at' => 'datetime',
        'last_login_at' => 'datetime',
        'email_verified_at' => 'datetime',
        'active' => 'boolean',
        'birth_date' => 'date',
        'gender' => Gender::class,
    ];

    // Accessor para user_type (necesario para $appends)
    public function getUserTypeAttribute(): string
    {
        return 'teacher';
    }

    // Obtiene la URL completa de la foto de perfil
    public function getPhotoProfileUrlAttribute(): ?string
    {
        if (!$this->photo_profile) {
            return null;
        }

        // Si ya es una URL completa, retornarla
        if (filter_var($this->photo_profile, FILTER_VALIDATE_URL)) {
            return $this->photo_profile;
        }

        // Generar URL completa con el dominio del backend
        return url('storage/' . $this->photo_profile);
    }
}
