<?php
declare(strict_types=1);

/**
 * 通用属性类型模型，对应 attr_type 表
 */
class AttrType extends Model
{
    protected string $table = 'attr_type';
    protected string $key   = 'attr_type_id';

    /**
     * dxDataGrid 列表查询：父类 grid() 返回原始行，这里不需要 decode，
     * ext_schema 在 grid 里直接显示为 JSON 字符串（供 textarea 编辑）
     */

    /**
     * 供 attrValue 页面初始化时加载完整类型定义（ext_schema 已 decode 为数组）
     */
    public function listAll(): array
    {
        $rows = $this->db->select($this->table, '*', [
            'ORDER' => ['attr_type_sort' => 'ASC', 'attr_type_id' => 'ASC'],
        ]);

        foreach ($rows as &$row) {
            $row['attr_type_ext_schema'] = $row['attr_type_ext_schema']
                ? (json_decode($row['attr_type_ext_schema'], true) ?: null)
                : null;
        }

        return $rows;
    }

    /**
     * gridInsert/gridUpdate：ext_schema 从前端以 JSON 字符串传来，直接存；
     * 若前端误发了 array（框架解析 JSON body 时），重新 encode 回去
     */
    public function gridInsert(array $values): mixed
    {
        $this->normalizeSchema($values);
        return parent::gridInsert($values);
    }

    public function gridUpdate(mixed $key, array $values): int
    {
        $this->normalizeSchema($values);
        return parent::gridUpdate($key, $values);
    }

    private function normalizeSchema(array &$values): void
    {
        if (!array_key_exists('attr_type_ext_schema', $values)) {
            return;
        }

        $v = $values['attr_type_ext_schema'];

        if (is_array($v)) {
            $values['attr_type_ext_schema'] = json_encode($v, JSON_UNESCAPED_UNICODE);
        } elseif (is_string($v) && $v !== '') {
            // 验证是合法 JSON，不合法就清空（防止存入脏数据）
            if (json_decode($v) === null) {
                $values['attr_type_ext_schema'] = null;
            }
        } else {
            $values['attr_type_ext_schema'] = null;
        }
    }
}
