<?php

namespace Kylin\Guardian\Models;

use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Kylin\Core\Models\BaseModel;
use Kylin\User\Models\User;

/**
 * 监护人模型
 *
 * 游戏防沉迷系统监护人，关联被监护的未成年用户。
 */
class Guardian extends BaseModel
{
    protected $table = 'kylin_guardians';

    protected $fillable = [
        'user_id',
        'name',
        'phone',
        'id_card',
        'relationship',
        'verified',
        'verified_at',
    ];

    protected $hidden = [
        'id_card',
    ];

    protected $casts = [
        'verified' => 'boolean',
        'verified_at' => 'datetime',
    ];

    /**
     * 关联用户
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 关联绑定关系
     */
    public function bindings(): HasMany
    {
        return $this->hasMany(GuardianBinding::class);
    }

    /**
     * 是否已通过实名验证
     */
    public function isVerified(): bool
    {
        return $this->verified === true;
    }

    /**
     * 设置身份证号（加密存储）
     */
    public function setIdCardAttribute(?string $value): void
    {
        $this->attributes['id_card'] = $value
            ? encrypt($value)
            : null;
    }

    /**
     * 获取身份证号（解密读取）
     */
    public function getIdCardAttribute(?string $value): ?string
    {
        return $value ? decrypt($value) : null;
    }
}
