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

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

function safe_news_file($name) {
  $name = basename((string)$name);
  return preg_match('/^[a-zA-Z0-9._-]+\.json$/', $name) ? $name : '';
}

function news_defaults(): array { return ht_news_defaults(); }

function rebuild_news_index(string $newsDir, string $newsIndexFile): void {
  $items = ht_load_news_items(dirname(__DIR__));
  $out = [];
  foreach ($items as $item) {
    $item = ht_normalize_news_item($item, (string)($item['source_file'] ?? ''), (int)($item['_mtime'] ?? 0));
    unset($item['_mtime']);
    $out[] = $item;
  }
  smurf_write_json($newsIndexFile, $out);
}

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

if ($action === 'delete' && $file) {
  if (!$CAN_EDIT) smurf_admin_denied('You do not have permission to delete news.');
  $sf = safe_news_file($file);
  if ($sf && file_exists($newsDir . $sf)) {
    @copy($newsDir . $sf, $newsDir . $sf . '.bak');
    unlink($newsDir . $sf);
    rebuild_news_index($newsDir, $newsIndexFile);
  }
  header('Location: /admin/news.php?deleted=1');
  exit;
}

$editFile = ($action === 'edit' && $file) ? safe_news_file($file) : '';
$post = news_defaults();
if ($editFile && file_exists($newsDir . $editFile)) {
  $post = ht_normalize_news_item(smurf_read_json($newsDir . $editFile, []), $editFile, (int)@filemtime($newsDir . $editFile));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!$CAN_EDIT) smurf_admin_denied('You do not have permission to edit news.');
  $editFile = safe_news_file($_POST['edit_file'] ?? '');
  if (isset($_POST['create_new']) && $_POST['create_new'] === '1') $editFile = '';
  $post = news_defaults();
  $post['title'] = trim((string)($_POST['title'] ?? ''));
  $post['author'] = trim((string)($_POST['author'] ?? ($_SESSION['user'] ?? 'Admin')));
  $post['date'] = trim((string)($_POST['date'] ?? date('Y-m-d')));
  $post['tag'] = trim((string)($_POST['tag'] ?? ''));
  $post['content'] = trim((string)($_POST['content'] ?? ''));
  $post['body'] = $post['content'];
  $post['image'] = trim((string)($_POST['image'] ?? ''));
  if ($post['image'] === '') {
    $uploaded = smurf_handle_upload('image_file', __DIR__ . '/../img/content');
    if ($uploaded !== '') {
      $post['image'] = $uploaded;
    } elseif ($editFile && file_exists($newsDir . $editFile)) {
      $existing = smurf_read_json($newsDir . $editFile, []);
      if (is_array($existing) && !empty($existing['image'])) $post['image'] = (string)$existing['image'];
    }
  }
  $post['published'] = isset($_POST['published']) ? 1 : 0;
  $post['featured_home'] = isset($_POST['featured_home']) ? 1 : 0;

  if ($post['title'] === '') $post['title'] = 'News Update';
  $slug = preg_replace('/[^a-z0-9]+/i', '-', strtolower($post['title']));
  $slug = trim((string)$slug, '-');
  if ($slug === '') $slug = 'post';
  $fname = $editFile ?: (date('Ymd_His') . '_' . substr(md5(uniqid('', true)), 0, 6) . '_' . $slug . '.json');
  $post['source_file'] = $fname;
  smurf_write_json($newsDir . $fname, $post);
  rebuild_news_index($newsDir, $newsIndexFile);
  $target = $editFile ? ('/admin/news.php?action=edit&file=' . urlencode($fname) . '&saved=1') : '/admin/news.php?created=1';
  header('Location: ' . $target);
  exit;
}

$allItems = ht_load_news_items(dirname(__DIR__));
$q = smurf_q('q');
$status = strtolower(smurf_q('status', 'all'));
$items = array_values(array_filter($allItems, function($item) use ($q, $status) {
  $haystack = implode(' ', [
    (string)($item['title'] ?? ''),
    (string)($item['author'] ?? ''),
    (string)($item['tag'] ?? ''),
    (string)($item['content'] ?? ''),
  ]);
  if (!smurf_match_text($haystack, $q)) return false;
  return match ($status) {
    'published' => !empty($item['published']),
    'draft' => empty($item['published']),
    'featured' => !empty($item['featured_home']),
    default => true,
  };
}));
$stats = [
  'all' => count($allItems),
  'published' => count(array_filter($allItems, fn($i) => !empty($i['published']))),
  'draft' => count(array_filter($allItems, fn($i) => empty($i['published']))),
  'featured' => count(array_filter($allItems, fn($i) => !empty($i['featured_home']))),
];
$uploadError = (string)($GLOBALS['SMURF_UPLOAD_ERROR'] ?? '');
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <h1 class="admin-title">📰 News Manager</h1>
  <p style="opacity:.8;">Create multiple news posts, feature one on the homepage, and keep the public news page in sync.</p>

  <?php if (isset($_GET['saved'])): ?><div class="msg success">News post updated.</div><?php endif; ?>
  <?php if (isset($_GET['created'])): ?><div class="msg success">News post created.</div><?php endif; ?>
  <?php if (isset($_GET['deleted'])): ?><div class="msg success">News post deleted.</div><?php endif; ?>
  <?php if ($uploadError !== ''): ?><div class="msg error"><?= smurf_h($uploadError) ?></div><?php endif; ?>

  <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px;margin:12px 0 18px;">
    <div class="content-card"><strong><?= (int)$stats['all'] ?></strong><div>Total posts</div></div>
    <div class="content-card"><strong><?= (int)$stats['published'] ?></strong><div>Published</div></div>
    <div class="content-card"><strong><?= (int)$stats['draft'] ?></strong><div>Drafts</div></div>
    <div class="content-card"><strong><?= (int)$stats['featured'] ?></strong><div>Featured</div></div>
  </div>

  <div class="admin-wrap stack" style="margin-top:10px;">
    <section class="content-card" style="text-align:left;">
      <div style="display:flex;justify-content:space-between;gap:10px;align-items:center;flex-wrap:wrap;">
        <h3 style="margin:0;"><?= $editFile ? 'Edit News Post' : 'Create News Post' ?></h3>
        <?php if ($editFile): ?><a class="admin-btn" href="/admin/news.php">Create New Post</a><?php endif; ?>
      </div>

      <form method="POST" enctype="multipart/form-data" class="form" style="margin-top:12px;">
        <input type="hidden" name="edit_file" value="<?= smurf_h($editFile) ?>">
        <input type="hidden" name="create_new" value="0">
        <label>Title</label>
        <input class="input-field" name="title" value="<?= smurf_h((string)$post['title']) ?>" required <?= $CAN_EDIT ? '' : 'disabled' ?>>

        <label>Author</label>
        <input class="input-field" name="author" value="<?= smurf_h((string)$post['author']) ?>" <?= $CAN_EDIT ? '' : 'disabled' ?>>

        <label>Date (YYYY-MM-DD)</label>
        <input class="input-field" name="date" value="<?= smurf_h((string)$post['date']) ?>" <?= $CAN_EDIT ? '' : 'disabled' ?>>

        <label>Tag</label>
        <input class="input-field" name="tag" value="<?= smurf_h((string)$post['tag']) ?>" <?= $CAN_EDIT ? '' : 'disabled' ?>>

        <label>Image Link (optional)</label>
        <input class="input-field" name="image" value="<?= smurf_h((string)$post['image']) ?>" placeholder="https://example.com/image.jpg" <?= $CAN_EDIT ? '' : 'disabled' ?>>

        <label>Or Upload Image File</label>
        <input class="input-field" type="file" name="image_file" accept="image/*" <?= $CAN_EDIT ? '' : 'disabled' ?>>

        <?php $previewImage = ht_asset_url((string)($post['image'] ?? ''), 'img/content'); ?>
        <?php 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((string)$post['content']) ?></textarea>
        <?php if ($CAN_EDIT): ?><div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:12px;"><button class="admin-btn primary" type="submit"><?= $editFile ? 'Save Changes' : 'Create Post' ?></button><?php if ($editFile): ?><button class="admin-btn" type="submit" onclick="this.form.create_new.value='1';">Save as New Post</button><?php endif; ?></div><?php endif; ?>
      </form>
    </section>

    <section class="content-card" style="text-align:left;">
      <div style="display:flex;justify-content:space-between;gap:10px;align-items:center;flex-wrap:wrap;">
        <h3 style="margin:0;">Existing Posts</h3>
        <form method="get" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
          <input class="input-field" type="text" name="q" value="<?= smurf_h($q) ?>" placeholder="Search title, tag or content" style="min-width:220px;">
          <select class="input-field" name="status" style="min-width:160px;">
            <option value="all" <?= $status === 'all' ? 'selected' : '' ?>>All posts</option>
            <option value="published" <?= $status === 'published' ? 'selected' : '' ?>>Published</option>
            <option value="draft" <?= $status === 'draft' ? 'selected' : '' ?>>Drafts</option>
            <option value="featured" <?= $status === 'featured' ? 'selected' : '' ?>>Featured</option>
          </select>
          <button class="admin-btn" type="submit">Filter</button>
          <?php if ($q !== '' || $status !== 'all'): ?><a class="admin-btn" href="/admin/news.php">Reset</a><?php endif; ?>
        </form>
      </div>

      <?php if (empty($items)): ?>
        <p>No posts match this view.</p>
      <?php else: ?>
        <?php foreach ($items as $j): $name = (string)($j['source_file'] ?? ''); $imageSrc = ht_asset_url((string)($j['image'] ?? ''), 'img/content'); ?>
          <div class="content-card" style="text-align:left; margin-bottom:12px;">
            <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((string)$j['title']) ?>" style="width:110px;height:80px;object-fit:cover;border-radius:14px;flex:0 0 auto;"><?php endif; ?>
                <div>
                  <strong><?= smurf_h((string)$j['title']) ?></strong>
                  <div style="opacity:.8;font-size:.95em;"><?= smurf_h((string)$j['date']) ?><?php if(!empty($j['author'])): ?> • <?= smurf_h((string)$j['author']) ?><?php endif; ?><?php if($name !== ''): ?> • <code><?= smurf_h($name) ?></code><?php endif; ?></div>
                  <?php if (!empty($j['tag'])): ?><div style="opacity:.75;margin-top:4px;">Tag: <?= smurf_h((string)$j['tag']) ?></div><?php endif; ?>
                  <div style="margin-top:6px; display:flex; gap:8px; flex-wrap:wrap;">
                    <span class="badge" style="background:<?= empty($j['published']) ? 'rgba(255,255,255,.08)' : 'rgba(0,204,136,.18)' ?>;padding:4px 8px;border-radius:999px;"><?= empty($j['published']) ? 'Draft' : 'Published' ?></span>
                    <?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>
                  <?php if (!empty($j['content'])): ?><div style="margin-top:8px;opacity:.9;"><?= smurf_h(mb_strimwidth((string)$j['content'], 0, 180, '…', 'UTF-8')) ?></div><?php endif; ?>
                </div>
              </div>
              <div style="display:flex;gap:8px;">
                <?php if($name !== ''): ?><a class="admin-btn" href="/admin/news.php?action=edit&file=<?= urlencode($name) ?>">Edit</a><?php endif; ?>
                <?php if ($CAN_EDIT && $name !== ''): ?><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'; ?>
