<?php
session_start();
include(__DIR__ . '/../includes/auth.php');
requireRole(['master','admin']);

$newsFile   = __DIR__ . '/../data/news.txt';
$pinnedFile = __DIR__ . '/../data/news_pinned.txt';

$entries = file_exists($newsFile) ? explode("---\n", file_get_contents($newsFile)) : [];
$pinned  = file_exists($pinnedFile) ? explode("\n", trim(file_get_contents($pinnedFile))) : [];

$editMode   = false;
$editIndex  = null;
$editTitle  = '';
$editBody   = '';
$editTag    = '';
$editAuthor = '';
$editDate   = '';

// Handle edit mode
if (isset($_GET['edit'])) {
  $editIndex = (int)$_GET['edit'];
  if (isset($entries[$editIndex])) {
    $editMode = true;
    $lines = explode("\n", trim($entries[$editIndex]));
    $editTitle = array_shift($lines);
    $editBody  = implode("\n", $lines);

    if (preg_match_all('/

\[(tag|author|date):([^\]

]+)\]

/i', $editBody, $matches)) {
      foreach ($matches[1] as $i => $key) {
        ${'edit' . ucfirst(strtolower($key))} = trim($matches[2][$i]);
      }
      $editBody = preg_replace('/

\[(tag|author|date):([^\]

]+)\]

/i', '', $editBody);
      $editBody = trim($editBody);
    }
  }
}

// Handle create/update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['title'], $_POST['body'])) {
  $title  = trim($_POST['title']);
  $body   = trim($_POST['body']);
  $tag    = trim($_POST['tag']);
  $author = trim($_POST['author']);
  $date   = trim($_POST['date']);

  $meta = '';
  if ($tag)    $meta .= "[tag:$tag] ";
  if ($author) $meta .= "[author:$author] ";
  if ($date)   $meta .= "[date:$date] ";

  $entry = "$title\n$meta$body";

  if (isset($_POST['edit_index']) && $_POST['edit_index'] !== '') {
    $entries[(int)$_POST['edit_index']] = $entry;
  } else {
    $entries[] = $entry;
  }

  file_put_contents($newsFile, implode("---\n", $entries));
  header('Location: newsreel_admin.php');
  exit;
}

// Handle delete
if (isset($_GET['delete'])) {
  $deleteIndex = (int)$_GET['delete'];
  if (isset($entries[$deleteIndex])) {
    unset($entries[$deleteIndex]);
    $entries = array_values($entries);
    file_put_contents($newsFile, implode("---\n", $entries));
  }
  header('Location: newsreel_admin.php');
  exit;
}

// Handle pin/unpin
if (isset($_GET['pin'])) {
  $id = (string)$_GET['pin'];
  if (!in_array($id, $pinned)) $pinned[] = $id;
  file_put_contents($pinnedFile, implode("\n", $pinned));
  header('Location: newsreel_admin.php');
  exit;
}
if (isset($_GET['unpin'])) {
  $id = (string)$_GET['unpin'];
  $pinned = array_diff($pinned, [$id]);
  file_put_contents($pinnedFile, implode("\n", $pinned));
  header('Location: newsreel_admin.php');
  exit;
}

// Handle move up/down
if (isset($_GET['move'], $_GET['id'])) {
  $id = (int)$_GET['id'];
  if ($_GET['move'] === 'up' && $id > 0) {
    $tmp = $entries[$id];
    $entries[$id] = $entries[$id-1];
    $entries[$id-1] = $tmp;
  }
  if ($_GET['move'] === 'down' && $id < count($entries)-1) {
    $tmp = $entries[$id];
    $entries[$id] = $entries[$id+1];
    $entries[$id+1] = $tmp;
  }
  file_put_contents($newsFile, implode("---\n", $entries));
  header('Location: newsreel_admin.php');
  exit;
}
?>
<?php include('../header.php'); ?>
<?php include('../menu.php'); ?>
<link rel="stylesheet" href="/css/style.css?v=1">

<main class="main-container">
  <section class="admin-card">
    <h2 class="text-warning">📰 Manage Newsreel</h2>

    <!-- Create / Edit Form -->
    <form method="POST" class="admin-form mb-4">
      <input type="hidden" name="edit_index" value="<?= $editMode ? $editIndex : '' ?>">
      <input type="text" name="title" class="admin-input mb-2" placeholder="News title" required value="<?= htmlspecialchars($editTitle) ?>">
      <textarea name="body" class="admin-textarea mb-2" placeholder="News body" required><?= htmlspecialchars($editBody) ?></textarea>
      <div class="row g-2 mb-2">
        <div class="col-md-4"><input type="text" name="tag" class="admin-input" placeholder="Tag" value="<?= htmlspecialchars($editTag) ?>"></div>
        <div class="col-md-4"><input type="text" name="author" class="admin-input" placeholder="Author" value="<?= htmlspecialchars($editAuthor) ?>"></div>
        <div class="col-md-4"><input type="date" name="date" class="admin-input" value="<?= htmlspecialchars($editDate) ?>"></div>
      </div>
      <button type="submit" class="btn btn-<?= $editMode ? 'warning' : 'primary' ?>">
        <?= $editMode ? 'Update News' : 'Post News' ?>
      </button>
      <?php if ($editMode): ?>
        <a href="newsreel_admin.php" class="btn btn-secondary ms-2">Cancel</a>
      <?php endif; ?>
    </form>
    <!-- Existing Entries -->
    <?php foreach ($entries as $index => $entry): ?>
      <?php
        $lines = explode("\n", trim($entry));
        if (count($lines) < 1) continue;
        $title = array_shift($lines);
        $body  = implode("\n", $lines);
        if (trim($title) === '' && trim($body) === '') continue;
        $isPinned = in_array((string)$index, $pinned);

        $meta = ['tag'=>'','author'=>'','date'=>''];
        if (preg_match_all('/

\[(tag|author|date):([^\]

]+)\]

/i', $body, $matches)) {
          foreach ($matches[1] as $i => $key) {
            $meta[strtolower($key)] = trim($matches[2][$i]);
          }
        }
      ?>
      <div class="admin-news-card mb-4">
        <h4 class="text-warning"><?= $isPinned ? '📌 ' : '' ?><?= htmlspecialchars($title) ?></h4>
        <p><?= nl2br(htmlspecialchars($body)) ?></p>
        <small class="text-muted">
          <?php if ($meta['tag']): ?>🏷️ <?= htmlspecialchars($meta['tag']) ?><?php endif; ?>
          <?php if ($meta['author']): ?> | ✍️ <?= htmlspecialchars($meta['author']) ?><?php endif; ?>
          <?php if ($meta['date']): ?> | 📅 <?= htmlspecialchars($meta['date']) ?><?php endif; ?>
        </small>
        <div class="mt-2">
          <?php if ($index > 0): ?>
            <a href="?move=up&id=<?= $index ?>" class="btn btn-sm btn-outline-dark me-1">⬆️ Move Up</a>
          <?php endif; ?>
          <?php if ($index < count($entries)-1): ?>
            <a href="?move=down&id=<?= $index ?>" class="btn btn-sm btn-outline-dark me-1">⬇️ Move Down</a>
          <?php endif; ?>
          <?php if ($isPinned): ?>
            <a href="?unpin=<?= $index ?>" class="btn btn-sm btn-secondary me-1">Unpin</a>
          <?php else: ?>
            <a href="?pin=<?= $index ?>" class="btn btn-sm btn-outline-secondary me-1">Pin</a>
          <?php endif; ?>
          <a href="?edit=<?= $index ?>" class="btn btn-sm btn-warning me-1">Edit</a>
          <a href="?delete=<?= $index ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete this news item?')">Delete</a>
        </div>
      </div>
    <?php endforeach; ?>

    <?php if (empty($entries)): ?>
      <div class="admin-news-card">
        <p>No news entries yet. The mountain is quiet… for now.</p>
      </div>
    <?php endif; ?>

    <div class="text-end mt-4">
      <a href="/news/news.php" class="btn btn-sm btn-dark">View Public News Page</a>
    </div>
  </section>
</main>

<?php include('../footer.php'); ?>
