<?php

namespace App\Models;

use App\Traits\Auditable;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\PhysicalTest\PhysicalTest;
use App\Models\HistoryConfiguration;
use App\Models\SectionType;

class Especiality extends Model
{
    use Auditable;
    use HasFactory;
    protected $table = 'especiality';
     /**
     * The "type" of the auto-incrementing ID.
     * 
     * @var string
     */
    protected $keyType = 'string';

    /**
     * Indicates if the IDs are auto-incrementing.
     * 
     * @var bool
     */
    public $incrementing = false;

    /**
     * @var array
     */
    protected $fillable = ['id','name','active','created_at', 'updated_at'];

    /**
     * Boot the model.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();
        
        // Asegurar que solo se retornen especialidades activas por defecto
        static::addGlobalScope('active', function ($builder) {
            $builder->where('active', 1);
        });
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function appointments()
    {
        return $this->hasMany('App\Models\Appointments', 'especiality');
    }
    
    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function histories()
    {
        return $this->hasMany('App\Models\History', 'especiality');
    }

    /**
     * Obtener todas las especialidades activas
     */
    public static function getEspecialities(){
        $especialties = [];
        foreach(self::where('active', 1)->get() as $especiality){
            $especialties[$especiality->id] = strtoupper($especiality->name);
        }
        return $especialties;
    }

    /**
     * Obtener todas las especialidades (incluyendo inactivas)
     */
    public static function getAllEspecialities(){
        $especialties = [];
        foreach(self::withoutGlobalScope('active')->get() as $especiality){
            $especialties[$especiality->id] = strtoupper($especiality->name);
        }
        return $especialties;
    }

    /**
     * Marcar una especialidad como inactiva
     */
    public function inactive(){
        $this->active = 0;
        return $this->save();
    }

    /**
     * Marcar una especialidad como inactiva
     */
    public function active(){
        $this->active = 1;
        return $this->save();   
    }


    public function createHistoryConfiguration(){
         // Obtener los exámenes médicos del PhysicalTest
         $physicalTest = new PhysicalTest();
         $fields = $physicalTest->getFields();
         $st = [];
         $medicalExams = [];

         // Buscar o crear la configuración para la especialidad
         $configuration = HistoryConfiguration::firstOrNew(['especiality_id' => $this->id]);
         
         // Generar ID si es nuevo
         if (!$configuration->exists) {
             $configuration->id = md5(uniqid($this->id, true));
         }


         $sectionTypes = SectionType::whereNotNull('section_type_id')->get();
         foreach($sectionTypes as $sectionType){
             $st[] =  $sectionType->id;
         }
         foreach ($fields as $key => $value) {
            $medicalExams[] = $key;
        }

         $configuration->section_types = $st;
         $configuration->medical_exams = $medicalExams;
         $configuration->save();
    }
}
