<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Alumno extends Model
{
    protected $guarded = [];

    protected $casts = [
        'opt_out'    => 'boolean',
        'opt_out_at' => 'datetime',
    ];

    public function existe($plantelId): bool
    {
        return $this->plantelUsuarios()
            ->where('plantels.id', $plantelId)
            ->exists();
    }

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

    public function usuario()
    {
        return $this->belongsToMany(User::class);
    }

    public function statusAlumno(): BelongsTo
    {
        return $this->belongsTo(AlumnoStatus::class, 'status');
    }

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

    public function plan()
    {
        return $this->belongsTo(Plan::class);
    }

    public function nivelRel()
    {
        return $this->belongsTo(Nivel::class, 'nivel');
    }

    public function documentos()
    {
        return $this->hasMany(Documento::class);
    }

    public function promociones(): BelongsToMany
    {
        return $this->belongsToMany(Promocion::class, 'alumno_promocion')
            ->withPivot(['enviado_at', 'status_envio', 'whatsapp_mensaje_id']);
    }

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

    public function telefonoWhatsapp(): ?string
    {
        $user = $this->alumnos()->first();
        return $user?->telefono;
    }

}
