<?php
session_start();
require __DIR__ . '/includes/admin_lib.php';

$newsDir = __DIR__ . '/../data/news/';
if (!is_dir($newsDir)) mkdir($newsDir, 0777, true);
$legacyNewsFile = __DIR__ . '/../data/news.txt';

$action = $_GET['action'] ?? '';
$file = $_GET['file'] ?? '';
function safe_news_file($name) { $name = basename($name); return preg_match('/^[a-zA-Z0-9._-]+\.json$/', $name) ? $name : ''; }
if ($action === 'delete' && $file) {
  if (!$CAN_EDIT) die("<h1>Access Denied</h1><p>You do not have permission to delete news.</p>");
  $sf = safe_news_file($file);
  if ($sf && file_exists($newsDir . $sf)) { @copy($newsDir . $sf, $newsDir . $sf . '.bak'); unlink($newsDir . $sf); }
  smurf_redirect_self([], ['action','file']);
}
$editFile = ($action === 'edit' && $file) ? safe_news_file($file) : '';
$post = ['title'=>'','author'=>$_SESSION['user'] ?? 'Admin','date'=>date('Y-m-d'),'tag'=>'','content'=>'','image'=>'','published'=>1,'featured_home'=>0];
if ($editFile && file_exists($newsDir . $editFile)) { $post = array_merge($post, smurf_read_json($newsDir . $editFile, [])); }
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!$CAN_EDIT) die("<h1>Access Denied</h1><p>You do not have permission to edit news.</p>");
  $post['title'] = trim($_POST['title'] ?? '');
  $post['author'] = trim($_POST['author'] ?? '');
  $post['date'] = trim($_POST['date'] ?? date('Y-m-d'));
  $post['tag'] = trim($_POST['tag'] ?? '');
  $post['content'] = trim($_POST['content'] ?? '');
  $post['image'] = trim($_POST['image'] ?? '');
  if ($post['image'] === '') { $uploaded = smurf_handle_upload('image_file', __DIR__ . '/../img/content'); if ($uploaded !== '') $post['image'] = $uploaded; }
  $post['published'] = isset($_POST['published']) ? 1 : 0;
  $post['featured_home'] = isset($_POST['featured_home']) ? 1 : 0;
  $slug = preg_replace('/[^a-z0-9]+/i', '-', strtolower($post['title'])); $slug = trim($slug, '-'); if ($slug === '') $slug = 'post';
  $fname = $editFile ?: (date('Ymd_His') . '_' . $slug . '.json');
  smurf_write_json($newsDir . $fname, $post);
  header('Location: /admin/news.php?action=edit&file=' . urlencode($fname) . '&saved=1'); exit;
}
$files = glob($newsDir . '*.json') ?: []; rsort($files);
$legacyBlocks = [];
if (file_exists($legacyNewsFile)) {
  $raw = trim((string)file_get_contents($legacyNewsFile));
  if ($raw !== '') {
    foreach (preg_split("/\n---\s*\n/", $raw) as $chunk) {
      $chunk = trim($chunk); if ($chunk !== '') $legacyBlocks[] = $chunk;
    }
    $legacyBlocks = array_reverse($legacyBlocks);
  }
}
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <h1 class="admin-title">📰 News Manager</h1>
  <p style="opacity:.8;">Thunder now supports Smurf-style structured JSON posts in <code>/data/news/*.json</code> while keeping your older Thunder stories in <code>/data/news.txt</code>.</p>
  <div class="admin-wrap stack" style="margin-top:10px;">
    <section class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;"><?= $editFile ? 'Edit Post' : 'Create New Post' ?></h3>
      <?php if (isset($_GET['saved'])): ?><div class="msg success">Saved.</div><?php endif; ?>
      <form method="POST" enctype="multipart/form-data" class="form">
        <label>Title</label><input class="input-field" name="title" value="<?= smurf_h($post['title']) ?>" required <?= $CAN_EDIT ? '' : 'disabled' ?>>
        <label>Author</label><input class="input-field" name="author" value="<?= smurf_h($post['author']) ?>" <?= $CAN_EDIT ? '' : 'disabled' ?>>
        <label>Date (YYYY-MM-DD)</label><input class="input-field" name="date" value="<?= smurf_h($post['date']) ?>" <?= $CAN_EDIT ? '' : 'disabled' ?>>
        <label>Tag</label><input class="input-field" name="tag" value="<?= smurf_h($post['tag']) ?>" <?= $CAN_EDIT ? '' : 'disabled' ?>>
        <label>Image Link (optional)</label><input class="input-field" name="image" value="<?= smurf_h($post['image']) ?>" placeholder="https://example.com/image.jpg" <?= $CAN_EDIT ? '' : 'disabled' ?>>
        <label>Or Upload Image File</label><input type="file" class="input-field" name="image_file" accept="image/*" <?= $CAN_EDIT ? '' : 'disabled' ?>>
        <?php $previewImage = smurf_image_src((string)($post['image'] ?? ''), 'img/content'); if ($previewImage !== ''): ?><div class="content-card" style="margin-top:12px;text-align:left;"><strong>Current Image Preview</strong><div style="margin-top:10px;"><img src="<?= smurf_h($previewImage) ?>" alt="Current news image" style="width:140px;height:180px;object-fit:cover;border-radius:14px;display:block;"></div></div><?php endif; ?>
        <div style="display:flex; gap:16px; flex-wrap:wrap; margin-top:8px;"><label style="display:flex; gap:8px; align-items:center; margin:0;"><input type="checkbox" name="published" value="1" <?= !empty($post['published']) ? 'checked' : '' ?> <?= $CAN_EDIT ? '' : 'disabled' ?>><span>Published</span></label><label style="display:flex; gap:8px; align-items:center; margin:0;"><input type="checkbox" name="featured_home" value="1" <?= !empty($post['featured_home']) ? 'checked' : '' ?> <?= $CAN_EDIT ? '' : 'disabled' ?>><span>Feature on Home Page</span></label></div>
        <label>Content</label><textarea class="input-field" name="content" rows="10" <?= $CAN_EDIT ? '' : 'disabled' ?>><?= smurf_h($post['content']) ?></textarea>
        <?php if ($CAN_EDIT): ?><button class="admin-btn primary" type="submit" style="margin-top:12px;"><?= $editFile ? 'Save Changes' : 'Create Post' ?></button><?php else: ?><p style="opacity:.7;margin-top:10px;">View-only mode — editing disabled.</p><?php endif; ?>
      </form>
    </section>
    <section class="content-card" style="text-align:left;"><h3 style="margin-top:0;">Structured Posts</h3><?php if (empty($files)): ?><p>No structured posts yet.</p><?php else: foreach ($files as $path): $name = basename($path); $j = smurf_read_json($path, []); $title = $j['title'] ?? $name; $date = $j['date'] ?? ''; $imageSrc = smurf_image_src((string)($j['image'] ?? ''), 'img/content'); ?><div class="content-card" style="text-align:left;"><div style="display:flex;justify-content:space-between;gap:14px;align-items:flex-start;flex-wrap:wrap;"><div style="display:flex;gap:14px;align-items:flex-start;flex-wrap:wrap;flex:1 1 420px;"><?php if ($imageSrc !== ''): ?><img src="<?= smurf_h($imageSrc) ?>" alt="<?= smurf_h($title) ?>" style="width:120px;height:90px;object-fit:cover;border-radius:14px;flex:0 0 auto;"><?php endif; ?><div><strong><?= smurf_h($title) ?></strong><div style="opacity:.8;font-size:.95em;"><?= smurf_h($date) ?> • <code><?= smurf_h($name) ?></code></div><div style="margin-top:6px; display:flex; gap:8px; flex-wrap:wrap;"><?php if (empty($j['published'])): ?><span class="badge" style="background:rgba(255,255,255,.08);padding:4px 8px;border-radius:999px;">Draft</span><?php else: ?><span class="badge" style="background:rgba(0,204,136,.18);padding:4px 8px;border-radius:999px;">Published</span><?php endif; ?><?php if (!empty($j['featured_home'])): ?><span class="badge" style="background:rgba(255,215,0,.18);padding:4px 8px;border-radius:999px;">Featured</span><?php endif; ?></div></div></div><div style="display:flex;gap:8px;"><a class="admin-btn" href="/admin/news.php?action=edit&file=<?= urlencode($name) ?>">Edit</a><?php if ($CAN_EDIT): ?><a class="admin-btn" href="/admin/news.php?action=delete&file=<?= urlencode($name) ?>" onclick="return confirm('Delete this post?');">Delete</a><?php endif; ?></div></div></div><?php endforeach; endif; ?></section>
    <section class="content-card" style="text-align:left;"><h3 style="margin-top:0;">Legacy Thunder News</h3><p style="opacity:.8;">These older stories are still shown on the public news page. They are preserved exactly as-is from <code>/data/news.txt</code>.</p><?php if (!$legacyBlocks): ?><p>No legacy news blocks found.</p><?php else: foreach (array_slice($legacyBlocks, 0, 10) as $block): ?><div class="content-card" style="text-align:left;"><pre style="white-space:pre-wrap;margin:0;opacity:.95;"><?= smurf_h($block) ?></pre></div><?php endforeach; endif; ?></section>
  </div>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
