<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Area extends Model
{
    use HasFactory;

    protected $table = 'areas';

    protected $fillable = [
        'nombre',
        'codigo',
        'activo',
    ];

    protected $casts = [
        'activo' => 'boolean',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];


    public function examenes()
    {
        return $this->belongsToMany(
            Examen::class,
            'examen_area',
            'area_id',
            'examen_id'
        )->withTimestamps();
    }


    public function scopeActivas($query)
    {
        return $query->where('activo', true);
    }

    public function scopeInactivas($query)
    {
        return $query->where('activo', false);
    }

    public function scopePorCodigo($query, $codigo)
    {
        return $query->where('codigo', strtoupper($codigo));
    }

    public function scopePorNombre($query, $nombre)
    {
        return $query->where('nombre', 'like', "%{$nombre}%");
    }

    public function scopeDeAcademia($query, $academiaId)
    {
        return $query->where('academia_id', $academiaId);
    }

    /* ================= ACCESSORS ================= */

    public function getEstadoAttribute()
    {
        return $this->activo ? 'Activo' : 'Inactivo';
    }

    public function getEstadisticasAttribute()
    {
        return [
            'total_cursos' => $this->cursos()->count(),
            'total_examenes' => $this->examenes()->count(),
        ];
    }

    public function getCursosCountAttribute()
    {
        return $this->cursos()->count();
    }

    public function getExamenesCountAttribute()
    {
        return $this->examenes()->count();
    }

    public function cursos()
    {
        return $this->belongsToMany(Curso::class, 'area_curso')->withTimestamps();
    }

    public function procesos()
    {
        return $this->belongsToMany(Proceso::class, 'area_proceso')
                    ->withPivot('id')
                    ->withTimestamps();
    }


    

}
