<?php include 'auth.php'; ?>
<?php include '../includes/header.php'; ?>
<?php include '../includes/menu.php'; ?>

<?php
$newsFile = '../data/news.txt';
$pinnedFile = '../data/news_pinned.txt';

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

// Edit mode setup
$editMode = false;
$editIndex = null;
$editTitle = '';
$editBody = '';
$editTag = '';
$editAuthor = '';
$editDate = '';

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 new post or 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\n---\n";

  if (isset($_POST['edit_index']) && $_POST['edit_index'] !== '') {
    $editIndex = (int)$_POST['edit_index'];
    $entries[$editIndex] = $entry;
    file_put_contents($newsFile, implode("---\n", $entries));
  } else {
    file_put_contents($newsFile, $entry, FILE_APPEND);
  }

  header('Location: newsreel_admin.php');
  exit;
}

// Handle clear all
if (isset($_GET['clearall'])) {
  file_put_contents($newsFile, '');
  file_put_contents($pinnedFile, '');
  header('Location: newsreel_admin.php?cleared=1');
  exit;
}

// Handle pin/unpin
if (isset($_GET['pin'])) {
  $id = $_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 = $_GET['unpin'];
  $pinned = array_filter($pinned, function($p) use ($id){ return $p !== $id; });
  file_put_contents($pinnedFile, implode("\n", $pinned));
  header('Location: newsreel_admin.php');
  exit;
}

// Handle delete and reindex
if (isset($_GET['delete'])) {
  $id = (int)$_GET['delete'];
  unset($entries[$id]);
  $entries = array_values($entries);
  file_put_contents($newsFile, implode("---\n", $entries));

  $newPinned = [];
  foreach ($pinned as $p) {
    $p = (int)$p;
    if ($p < $id) $newPinned[] = $p;
    elseif ($p > $id) $newPinned[] = $p - 1;
  }
  file_put_contents($pinnedFile, implode("\n", $newPinned));
  header('Location: newsreel_admin.php');
  exit;
}

// Handle move up/down
if (isset($_GET['move'])) {
  $direction = $_GET['move'];
  $id = (int)$_GET['id'];

  if (($direction === 'up' && $id > 0) || ($direction === 'down' && $id < count($entries) - 1)) {
    $swapWith = $direction === 'up' ? $id - 1 : $id + 1;
    [$entries[$id], $entries[$swapWith]] = [$entries[$swapWith], $entries[$id]];
    file_put_contents($newsFile, implode("---\n", $entries));

    $newPinned = [];
    foreach ($pinned as $p) {
      $p = (int)$p;
      if ($p === $id) $newPinned[] = $swapWith;
      elseif ($p === $swapWith) $newPinned[] = $id;
      else $newPinned[] = $p;
    }
    file_put_contents($pinnedFile, implode("\n", $newPinned));
  }

  header('Location: newsreel_admin.php');
  exit;
}
?>

<div class="container mt-5">
  <div class="content-box">
    <div class="d-flex flex-wrap gap-2 justify-content-between align-items-center mb-3">
      <h2 class="mb-0">📰 Manage Newsreel</h2>
      <div class="d-flex flex-wrap gap-2">
        <a href="index.php" class="btn btn-secondary btn-sm">Back to Admin Dashboard</a>
        <a href="?clearall=1" class="btn btn-danger btn-sm" onclick="return confirm('Clear all news items?')">Clear All</a>
      </div>
    </div>
    <?php if (!empty($_GET['cleared'])): ?><div class="alert alert-warning">All news items cleared.</div><?php endif; ?>

    <!-- Add/Edit News Form -->
    <form method="POST" class="mb-4">
      <input type="hidden" name="edit_index" value="<?= $editMode ? $editIndex : '' ?>">
      <input type="text" name="title" class="form-control mb-2" placeholder="News title" required value="<?= htmlspecialchars($editTitle) ?>">
      <textarea name="body" class="form-control 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="form-control" placeholder="Tag (e.g. music)" value="<?= htmlspecialchars($editTag) ?>"></div>
        <div class="col-md-4"><input type="text" name="author" class="form-control" placeholder="Author (e.g. DJ Ember)" value="<?= htmlspecialchars($editAuthor) ?>"></div>
        <div class="col-md-4"><input type="date" name="date" class="form-control" 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 News 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="comment-box mb-4">
        <h4 class="text-warning"><?= $isPinned ? '📌 ' : '' ?><?= htmlspecialchars($title) ?></h4>
        <p><?= nl2br(htmlspecialchars($body)) ?></p>
        <small class="text-muted">
          <?php if ($meta['tag']): ?>🏷️ Tag: <?= htmlspecialchars($meta['tag']) ?><?php endif; ?>
          <?php if ($meta['author']): ?> | ✍️ Author: <?= htmlspecialchars($meta['author']) ?><?php endif; ?>
          <?php if ($meta['date']): ?> | 📅 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; ?>
  </div>
</div>

<?php include '../includes/footer.php'; ?>
