<?php
declare(strict_types=1);

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

auth_require_login();

// --- テーブル準備（存在しなければ作成。軽量なのでこのページで実行） ---
try {
    $pdo = db();
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS news (
            id         INTEGER PRIMARY KEY AUTOINCREMENT,
            date       TEXT    NOT NULL,   -- YYYY-MM-DD
            title      TEXT    NOT NULL,
            url        TEXT    DEFAULT NULL,
            created_at TEXT    NOT NULL DEFAULT (datetime('now')),
            updated_at TEXT
        );
    ");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_news_date ON news(date)");
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS settings (
            key   TEXT PRIMARY KEY,
            value TEXT NOT NULL DEFAULT ''
        );
    ");
} catch (Throwable $e) {
    http_response_code(500);
    exit('DB migration failed.');
}

// --- 保存処理 ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check_or_die(); // 不正時は 400/終了（/security/_csrf.php 既定）

    $topLimit = max(1, min(999, (int)($_POST['top_limit'] ?? 3)));

    // rows: news[date][], news[title][], news[url][]
    $rows = [
        'date'  => array_values((array)($_POST['news']['date']  ?? [])),
        'title' => array_values((array)($_POST['news']['title'] ?? [])),
        'url'   => array_values((array)($_POST['news']['url']   ?? [])),
    ];
    $n = max(count($rows['date']), count($rows['title']), count($rows['url']));

    $data = [];
    for ($i = 0; $i < $n; $i++) {
        $d = trim((string)($rows['date'][$i]  ?? ''));
        $t = trim((string)($rows['title'][$i] ?? ''));
        $u = trim((string)($rows['url'][$i]   ?? ''));

        if ($t === '') continue; // タイトル空はスキップ
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $d)) {
            $d = date('Y-m-d');
        }
        // URLは空OK。空でなければ最大長をざっくり制限
        if ($u !== '') $u = mb_substr($u, 0, 1000, 'UTF-8');

        $data[] = ['date' => $d, 'title' => $t, 'url' => $u];
    }

    try {
        $pdo->beginTransaction();

        // 件数設定を保存（REPLACE）
        $stSet = $pdo->prepare('REPLACE INTO settings(key, value) VALUES(:k, :v)');
        $stSet->execute([':k' => 'NEWS_LIMIT', ':v' => (string)$topLimit]);

        // news を丸ごと入れ替え（シンプル運用）
        $pdo->exec('DELETE FROM news');

        if (!empty($data)) {
            $stIns = $pdo->prepare('INSERT INTO news(date,title,url,updated_at) VALUES(?,?,?,datetime("now"))');
            foreach ($data as $r) {
                $stIns->execute([$r['date'], $r['title'], ($r['url'] !== '' ? $r['url'] : null)]);
            }
        }

        $pdo->commit();
        $to = url_for('/admin/news.php', ['saved' => 1]);
        header('Location: ' . $to);
        exit;
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        http_response_code(500);
        exit('Save failed.');
    }
}

// --- 表示用読み込み ---
$pdo = db();

// NEWS_LIMIT（無ければ 3）
$topLimit = 3;
try {
    $st = $pdo->prepare('SELECT value FROM settings WHERE key = ? LIMIT 1');
    $st->execute(['NEWS_LIMIT']);
    $v = $st->fetchColumn();
    if (is_string($v) && $v !== '') $topLimit = max(1, min(999, (int)$v));
} catch (Throwable $e) {}

$news = [];
try {
    $st = $pdo->query('SELECT date, title, url FROM news ORDER BY date DESC, id DESC');
    $news = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (Throwable $e) {}

?><!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="<?= h(asset_url('/admin/assets/admin.css', true)) ?>">
</head>
<body class="admin news">
<?php include __DIR__ . '/_header.php'; ?>
<div id="container">

  <h1>お知らせ管理</h1>

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

  <form method="post" action="<?= h(url_for('/admin/news.php')) ?>">
    <?= csrf_input_tag() ?>

    <div class="mb3rem">
    <h2>表示する件数</h2>
      <div><input type="number" name="top_limit" value="<?= h((string)$topLimit) ?>" min="1" max="999" step="1"></div>
    </div>

    <h2>お知らせ投稿</h2>

    <div id="listArea">
      <?php if (!$news): ?>
        <div class="row">
          <div class="date"><input type="date" name="news[date][]" value=""></div>
          <div><input type="text" name="news[title][]" placeholder="タイトル"></div>
          <div><input type="text" name="news[url][]"   placeholder="リンク先があれば"></div>
          <div class="actions"><button type="button" class="btn js-del">削除</button></div>
        </div>
      <?php else: ?>
        <?php foreach ($news as $r): ?>
          <div class="row">
            <div class="date"><input type="date" name="news[date][]" value="<?= h((string)($r['date'] ?? '')) ?>"></div>
            <div><input type="text" name="news[title][]" value="<?= h((string)($r['title'] ?? '')) ?>" placeholder="タイトル"></div>
            <div><input type="text" name="news[url][]"   value="<?= h((string)($r['url'] ?? '')) ?>"   placeholder="リンク先があれば"></div>
            <div class="actions"><button type="button" class="btn js-del">削除</button></div>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>

    <!-- 下部 操作 -->
    <div><button type="button" id="addRow" class="btn mb1rem">＋ お知らせを追加</button></div>
    <div><button class="btn1" type="submit">保存する</button></div>
  </form>

</div>

<template id="tpl-row">
  <div class="row">
    <div class="date"><input type="date" name="news[date][]" value=""></div>
    <div><input type="text" name="news[title][]" placeholder="タイトル"></div>
    <div><input type="text" name="news[url][]"   placeholder="リンク先があれば"></div>
    <div class="actions"><button type="button" class="btn js-del">削除</button></div>
  </div>
</template>

<script>
(function(){
  const area = document.getElementById('listArea');
  const tpl  = document.getElementById('tpl-row');
  const add  = document.getElementById('addRow');

  function bindRow(row){
    const del = row.querySelector('.js-del');
    if (del) del.addEventListener('click', () => {
      row.parentNode.removeChild(row);
    });
  }

  // 既存行にも削除バインド
  Array.from(area.querySelectorAll('.row')).forEach(bindRow);

  add.addEventListener('click', () => {
    const node = document.importNode(tpl.content, true);
    const row  = node.querySelector('.row');
    area.insertBefore(node, area.firstChild);
    // 直後にフォーカス（タイトル）
    const first = area.querySelector('.row:first-child input[name="news[title][]"]');
    if (first) first.focus();
    bindRow(area.querySelector('.row:first-child'));
  });
})();
</script>

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