<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DateTime;
use App\Models\SectionHistory;
use App\Models\PhysicalExam;
use App\Models\Especiality;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Traits\Auditable;
use \Exception;
/**
 * @property string $id
 * @property string $patients_id
 * @property string $summary
 * @property string $especiality
 * @property string $created_at
 * @property string $updated_at
 * @property Patient $patient
 */
class History extends Model
{
    use Auditable;

    public function __construct(){
        parent::__construct();
        $this->createIdentification();
        $user =  Auth::user();
        if(isset($user)){
            $this->users_id = Auth::user()->id;
        }
    }
    /**
     * The table associated with the model.
     * 
     * @var string
     */
    protected $table = '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','users_id','patients_id', 'summary','title', 'especiality', 'created_at', 'updated_at', 'cie_code', 'diagnosis'];


    /**
     * @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 user()
    {
        return $this->belongsTo('App\Models\User', 'users_id');
    }


    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function controlHistories()
    {
        return $this->hasMany('App\Models\ControlHistory', 'history_id');
    }

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

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

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

    public function getSectionHistoryValueById($sectionTypeId){
       
        try{
            $sectionHistory = SectionHistory::where("section_type_id", $sectionTypeId)
        ->where("history_id", $this->id)
        ->firstOrFail();        
        return $sectionHistory->summary;
       }catch(Exception $e){
            return "";
       }
    }

    public function getSectionTestValueById($key){
       try{
            $physicalExam  = PhysicalExam::where("history_id",$this->id)->get()->first();
            if($physicalExam === NULL) 
                return "";
            $data = json_decode($physicalExam->value, TRUE);
            return $data[$key];
       }catch(Exception $e){
            return "";
       }
    }

    /**
     * 
     */
    public function getPhyscalExam(){
        $physicalExam  = PhysicalExam::where("history_id",$this->id)->get()->first();
        if($physicalExam === NULL) 
            return [];
        return json_decode($physicalExam->value, TRUE);
    }

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

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

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

            $model->number_history = $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
            });
        });
    }

}
