<?php
declare(strict_types=1);

require_once __DIR__ . '/../auth/_auth.php';
require_once __DIR__ . '/../security/_csrf.php';

// 未ログインならログインへ
auth_require_login();

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../app/fields.php'; // 初回アクセスで fields テーブルを保証

// tpcms_h（未定義時のみ）
if (!function_exists('tpcms_h')) {
    function tpcms_h(string $s): string {
        return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

$pdo = db();

// id 取得・検証
$rawId = $_GET['id'] ?? '';
if (is_array($rawId)) $rawId = reset($rawId) ?: '';
if (!preg_match('/^\d+$/', (string)$rawId)) {
    http_response_code(400);
    $field = null;
} else {
    $st = $pdo->prepare('SELECT id, category_id, label, "key", type, required, searchable, list_visible, list_site, detail_site, sortable, unit, options FROM fields WHERE id = ?');
    $st->execute([(int)$rawId]);
    $field = $st->fetch(PDO::FETCH_ASSOC) ?: null;
}

// カテゴリ名（表示用）
$catName = $catSlug = '';
$catId = (int)($field['category_id'] ?? 0);
if ($catId > 0) {
    $cst = $pdo->prepare('SELECT name, slug FROM categories WHERE id = ?');
    $cst->execute([$catId]);
    if ($c = $cst->fetch(PDO::FETCH_ASSOC)) {
        $catName = (string)$c['name'];
        $catSlug = (string)$c['slug'];
    }
}

// 型の候補
$types = ['text','textarea','select','radio','checkbox','number','currency','date','assets','map_iframe'];

/* ---------- LD-03: update field (POST) ---------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $act = $_POST['_action'] ?? '';
    if ($act === 'update' && $field && $catId > 0) {
    csrf_check_or_die();
        $label   = trim((string)($_POST['label'] ?? ''));
        $key     = trim((string)($_POST['key'] ?? ''));
        $type    = trim((string)($_POST['type'] ?? ''));
        $unit    = trim((string)($_POST['unit'] ?? ''));
        $options = (string)($_POST['options'] ?? '');

        // flags
        $required   = !empty($_POST['required'])     ? 1 : 0;
        $searchable = !empty($_POST['searchable'])   ? 1 : 0;
        $listVis    = !empty($_POST['list_visible']) ? 1 : 0;
        $sortable   = !empty($_POST['sortable'])     ? 1 : 0;
        $listSite   = !empty($_POST['list_site'])    ? 1 : 0;
        $detailSite = !empty($_POST['detail_site'])  ? 1 : 0;

        if (!in_array($type, ['number','currency','date'], true)) { $sortable = 0; }

        // validate
        if ($label === '' || $key === '' || !preg_match('/^[A-Za-z0-9_-]+$/', $key) || !in_array($type, $types, true)) {
            header('Location: ./fields_edit.php?id='.(string)$field['id']);
            exit;
        }

        // unique (category_id, "key") except self
        $st = $pdo->prepare('SELECT 1 FROM fields WHERE category_id = ? AND "key" = ? AND id <> ? LIMIT 1');
        $st->execute([$catId, $key, (int)$field['id']]);
        if ($st->fetchColumn()) {
            header('Location: ./fields_edit.php?id='.(string)$field['id']);
            exit;
        }

        // update
        $up = $pdo->prepare('UPDATE fields
            SET label = ?, "key" = ?, type = ?, required = ?, searchable = ?, list_visible = ?, list_site = ?, detail_site = ?, sortable = ?, unit = ?, options = ?
            WHERE id = ?');
        $up->execute([
            $label, $key, $type,
            $required, $searchable, $listVis, $listSite, $detailSite, $sortable,
            ($unit !== '' ? $unit : null),
            fields_normalize_options($type, $options),
            (int)$field['id']
        ]);

        header('Location: ./fields.php?cat='.(string)$catId.'&ok=1');
        exit;
    }
}

?><!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>項目の編集｜Template Party CMS</title>
<link rel="stylesheet" href="./assets/admin.css">
</head>
<body class="admin fields">

<header>
  <div>
    <a href="./">ダッシュボード</a>
    <a href="../" target="_blank" rel="noopener">公開側トップ</a>
  </div>
  <div>
    <a href="./logout.php">ログアウト</a>
  </div>
</header>

<div id="container">

  <h1>項目の編集</h1>

  <?php if (!$field): ?>
    <p>対象の項目が見つかりませんでした。</p>
    <p><a class="btn" href="./fields.php">項目一覧へ戻る</a></p>
  <?php else: ?>
    <div class="mb1rem">
      <a class="btn" href="./fields.php?cat=<?= tpcms_h((string)$catId) ?>">← 項目一覧へ戻る</a>
    </div>

    <div class="row">
      <span class="label">カテゴリ</span>
      <div><?= tpcms_h($catName) ?> (<?= tpcms_h($catSlug) ?>)</div>
    </div>

    <form method="post" action="./fields_edit.php?id=<?= tpcms_h((string)$field['id']) ?>">
    <?= csrf_input_tag() ?>
      <input type="hidden" name="_action" value="update">

      <div class="row">
        <label class="label" for="f_label">ラベル</label>
        <input class="input" type="text" id="f_label" name="label" value="<?= tpcms_h((string)$field['label']) ?>" required>
      </div>

      <div class="row">
        <label class="label" for="f_key">キー</label>
        <input class="input" type="text" id="f_key" name="key" value="<?= tpcms_h((string)$field['key']) ?>" pattern="[A-Za-z0-9_-]+" required>
      </div>

      <div class="row">
        <label class="label" for="f_type">型</label>
        <select class="input" id="f_type" name="type" required>
          <?php
            // 英語キー => 表示ラベル（valueは英語キーのまま保持）
            $typeLabels = [
              'text'       => '１行テキスト入力（text）',
              'textarea'   => '複数行テキスト入力（textarea）',
              'select'     => 'プルダウン（select）',
              'radio'      => 'ラジオボタン（radio）',
              'checkbox'   => 'チェックボックス（checkbox）',
              'number'     => '数値（number）',
              'currency'   => '金額（currency）',
              'date'       => '日付（date）',
              'assets'     => '画像・動画（assets）',
              'map_iframe' => 'Google Map のiframe地図埋め込み（map_iframe）',
            ];
            foreach ($types as $t):
              $label = (string)($typeLabels[$t] ?? $t);
          ?>
            <option value="<?= tpcms_h($t) ?>" <?= ($t === (string)$field['type'] ? 'selected' : '') ?>><?= tpcms_h($label) ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="row block">
        <label class="label">フラグ</label>
        <label><input type="checkbox" name="searchable"   value="1" <?= ((int)$field['searchable']   === 1 ? 'checked' : '') ?>> 検索：サイト側のキーワード／絞り込みの対象にする</label>
        <label><input type="checkbox" name="list_visible" value="1" <?= ((int)$field['list_visible'] === 1 ? 'checked' : '') ?>> 一覧（管理）：管理ページのデータ一覧の表に列を追加（最大3列）</label>
        <label><input type="checkbox" name="list_site"    value="1" <?= ((int)($field['list_site']    ?? 0) === 1 ? 'checked' : '') ?>> 一覧（サイト）：一覧ページに出力させる</label>
        <label><input type="checkbox" name="detail_site"  value="1" <?= ((int)($field['detail_site']  ?? 0) === 1 ? 'checked' : '') ?>> 詳細（サイト）：詳細ページに出力させる</label>
      </div>

      <div class="row">
        <label class="label" for="f_unit">単位</label>
        <input class="input" type="text" id="f_unit" name="unit" value="<?= tpcms_h((string)($field['unit'] ?? '')) ?>">
      </div>

      <div class="row">
        <label class="label" for="f_options">options（選択肢や制約）</label>
        <textarea class="input" id="f_options" name="options"><?= tpcms_h(fields_options_to_human((string)$field['type'], (string)($field['options'] ?? ''))) ?></textarea>
      </div>

      <div>
        <button class="btn1 mb1rem" type="submit">保存する</button>
        <a class="btn" href="./fields.php?cat=<?= tpcms_h((string)$catId) ?>">キャンセル</a>
      </div>
    </form>
  <?php endif; ?>

</div><!-- /#container -->

<script src="./assets/admin.js"></script>

<script>
(function(){
  var type  = document.getElementById('f_type');
  var chk   = document.querySelector('input[name="searchable"]');
  if(!type || !chk) return;
  var label = chk.closest('label');
  var disableOn = ['assets','map_iframe'];

  function update(){
    var ok = disableOn.indexOf(type.value) === -1; // assets / map_iframe 以外はOK
    chk.disabled = !ok;
    if(!ok){ chk.checked = false; }
    if(label){
      label.style.opacity = ok ? '1' : '0.5';
      label.title = ok ? '' : 'この型では「検索」は使えません';
    }
  }
  type.addEventListener('change', update);
  update();
})();
</script>

<script>
(function(){
  var type  = document.getElementById('f_type');
  var chk   = document.querySelector('input[name="sortable"]');
  if(!type || !chk) return;
  var label = chk.closest('label');

  function update(){
    var ok = ['number','currency','date'].indexOf(type.value) !== -1;
    chk.disabled = !ok;
    if(!ok){ chk.checked = false; }
    if(label){
      label.style.opacity = ok ? '1' : '0.5';
      label.title = ok ? '' : 'この型では「並替」は使えません';
    }
  }
  type.addEventListener('change', update);
  update();
})();
</script>

</body>
</html>
