<?php
declare(strict_types=1);

require_once __DIR__ . '/_auth.php';
tpcms_require_admin();

require_once __DIR__ . '/../config.php';

// --- JSONユーティリティ（存在しなければ定義） ---
if (!function_exists('tpcms_json_read')) {
    function tpcms_json_read(string $path, $default = []) {
        if (is_file($path)) {
            $json = file_get_contents($path);
            $data = json_decode((string)$json, true);
            if (is_array($data) || is_object($data)) return $data;
        }
        return $default;
    }
}
if (!function_exists('tpcms_json_write')) {
    function tpcms_json_write(string $path, $data): bool {
        $dir = dirname($path);
        if (!is_dir($dir) && !@mkdir($dir, 0777, true)) return false;
        $json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
        if ($json === false) return false;
        $tmp = $path . '.tmp';
        if (@file_put_contents($tmp, $json) === false) return false;
        @chmod($tmp, 0664);
        $ok = @rename($tmp, $path);
        if (!$ok) { @unlink($tmp); return false; }
        @chmod($path, 0664);
        clearstatcache(true, $path);
        return true;
    }
}

$newsPath = __DIR__ . '/../data/news.json';
$default  = ['items' => [], 'top_limit' => 5, 'archive_url' => ''];
$current  = tpcms_json_read($newsPath, $default);
if (!is_array($current)) $current = $default;

// --- 保存処理 ---
$notice = null; $error = null; $ignored = 0;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
tpcms_require_post_csrf();
    $posted = $_POST['items'] ?? [];
    $items  = [];

    if (is_array($posted)) {
        foreach ($posted as $row) {
            if (!is_array($row)) continue;

            $date  = is_scalar($row['date']  ?? null) ? trim((string)$row['date'])  : '';
            $title = is_scalar($row['title'] ?? null) ? trim((string)$row['title']) : '';
            $url   = is_scalar($row['url']   ?? null) ? trim((string)$row['url'])   : '';

            // 空行は無視（title必須）
            if ($title === '') { $ignored++; continue; }

            // 日付：YYYY-MM-DD 形式、空なら本日
            if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
                $date = date('Y-m-d');
            }

            // URL：内部リンクは相対で保持（先頭 / は除去）、外部は http(s):// を許可
            if ($url !== '') {
                if (preg_match('#^https?://#i', $url)) {
                    // 外部URLはそのまま
                } else {
                    // 例：news/xxxx, company（先頭スラッシュは外す）
                    $url = ltrim($url, '/');
                }
            }

            $items[] = ['date' => $date, 'title' => $title, 'url' => $url];
        }
    }

    // 追加設定（top_limit / archive_url）
    $topLimit = 0;
    if (isset($_POST['top_limit']) && is_scalar($_POST['top_limit'])) {
        $n = (int)$_POST['top_limit']; if ($n < 1) $n = 1; if ($n > 999) $n = 999;
        $topLimit = $n;
    }
    $archiveUrl = is_scalar($_POST['archive_url'] ?? null) ? trim((string)$_POST['archive_url']) : '';
    if ($archiveUrl !== '') {
        if (preg_match('#^https?://#i', $archiveUrl)) {
            // 外部URLはそのまま
        } else {
            // 相対で保存（例：news）※先頭スラッシュは外す
            $archiveUrl = ltrim($archiveUrl, '/');
        }
    }

    // 既存の未知キーは温存しつつ items を上書き
    $updated = $current;
    usort($items, function($a,$b){ return strcmp(($b['date'] ?? ''), ($a['date'] ?? '')); });
    $updated['top_limit']  = $topLimit;
    $updated['archive_url'] = $archiveUrl;
    $updated['items'] = $items;

    if (tpcms_json_write($newsPath, $updated)) {
        $current = $updated;
        $notice = '保存しました。' . ($ignored ? "（空行 {$ignored} 件は保存対象外）" : '');
    } else {
        $error = '保存に失敗しました。権限やディスク容量を確認してください。';
    }
}

// --- 表示用 ---
$items = [];
$__src = is_array($current['items'] ?? null) ? $current['items'] : [];
if (is_array($__src)) {
    usort($__src, function($a,$b){ return strcmp(($b['date'] ?? ''), ($a['date'] ?? '')); });
    foreach ($__src as $r) {
        if (!is_array($r)) continue;
        $items[] = [
            'date'  => is_scalar($r['date']  ?? null) ? (string)$r['date']  : '',
            'title' => is_scalar($r['title'] ?? null) ? (string)$r['title'] : '',
            'url'   => is_scalar($r['url']   ?? null) ? (string)$r['url']   : '',
        ];
    }
}

$topLimitVal   = (int)($current['top_limit']  ?? 5);
$archiveUrlVal = is_scalar($current['archive_url'] ?? null) ? (string)$current['archive_url'] : '';

?><!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 news">

<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 ($notice): ?>
      <div class="alert success"><?= tpcms_h($notice) ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
      <div class="alert error"><?= tpcms_h($error) ?></div>
    <?php endif; ?>

    <div class="card">
      <form id="newsForm" method="post" action="./news.php">
      <input type="hidden" name="_csrf" value="<?= tpcms_h(tpcms_csrf_token()) ?>">

        <!-- ヘッダ -->
        <div class="mb1rem">
          <label class="head">トップページに表示する件数</label>
          <div><input type="number" name="top_limit" value="<?= (int)$topLimitVal ?>" min="1" max="999" step="1"></div>
        </div>

        <div class="mb3rem">
          <label class="head">過去ログURL（空欄の場合はお知らせの下のリンクが出ません）</label>
          <div><input type="text" name="archive_url" value="<?= tpcms_h($archiveUrlVal) ?>" placeholder="/news または https://example.com/news"></div>
        </div>

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

        <div id="listArea">
          <?php foreach ($items as $i => $r): ?>
            <div class="row" data-row>
              <div class="date"><input type="date" name="items[<?= $i ?>][date]" value="<?= tpcms_h($r['date']) ?>"></div>
              <div><input type="text" name="items[<?= $i ?>][title]" value="<?= tpcms_h($r['title']) ?>" placeholder="タイトル"></div>
              <div><input type="text" name="items[<?= $i ?>][url]" value="<?= tpcms_h($r['url']) ?>" placeholder="company や https://example.com"></div>
              <div><button type="button" class="btn" data-del>削除</button></div>
            </div>
          <?php endforeach; ?>
        </div>

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

    </div>
  </div>

  <script src="./assets/admin.js"></script>
<script>
(function(){
  const list = document.getElementById('listArea');
  const form = document.getElementById('newsForm');
  const addBtns = [document.getElementById('addRowBtn'), document.getElementById('addRowBtn2')];

  function today(){
    const d = new Date();
    const m = ('0' + (d.getMonth()+1)).slice(-2);
    const day = ('0' + d.getDate()).slice(-2);
    return d.getFullYear() + '-' + m + '-' + day;
  }

  function newRow(idx){
    const wrap = document.createElement('div');
    wrap.className = 'row';
    wrap.setAttribute('data-row','');
    wrap.innerHTML =
      '<div class="date"><input type="date" name="items['+idx+'][date]" value="'+today()+'"></div>' +
      '<div><input type="text" name="items['+idx+'][title]" value="" placeholder="タイトル"></div>' +
      '<div><input type="text" name="items['+idx+'][url]" value="" placeholder="company や https://example.com"></div>' +
      '<div><button type="button" class="btn" data-del>削除</button></div>';
    return wrap;
  }

  function reindex(){
    const rows = list.querySelectorAll('[data-row]');
    rows.forEach(function(row, i){
      row.querySelectorAll('input').forEach(function(inp){
        const m = inp.name.match(/^items\[\d+\]\[(date|title|url)\]$/);
        if (m) inp.name = 'items['+i+']['+m[1]+']';
      });
    });
  }

  function addRow(){
    const el = newRow(0);
    if (list.firstChild) list.insertBefore(el, list.firstChild);
    else list.appendChild(el);
    reindex();
  }

  addBtns.forEach(function(b){ if (b) b.addEventListener('click', addRow); });

  // 削除
  list.addEventListener('click', function(e){
    const btn = e.target.closest('[data-del]');
    if (!btn) return;
    const row = btn.closest('[data-row]');
    if (row) row.remove();
    reindex();
  });

  // 送信前に name を連番に整える
  form.addEventListener('submit', function(){ reindex(); });
})();
</script>

</body>
</html>
