<?php

declare(strict_types=1);

namespace Kylin\ElderlyCare\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Kylin\ElderlyCare\Services\HealthDataEncryptor;
use Kylin\ElderlyCare\Traits\ElderlyCareAudit;

/**
 * 老人档案模型
 *
 * 依据《养老机构管理办法》第十七条，建立老年人健康档案。
 * 依据《个人信息保护法》第二十八条，身份证号等敏感信息加密存储。
 *
 * @property int    $id
 * @property string $name              姓名（加密）
 * @property string $id_card_encrypted 身份证号（加密）
 * @property string $gender            性别
 * @property string $birth_date        出生日期
 * @property string $phone             联系电话（加密）
 * @property string $emergency_contact 紧急联系人（加密）
 * @property string $emergency_phone   紧急联系电话（加密）
 * @property int    $care_level        护理等级 0-3
 * @property string $admission_date    入院日期
 * @property string $discharge_date    离院日期
 * @property string $status            状态: active/discharged
 */
class ElderlyProfile extends Model
{
    use ElderlyCareAudit;

    protected $table = 'kylin_elderly_profiles';

    protected $fillable = [
        'name',
        'id_card_encrypted',
        'gender',
        'birth_date',
        'phone',
        'emergency_contact',
        'emergency_phone',
        'care_level',
        'admission_date',
        'discharge_date',
        'status',
    ];

    protected function casts(): array
    {
        return [
            'birth_date' => 'date',
            'admission_date' => 'date',
            'discharge_date' => 'date',
            'care_level' => 'integer',
        ];
    }

    /**
     * 加密身份证号
     */
    public function setIdCardAttribute(string $value): void
    {
        $this->attributes['id_card_encrypted'] = HealthDataEncryptor::encrypt(['id_card' => $value]);
    }

    /**
     * 解密身份证号
     */
    public function getIdCardAttribute(): ?string
    {
        if (empty($this->id_card_encrypted)) {
            return null;
        }
        $data = HealthDataEncryptor::decrypt($this->id_card_encrypted);
        return $data['id_card'] ?? null;
    }

    public function assessments(): HasMany
    {
        return $this->hasMany(CareAssessment::class, 'elderly_id');
    }

    public function healthRecords(): HasMany
    {
        return $this->hasMany(HealthRecord::class, 'elderly_id');
    }

    public function medicationRecords(): HasMany
    {
        return $this->hasMany(MedicationRecord::class, 'elderly_id');
    }

    public function emergencyCalls(): HasMany
    {
        return $this->hasMany(EmergencyCall::class, 'elderly_id');
    }
}
