<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use App\Traits\Auditable;

class PatientCustomFieldValue extends Model
{
    use HasFactory;
    use Auditable;
    
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'patient_id',
        'field_id',
        'value',
        'updated_by'
    ];
    
    /**
     * Get the patient that owns this value.
     */
    public function patient(): BelongsTo
    {
        return $this->belongsTo(Patient::class);
    }
    
    /**
     * Get the custom field this value belongs to.
     */
    public function field(): BelongsTo
    {
        return $this->belongsTo(PatientCustomField::class, 'field_id');
    }
    
    /**
     * Get the user that last updated this value.
     */
    public function updatedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'updated_by');
    }
    
    /**
     * Get formatted value based on field type
     * 
     * @return mixed
     */
    public function getFormattedValue()
    {
        if (!$this->field) {
            return $this->value;
        }
        
        switch ($this->field->type) {
            case 'date':
                return !empty($this->value) ? date('Y-m-d', strtotime($this->value)) : null;
            case 'number':
                return is_numeric($this->value) ? (float) $this->value : $this->value;
            case 'checkbox':
                return (bool) $this->value;
            default:
                return $this->value;
        }
    }
}
