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

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

$action = $_GET['action'] ?? '';
$file = $_GET['file'] ?? '';

function safe_news_file($name) {
  $name = basename($name);
  if (!preg_match('/^[a-zA-Z0-9._-]+\.json$/', $name)) return '';
  return $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);
  }
  header("Location: /admin/news.php");
  exit;
}

$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'] ?? '');

  $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;
}

// list files newest first
$files = glob($newsDir . '*.json');
rsort($files);
?>
<section class="content-card">
  <h1 class="admin-title">📰 News Manager</h1>
  <p style="opacity:.8;">Front-end reads: <code>/data/news/*.json</code> • Images in <code>/img/content/</code></p>

  <div class="admin-wrap" 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" 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 filename (optional, stored in /img/content/)</label>
        <input class="input-field" name="image" value="<?= smurf_h($post['image']) ?>" <?= $CAN_EDIT ? '' : 'disabled' ?>>

        
        <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;">Existing Posts</h3>

      <?php if (empty($files)): ?>
        <p>No posts yet.</p>
      <?php else: ?>
        <?php foreach ($files as $path):
          $name = basename($path);
          $j = smurf_read_json($path, []);
          $title = $j['title'] ?? $name;
          $date = $j['date'] ?? '';
        ?>
          <div class="content-card" style="text-align:left;">
            <div style="display:flex;justify-content:space-between;gap:10px;align-items:center;">
              <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 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; ?>
      <?php endif; ?>
    </section>
  </div>
</section>

<?php include __DIR__ . '/includes/admin_footer.php'; ?>
