<?php
declare(strict_types=1);

require_once __DIR__ . '/../helpers.php';
require_once __DIR__ . '/../auth/_auth.php';
require_once __DIR__ . '/../db.php';

auth_require_login();         // 要ログイン
db_migrate_settings();        // settings テーブルを用意

// CSRF トークン準備
if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); }
if (empty($_SESSION['_csrf'])) { $_SESSION['_csrf'] = bin2hex(random_bytes(32)); }
$csrfToken = (string)($_SESSION['_csrf'] ?? '');

// 既定値
$defaults = [
    'SHOW_FEATURE'  => '0',   // 0:OFF / 1:ON
    'FEATURE_TOPIC' => '',
    'FEATURE_TITLE' => '',
    'FEATURE_DESC'  => '',
    'FEATURE_LIMIT' => '8',
    'NEW_DAYS'      => '7',
    'UP_DAYS'       => '7',
];

// 現在値を読込
$pdo = db();
$S = $defaults;
try {
    $in = implode(',', array_fill(0, count($defaults), '?'));
    $st = $pdo->prepare('SELECT key, value FROM settings WHERE key IN ('.$in.')');
    $st->execute(array_keys($defaults));
    foreach ($st->fetchAll(PDO::FETCH_ASSOC) ?: [] as $r) {
        $k = (string)($r['key'] ?? '');
        $v = (string)($r['value'] ?? '');
        if ($k !== '') $S[$k] = $v;
    }
} catch (\Throwable $e) {
    // 初回未作成などは既定値のまま
}

// 保存処理
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrfPost = (string)($_POST['_csrf'] ?? '');
    if ($csrfPost === '' || !hash_equals($csrfToken, $csrfPost)) {
        header('Location: ./site_settings.php?err=' . rawurlencode('フォームの有効期限が切れました。もう一度お試しください。'));
        exit;
    }

    // 受取＆バリデーション
    $show   = ((string)($_POST['show_feature'] ?? '0') === '1') ? '1' : '0';
    $topic  = trim((string)($_POST['feature_topic'] ?? ''));
    $title  = trim((string)($_POST['feature_title'] ?? ''));
    $desc   = trim((string)($_POST['feature_desc']  ?? ''));
    $limit  = (int)($_POST['feature_limit'] ?? 8);  if ($limit < 1) $limit = 1; if ($limit > 100) $limit = 100;
    $newD   = (int)($_POST['new_days'] ?? 7);       if ($newD < 0) $newD = 0;   if ($newD > 60)  $newD = 60;
    $upD    = (int)($_POST['up_days']  ?? 7);       if ($upD  < 0) $upD  = 0;   if ($upD  > 60)  $upD  = 60;

    // 保存（UPSERT）
    $pairs = [
        'SHOW_FEATURE'  => $show,
        'FEATURE_TOPIC' => $topic,
        'FEATURE_TITLE' => $title,
        'FEATURE_DESC'  => $desc,
        'FEATURE_LIMIT' => (string)$limit,
        'NEW_DAYS'      => (string)$newD,
        'UP_DAYS'       => (string)$upD,
    ];
    try {
        $pdo->beginTransaction();
        $stmt = $pdo->prepare('INSERT OR REPLACE INTO settings(key, value) VALUES(?, ?)');
        foreach ($pairs as $k => $v) { $stmt->execute([$k, (string)$v]); }
        $pdo->commit();
    } catch (\Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        header('Location: ./site_settings.php?err=' . rawurlencode('保存に失敗しました。'));
        exit;
    }

    header('Location: ./site_settings.php?ok=1');
    exit;
}

// 表示用に $S を更新（DB読み＋既定値マージ済み）
?><!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>NEW/UPアイコン・特集の設定｜Template Party CMS</title>
  <link rel="stylesheet" href="<?= h(asset_url('/admin/assets/admin.css', true)) ?>">
</head>
<body class="admin settings">
<?php include __DIR__ . '/_header.php'; ?>

<div id="container">
  <h1>NEW/UPアイコン・特集の設定</h1>

  <?php if ((string)($_GET['ok'] ?? '') === '1'): ?>
    <p class="ok">保存しました。</p>
  <?php elseif (($msg = (string)($_GET['err'] ?? '')) !== ''): ?>
    <p class="err"><?= h($msg) ?></p>
  <?php endif; ?>

  <form method="post" action="./site_settings.php">
    <input type="hidden" name="_csrf" value="<?= h($csrfToken) ?>">

  <h2>NEW/UPアイコンの設定</h2>
  <p class="small">NEW が出ている間は、UP は出ません。0 と入力すればアイコンは出なくなります。</p>

    <div class="row">
      <div class="label">NEW 日数（NEW_DAYS）</div>
      <input class="input-default" style="width:8rem" type="number" name="new_days" min="0" max="60" step="1" value="<?= (int)$S['NEW_DAYS'] ?>">
    </div>

    <div class="row 3rem">
      <div class="label">UP 日数（UP_DAYS）</div>
      <input class="input-default" style="width:8rem" type="number" name="up_days" min="0" max="60" step="1" value="<?= (int)$S['UP_DAYS'] ?>">
    </div>

  <h2>特集の設定</h2>

    <div class="row">
      <div class="label">特集の表示</div>
      <label><input class="input-default" type="radio" name="show_feature" value="1" <?= ($S['SHOW_FEATURE']==='1'?'checked':'') ?>> ON</label>
      <label><input class="input-default" type="radio" name="show_feature" value="0" <?= ($S['SHOW_FEATURE']!=='1'?'checked':'') ?>> OFF</label>
      <p class="small">※ OFF を選択すると、トップの特集ブロックが非表示になります。</p>
    </div>

    <div class="row">
      <div class="label">特集コード（FEATURE_TOPIC）</div>
      <input type="text" name="feature_topic" value="<?= h($S['FEATURE_TOPIC']) ?>" placeholder="例：spring2025">
      <p class="small">項目設計の <code>PICKUP_TOPIC</code> に一致したデータのみ表示します。</p>
    </div>

    <div class="row">
      <div class="label">特集見出し（FEATURE_TITLE）</div>
      <input type="text" name="feature_title" value="<?= h($S['FEATURE_TITLE']) ?>">
    </div>

    <div class="row">
      <div class="label">特集説明（FEATURE_DESC）</div>
      <textarea name="feature_desc" rows="4"><?= h($S['FEATURE_DESC']) ?></textarea>
    </div>

    <div class="row">
      <div class="label">表示件数（FEATURE_LIMIT）</div>
      <input class="input-default" style="width:8rem" type="number" name="feature_limit" min="1" max="100" step="1" value="<?= (int)$S['FEATURE_LIMIT'] ?>">
    </div>

    <p><button type="submit" class="btn1">保存する</button></p>
  </form>

</div>

<script src="<?= h(asset_url('/admin/assets/admin.js', true)) ?>"></script>
</body>
</html>
