<?php
require_once __DIR__ . '/lib/news-lib.php';

/** 編集パスワード — いずれか一致で可 */
$PASSWORDS = [
    "welb5151",
    // "2つ目のパスワード",
];

function news_editor_password_ok(string $submitted): bool {
    global $PASSWORDS;
    foreach ($PASSWORDS as $p) {
        if ($p === '' || $p === null) {
            continue;
        }
        if (hash_equals((string)$p, $submitted)) {
            return true;
        }
    }
    return false;
}

$newsDir = news_data_dir();

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (!news_editor_password_ok((string)($_POST["password"] ?? ""))) {
        die("パスワードが違います");
    }

    if (isset($_POST["delete"])) {
        $file = $newsDir . $_POST["id"];
        if (file_exists($file)) unlink($file);
        header("Location: news_edit.php");
        exit;
    }

    $uploadedTag = "";

    if (!empty($_FILES["upload_file"]["name"][0])) {
        $upDir = $newsDir . "files/";
        if (!is_dir($upDir)) {
            mkdir($upDir, 0755, true);
        }

        foreach ($_FILES["upload_file"]["name"] as $key => $fname) {
            if (!$fname) continue;
            $fname = basename($fname);
            $target = $upDir . $fname;

            if (move_uploaded_file($_FILES["upload_file"]["tmp_name"][$key], $target)) {
                $ext = strtolower(pathinfo($fname, PATHINFO_EXTENSION));

                if (in_array($ext, ["jpg","jpeg","png","gif","webp"])) {
                    $uploadedTag .= "\n[img]{$fname}[/img]\n";
                } elseif ($ext === "pdf") {
                    $pdfLabel = PDF_LABEL_DEFAULT;
                    if (!empty($_POST["pdf_label"][$key])) {
                        $pdfLabel = news_parse_pdf_label((string)$_POST["pdf_label"][$key]);
                        if ($pdfLabel === '') {
                            $pdfLabel = PDF_LABEL_DEFAULT;
                        }
                    }
                    $uploadedTag .= "\n" . news_build_pdf_tag($pdfLabel, $fname) . "\n";
                }
            }
        }
    }

    $categories = [];
    if (!empty($_POST["categories"]) && is_array($_POST["categories"])) {
        foreach ($_POST["categories"] as $c) {
            if (in_array($c, NEWS_CATEGORIES, true)) {
                $categories[] = $c;
            }
        }
    }

    $id   = news_normalize_article_id((string)($_POST["id"] ?? ""));
    $file = $newsDir . $id;

    $existingDate = date("Y-m-d");
    if (!empty($_POST["id"])) {
        $oldPath = $newsDir . $_POST["id"];
        if (is_file($oldPath)) {
            $old = news_parse_file($oldPath);
            if ($old["date"] !== "") {
                $existingDate = $old["date"];
            }
        }
    }

    $content = news_build_content([
        "categories"  => $categories,
        "description" => trim($_POST["description"] ?? ""),
        "memo"        => trim($_POST["memo"] ?? ""),
        "date"        => $existingDate,
        "title"       => trim($_POST["title"] ?? ""),
        "body"        => trim($_POST["body"] ?? "") . $uploadedTag,
    ]);

    file_put_contents($file, $content);
    header("Location: news_edit.php?id=" . rawurlencode($id));
    exit;
}

$id    = isset($_GET["id"]) ? $_GET["id"] : "";
$title = "";
$body  = "";
$description = "";
$memo = "";
$selectedCategories = [];

if ($id) {
    $file = $newsDir . $id;
    if (file_exists($file)) {
        $parsed = news_parse_file($file);
        $title = $parsed["title"];
        $body = $parsed["body"];
        $description = $parsed["description"];
        $memo = $parsed["memo"];
        $selectedCategories = $parsed["categories"];
    }
}

$attachedImages = [];
$attachedPdfs = [];
if ($body !== '') {
    $attachments = news_extract_attachments($body);
    $attachedImages = $attachments['images'];
    $attachedPdfs = $attachments['pdfs'];
}

$files = glob($newsDir . "*.txt");
rsort($files);
$oneYearAgo = strtotime("-1 year");
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NEWS管理 — Board Room</title>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

body {
  font-family: 'Hiragino Sans', 'Hiragino Kaku Gothic ProN', 'Noto Sans JP', sans-serif;
  background: #f2f4f8;
  color: #2a3050;
  font-size: 14px;
  line-height: 1.6;
  padding: 24px 20px 48px;
}

a { color: #4a90e2; text-decoration: none; }
a:hover { text-decoration: underline; }

.page-wrap { max-width: 1000px; margin: 0 auto; display: flex; flex-direction: column; gap: 20px; }

.page-header {
  background: #1a2744;
  border-radius: 12px;
  padding: 18px 24px;
  display: flex; align-items: center; justify-content: space-between;
}
.page-header-title { font-size: 17px; font-weight: 700; color: #fff; }
.page-header-back {
  font-size: 12px; color: #7a90b8;
  padding: 5px 12px; border-radius: 6px; border: 1px solid rgba(255,255,255,0.15);
  transition: background 0.12s;
}
.page-header-back:hover { background: rgba(255,255,255,0.1); color: #a8c8f8; text-decoration: none; }

.card { background: #fff; border: 1px solid #e4e7ef; border-radius: 12px; overflow: hidden; }
.card-header {
  padding: 13px 20px; border-bottom: 1px solid #f0f2f6;
  display: flex; align-items: center; gap: 8px;
}
.card-title-icon { font-size: 15px; }
.card-title { font-size: 14px; font-weight: 600; color: #1a2744; }
.card-body { padding: 16px 20px; }

.article-item {
  display: flex; align-items: center; gap: 12px;
  padding: 10px 0; border-bottom: 1px solid #f4f5f8;
  font-size: 13px;
}
.article-item:last-child { border-bottom: none; }
.article-date { color: #8a96b0; white-space: nowrap; flex-shrink: 0; font-variant-numeric: tabular-nums; }
.article-title-text { flex: 1; color: #2a3050; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.article-desc { color: #7b8399; font-size: 12px; }
.btn-edit {
  font-size: 11px; color: #4a90e2; padding: 3px 10px;
  border-radius: 5px; border: 1px solid #c0d8f4; background: #eef4ff;
  white-space: nowrap; flex-shrink: 0;
}
.btn-edit:hover { background: #d8ecff; text-decoration: none; }
.news-cat {
  display: inline-block; font-size: 11px; font-weight: 600;
  padding: 2px 8px; border-radius: 20px; background: #eef4ff; color: #4a90e2;
  white-space: nowrap; flex-shrink: 0;
}

.form-hint {
  font-size: 12px; color: #8a93a8; margin-bottom: 16px; line-height: 1.7;
  padding: 10px 14px; background: #f8f9fb; border-radius: 7px; border: 1px solid #e8eaef;
}
.form-hint code { background: #eef0f4; padding: 1px 5px; border-radius: 4px; font-size: 11px; }

.form-group { margin-bottom: 16px; }
.form-label {
  display: block; font-size: 12px; font-weight: 600; color: #4a5070; margin-bottom: 6px;
}
.form-label span { font-weight: 400; color: #8a93a8; margin-left: 6px; }

.form-input, .form-textarea {
  width: 100%; padding: 9px 12px; font-size: 13px;
  border: 1px solid #d8dce8; border-radius: 7px;
  outline: none; background: #f8f9fb; color: #2a3050;
  font-family: inherit; transition: border-color 0.12s, box-shadow 0.12s;
}
.form-input:focus, .form-textarea:focus {
  border-color: #4a90e2; box-shadow: 0 0 0 3px rgba(74,144,226,0.12); background: #fff;
}
.form-textarea { resize: vertical; }

.password-row {
  display: flex; align-items: center; gap: 10px;
  padding: 12px 14px; background: #fff8ec; border: 1px solid #fce8b2;
  border-radius: 8px; margin-bottom: 18px;
}
.password-row label { font-size: 12px; font-weight: 600; color: #8a6020; white-space: nowrap; }
.password-row input {
  padding: 7px 10px; font-size: 13px; border: 1px solid #e8d090;
  border-radius: 6px; outline: none; background: #fff; font-family: inherit; width: 180px;
}

.cat-list { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 6px; }
.cat-label {
  display: inline-flex; align-items: center; gap: 5px;
  padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 500;
  border: 1px solid #e0e3ea; background: #f4f5f7; color: #5a6080; cursor: pointer;
  transition: background 0.12s, border-color 0.12s;
}
.cat-label input { display: none; }
.cat-label:has(input:checked) { background: #eef4ff; border-color: #4a90e2; color: #4a90e2; }

.attach-preview { display: flex; flex-wrap: wrap; gap: 10px; margin: 10px 0; }
.attach-preview img {
  width: 120px; height: 90px; object-fit: cover;
  border-radius: 7px; border: 1px solid #e4e7ef;
  box-shadow: 0 1px 4px rgba(0,0,0,.1);
}
.pdf-item {
  display: inline-flex; align-items: center; gap: 6px;
  padding: 7px 12px; border: 1px solid #dde1ea; border-radius: 7px;
  background: #f8f9fb; font-size: 12px; color: #2a3050;
}

.upload-row {
  padding: 8px 10px; margin-bottom: 6px;
  background: #f8f9fb; border: 1px solid #e8eaef; border-radius: 7px;
  font-size: 13px;
}
.pdf-label-list { display: flex; flex-wrap: wrap; gap: 6px 14px; margin: 8px 0 0 4px; font-size: 12px; }
.pdf-label-list label { white-space: nowrap; display: flex; align-items: center; gap: 4px; }

.btn-row { display: flex; gap: 10px; align-items: center; margin-top: 18px; flex-wrap: wrap; }
.btn-save {
  padding: 9px 24px; background: #1a2744; color: #fff; border: none;
  border-radius: 8px; cursor: pointer; font-size: 13px; font-weight: 600;
  font-family: inherit; transition: background 0.15s;
}
.btn-save:hover { background: #4a90e2; }
.btn-delete {
  padding: 9px 20px; background: #fff; color: #c0392b;
  border: 1px solid #e8b4b0; border-radius: 8px; cursor: pointer;
  font-size: 13px; font-weight: 600; font-family: inherit; transition: background 0.15s;
}
.btn-delete:hover { background: #fde8e8; }

.delete-section {
  margin-top: 20px; padding: 14px 16px;
  background: #fff8f8; border: 1px solid #f0d0cc; border-radius: 8px;
}
.delete-section label { font-size: 12px; font-weight: 600; color: #8a4040; }
.delete-section input {
  padding: 7px 10px; font-size: 13px; border: 1px solid #e8b4b0;
  border-radius: 6px; outline: none; font-family: inherit; margin: 0 10px;
}

.file-input-wrap {
  padding: 12px 14px; background: #f8f9fb; border: 2px dashed #d8dce8;
  border-radius: 8px; font-size: 13px; color: #6b7280;
}
.file-input-wrap input[type=file] { font-size: 13px; font-family: inherit; }
</style>
</head>
<body>

<div class="page-wrap">

  <div class="page-header">
    <span class="page-header-title">📝 NEWS管理</span>
    <a href="Board-Room.php" class="page-header-back">◀ Board Room</a>
  </div>

  <div class="card">
    <div class="card-header">
      <span class="card-title-icon">📋</span>
      <span class="card-title">過去記事（過去1年以内）</span>
    </div>
    <div class="card-body">
      <?php foreach ($files as $f):
        $parsed = news_parse_file($f);
        $date  = $parsed["date"];
        $title = $parsed["title"];
        if (!$date) continue;
        $ts = strtotime($date);
        if ($ts < $oneYearAgo) continue;
      ?>
      <div class="article-item">
        <span class="article-date"><?= htmlspecialchars($date) ?></span>
        <?= news_category_labels_html($parsed["categories"]) ?>
        <span class="article-title-text">
          <?= htmlspecialchars($title) ?>
          <?php if ($parsed["description"] !== ""): ?>
            <span class="article-desc"> — <?= htmlspecialchars($parsed["description"]) ?></span>
          <?php endif; ?>
        </span>
        <a href="news_edit.php?id=<?= urlencode(basename($f)) ?>" class="btn-edit">編集</a>
      </div>
      <?php endforeach; ?>
    </div>
  </div>

  <div class="card">
    <div class="card-header">
      <span class="card-title-icon"><?= $id ? '✏️' : '🆕' ?></span>
      <span class="card-title"><?= $id ? '記事を編集' : '新規投稿' ?></span>
    </div>
    <div class="card-body">

      <div class="form-hint">
        区分・概要・メモは LISTER の APP_CATEGORY / APP_DESCRIPTION / APP_MEMO として保存されます。
        画像・PDF の添付は <code>News-Archive/files/</code> に保存され、本文に <code>[img]…[/img]</code> / <code>[pdf]種類|ファイル名[/pdf]</code> が付きます。
        PDF は添付時に種類（見積書・議案書など）を選べます。
      </div>

      <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="id" value="<?= htmlspecialchars($id) ?>">

        <div class="password-row">
          <label>🔑 パスワード</label>
          <input type="password" name="password" autofocus>
        </div>

        <div class="form-group">
          <label class="form-label">区分 <span>複数選択可</span></label>
          <div class="cat-list">
            <?php foreach (NEWS_CATEGORIES as $cat): ?>
            <label class="cat-label">
              <input type="checkbox" name="categories[]" value="<?= htmlspecialchars($cat) ?>"
                <?= in_array($cat, $selectedCategories, true) ? 'checked' : '' ?>>
              <?= htmlspecialchars($cat) ?>
            </label>
            <?php endforeach; ?>
          </div>
        </div>

        <div class="form-group">
          <label class="form-label">概要 <span>一覧・LISTERで見える短い説明</span></label>
          <input class="form-input" type="text" name="description" value="<?= htmlspecialchars($description) ?>" placeholder="一覧・LISTER で見える短い説明">
        </div>

        <div class="form-group">
          <label class="form-label">メモ <span>編集者向け・公開本文には出しません</span></label>
          <textarea class="form-textarea" name="memo" style="height:70px;" placeholder="編集者向けメモ"><?= htmlspecialchars($memo) ?></textarea>
        </div>

        <div class="form-group">
          <label class="form-label">タイトル</label>
          <input class="form-input" type="text" name="title" value="<?= htmlspecialchars($title) ?>">
        </div>

        <div class="form-group">
          <label class="form-label">本文</label>
          <?php if ($attachedImages !== [] || $attachedPdfs !== []): ?>
          <div style="margin-bottom:10px;">
            <div style="font-size:12px; font-weight:600; color:#4a5070; margin-bottom:6px;">添付済みファイル</div>
            <div class="attach-preview">
              <?php foreach ($attachedImages as $imgName): ?>
              <a href="<?= htmlspecialchars(news_resolve_attachment_url($imgName)) ?>" target="_blank" rel="noopener">
                <img src="<?= htmlspecialchars(news_resolve_attachment_url($imgName)) ?>" alt="<?= htmlspecialchars($imgName) ?>">
              </a>
              <?php endforeach; ?>
              <?php foreach ($attachedPdfs as $pdf): ?>
              <?php $pdfText = news_pdf_display_text($pdf['label'], $pdf['filename']); $pdfUrl = news_resolve_attachment_url($pdf['filename']); ?>
              <a class="pdf-item" href="<?= htmlspecialchars($pdfUrl) ?>" target="_blank" rel="noopener" title="<?= htmlspecialchars($pdf['filename']) ?>">📄 <?= htmlspecialchars($pdfText) ?></a>
              <?php endforeach; ?>
            </div>
          </div>
          <?php endif; ?>
          <textarea class="form-textarea" name="body" style="height:280px;"><?= htmlspecialchars($body) ?></textarea>
        </div>

        <div class="form-group">
          <label class="form-label">ファイル添付</label>
          <div class="file-input-wrap">
            <input type="file" id="upload_file" name="upload_file[]" multiple onchange="addFiles(this,'upload_list')">
          </div>
          <div id="upload_list" style="margin-top:8px;"></div>
        </div>

        <div class="btn-row">
          <button type="submit" class="btn-save">💾 保存</button>
        </div>
      </form>

      <?php if ($id): ?>
      <div class="delete-section">
        <form method="post" onsubmit="return confirm('本当に削除しますか？');">
          <input type="hidden" name="id" value="<?= htmlspecialchars($id) ?>">
          <label>🗑 削除する場合はパスワード：</label>
          <input type="password" name="password">
          <button type="submit" name="delete" value="1" class="btn-delete">削除</button>
        </form>
      </div>
      <?php endif; ?>

    </div>
  </div>

</div>

<script>
const PDF_LABELS = <?= json_encode(PDF_LABELS, JSON_UNESCAPED_UNICODE) ?>;
const PDF_LABEL_DEFAULT = <?= json_encode(PDF_LABEL_DEFAULT, JSON_UNESCAPED_UNICODE) ?>;

const fileStore = {};
const pdfLabelStore = {};

function addFiles(input, listId) {
    if (!fileStore[listId]) fileStore[listId] = new DataTransfer();
    for (const file of input.files) fileStore[listId].items.add(file);
    input.files = fileStore[listId].files;
    renderList(listId);
}

function isPdfFile(name) {
    const parts = name.split('.');
    return parts.length > 1 && parts.pop().toLowerCase() === 'pdf';
}

function renderList(listId) {
    const list = document.getElementById(listId);
    list.innerHTML = '';
    const files = fileStore[listId]?.files || [];
    Array.from(files).forEach((file, index) => {
        const div = document.createElement('div');
        div.className = 'upload-row';
        const name = document.createElement('span');
        name.textContent = file.name;
        const btn = document.createElement('button');
        btn.type = "button";
        btn.textContent = "削除";
        btn.style.cssText = "margin-left:10px; padding:2px 8px; font-size:12px; border:1px solid #e0e3ea; border-radius:4px; background:#fff; cursor:pointer;";
        btn.onclick = function() { removeFile(listId, index); };
        div.appendChild(name);
        div.appendChild(btn);
        if (isPdfFile(file.name)) {
            const labelBox = document.createElement('div');
            labelBox.className = 'pdf-label-list';
            labelBox.appendChild(document.createTextNode('種類：'));
            const saved = pdfLabelStore[file.name] || PDF_LABEL_DEFAULT;
            PDF_LABELS.forEach((label) => {
                const wrap = document.createElement('label');
                const radio = document.createElement('input');
                radio.type = 'radio';
                radio.name = 'pdf_label[' + index + ']';
                radio.value = label;
                radio.checked = (label === saved);
                radio.addEventListener('change', () => { pdfLabelStore[file.name] = label; });
                wrap.appendChild(radio);
                wrap.appendChild(document.createTextNode(' ' + label));
                labelBox.appendChild(wrap);
            });
            if (!pdfLabelStore[file.name]) pdfLabelStore[file.name] = saved;
            div.appendChild(labelBox);
        }
        list.appendChild(div);
    });
}

function removeFile(listId, index) {
    const oldInput = document.getElementById('upload_file');
    const newStore = new DataTransfer();
    Array.from(fileStore[listId].files).forEach((file, i) => {
        if (i !== index) newStore.items.add(file);
        else delete pdfLabelStore[file.name];
    });
    fileStore[listId] = newStore;
    const newInput = oldInput.cloneNode();
    oldInput.parentNode.replaceChild(newInput, oldInput);
    newInput.files = newStore.files;
    newInput.setAttribute("onchange", "addFiles(this,'upload_list')");
    renderList(listId);
}
</script>
</body>
</html>
