<?php
/** @var string $table @var array $cols @var string $pk @var array|null $row @var string $mode */
$isEdit = $mode === 'edit';
$action = $isEdit
    ? site_url('admin/db/update/' . $table . '/' . rawurlencode($row[$pk]))
    : site_url('admin/db/store/' . $table);
?>
<div class="page-head">
  <div>
    <h1><?php echo $isEdit ? '编辑记录' : '新增记录'; ?></h1>
    <div class="desc">表：<code><?php echo e($table); ?></code>　主键：<code><?php echo e($pk); ?></code></div>
  </div>
  <a class="btn-soft" href="<?php echo site_url('admin/db/browse/' . $table); ?>">← 返回列表</a>
</div>

<div class="admin-card db-form-card">
  <form method="post" action="<?php echo $action; ?>">
    <?php foreach ($cols as $c): ?>
      <?php
        $f = $c['Field'];
        $autoInc = ($c['Extra'] ?? '') === 'auto_increment';
        if ($autoInc && !$isEdit) continue; // 自增主键在新增时由数据库生成
        $val = $row !== null ? ($row[$f] ?? '') : '';
        $isPk = $f === $pk;
        $long = (bool)preg_match('/(text|blob|json)/i', $c['Type']);
        $required = $c['Null'] === 'NO' && $c['Default'] === null && !$autoInc;
      ?>
      <div class="form-row">
        <label>
          <span class="form-label"><?php echo e($f); ?>
            <?php if ($isPk): ?><span class="tag-mini tag-amber">PK</span><?php endif; ?>
            <?php if ($c['Null'] === 'YES'): ?><span class="tag-mini tag-gray">可空</span><?php endif; ?>
            <em class="form-type"><?php echo e($c['Type']); ?></em>
          </span>
          <?php if ($isPk && $isEdit): ?>
            <input type="hidden" name="<?php echo e($f); ?>" value="<?php echo e($val); ?>" />
            <input class="input" type="text" value="<?php echo e($val); ?>" disabled />
          <?php elseif ($long): ?>
            <textarea class="input" name="<?php echo e($f); ?>" rows="4" <?php echo $required ? 'required' : ''; ?>><?php echo e($val); ?></textarea>
          <?php else: ?>
            <input class="input" type="text" name="<?php echo e($f); ?>" value="<?php echo e($val); ?>" <?php echo $required ? 'required' : ''; ?> />
          <?php endif; ?>
        </label>
      </div>
    <?php endforeach; ?>

    <div class="form-actions">
      <button class="btn-primary" type="submit"><?php echo $isEdit ? '保存修改' : '创建记录'; ?></button>
      <a class="btn-soft" href="<?php echo site_url('admin/db/browse/' . $table); ?>">取消</a>
    </div>
  </form>
</div>
