<?php

namespace App\Models;

use App\Traits\Auditable;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\ControlPhysicalExam;
use DateTime;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class ControlHistory extends Model
{
    use Auditable;
    use HasFactory;
    /**
     * The table associated with the model.
     * 
     * @var string
     */
    protected $table = 'control_history';

    /**
     * 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','history_id','users_id', 'summary','title', 'especiality', 'active', 'created_at', 'updated_at', 'diagnosis', 'cie_code'];

    /**
     * 
     */
    public function __construct(){
        parent::__construct();
        $this->createIdentification();
        $user =  Auth::user();
        if(isset($user)){
            $this->users_id = Auth::user()->id;
        }
    }
    
     /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function patient()
    {
        return $this->belongsTo('App\Models\Patients', 'patients_id');
    }

     /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function history()
    {
        return $this->belongsTo('App\Models\History', 'history_id');
    }

    /**
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
    public function user()
    {
        return $this->belongsTo('App\Models\User', 'users_id');
    }

    /**
     * 
     */
    public function createIdentification(){
        $date = new DateTime();
        $this->id = md5($date->getTimestamp());
    }

    
    public function especiality1()
    {
        return $this->belongsTo('App\Models\Especiality', 'especiality');
    }

    /**
     * 
     */
    public function getControlSectionHistory(){
       return DB::table("control_section_history")
       ->select("control_section_history.id","control_section_history.control_history_id","control_section_history.section_type_id","control_section_history.title","control_section_history.summary","control_section_history.created_at","control_section_history.updated_at")
       ->join("section_type","control_section_history.section_type_id","=","section_type.id")
       ->where("control_history_id",$this->id)
       ->orderBy("section_type.position")
       ->get();
    }

    /**
     * 
     */
    public function getControlPhyscalExam(){
        $controlPhysicalExam  = ControlPhysicalExam::where("control_history_id",$this->id)->get()->first();
        if($controlPhysicalExam === NULL) 
            return [];
        return json_decode($controlPhysicalExam->value, TRUE);
    }

    
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $lastId = DB::table($model->getTable())
                ->select(DB::raw('MAX(number_control) as max_id'))
                ->value('max_id');

            $newValue = $lastId ? ((int)$lastId + 1) : 1;

            $model->number_control = $newValue < 10000 
                ? str_pad($newValue, 4, "0", STR_PAD_LEFT)
                : (string)$newValue;
        });

          // --- Global Scope para filtrar por especialidad activa ---
          static::addGlobalScope('activeSpeciality', function ($builder) {
            // 'especiality' es el nombre del MÉTODO de la relación en este modelo.
            // Si tu método de relación se llama diferente, cámbialo aquí.
            $builder->whereHas('especiality1', function ($query) {
                // $query aquí se refiere a la consulta sobre la tabla de Especiality
                $query->where('active', 1); // Filtra las especialidades donde 'active' sea 1
            });
        });

         // Asegurar que solo se retornen especialidades activas por defecto
         static::addGlobalScope('active', function ($builder) {
            $builder->where('active', 1);
        });
    }

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