<?php require_once __DIR__ . '/includes/admin_bootstrap.php';
ugfx_require_permission('news');
$items = ugfx_read_json($ugfx['storage']['news'], []);
$message = '';
$editing = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'save';
    if ($action === 'delete') {
        $id = (string)($_POST['id'] ?? '');
        $items = array_values(array_filter($items, fn($item) => (string)($item['id'] ?? '') !== $id));
        ugfx_write_json($ugfx['storage']['news'], $items);
        $message = 'News item deleted.';
    } else {
        $id = trim((string)($_POST['id'] ?? '')) ?: (string)(time() . random_int(100,999));
        $image = trim((string)($_POST['existing_image'] ?? ''));
        if (!empty($_FILES['image_upload']['name'])) {
            $uploaded = ugfx_upload_file($_FILES['image_upload']);
            if ($uploaded) $image = $uploaded;
        }
        if (trim((string)($_POST['image'] ?? '')) !== '') $image = trim((string)($_POST['image'] ?? ''));
        $entry = [
            'id' => $id,
            'title' => trim((string)($_POST['title'] ?? '')),
            'author' => trim((string)($_POST['author'] ?? 'UGFX Studio')),
            'date' => trim((string)($_POST['date'] ?? date('Y-m-d'))),
            'tag' => trim((string)($_POST['tag'] ?? 'Station News')),
            'excerpt' => trim((string)($_POST['excerpt'] ?? '')),
            'content' => trim((string)($_POST['content'] ?? '')),
            'image' => $image,
            'published' => isset($_POST['published']) ? 1 : 0,
        ];
        $updated = false;
        foreach ($items as &$item) { if ((string)($item['id'] ?? '') === $id) { $item = $entry; $updated = true; break; } }
        unset($item);
        if (!$updated) $items[] = $entry;
        ugfx_write_json($ugfx['storage']['news'], array_values($items));
        $message = $updated ? 'News item updated.' : 'News item created.';
    }
    $items = ugfx_read_json($ugfx['storage']['news'], []);
}
$editId = (string)($_GET['edit'] ?? '');
foreach ($items as $item) { if ((string)($item['id'] ?? '') === $editId) { $editing = $item; break; } }
$adminTitle='News'; include __DIR__ . '/includes/admin_header.php'; ?>
<?php if ($message): ?><div class="ugfx-admin-alert"><?= htmlspecialchars($message) ?></div><?php endif; ?>
<div class="ugfx-admin-grid">
  <div class="ugfx-card p-4">
    <div class="ugfx-micro-label">NEWS EDITOR</div><h3><?= $editing ? 'Edit news item' : 'Create news item' ?></h3>
    <form method="post" enctype="multipart/form-data" class="ugfx-admin-form row g-3 ugfx-rich-form">
      <input type="hidden" name="action" value="save"><input type="hidden" name="id" value="<?= htmlspecialchars((string)($editing['id'] ?? '')) ?>">
      <input type="hidden" name="existing_image" value="<?= htmlspecialchars((string)($editing['image'] ?? '')) ?>">
      <div class="col-12"><input class="form-control" name="title" placeholder="Title" required value="<?= htmlspecialchars((string)($editing['title'] ?? '')) ?>"></div>
      <div class="col-md-6"><input class="form-control" name="author" placeholder="Author" value="<?= htmlspecialchars((string)($editing['author'] ?? 'UGFX Studio')) ?>"></div>
      <div class="col-md-6"><input class="form-control" name="date" placeholder="Date label" value="<?= htmlspecialchars((string)($editing['date'] ?? date('Y-m-d'))) ?>"></div>
      <div class="col-12"><input class="form-control" name="tag" placeholder="Tag" value="<?= htmlspecialchars((string)($editing['tag'] ?? 'Station News')) ?>"></div>
      <div class="col-12"><textarea class="form-control" name="excerpt" rows="3" placeholder="Short excerpt"><?= htmlspecialchars((string)($editing['excerpt'] ?? '')) ?></textarea></div>
      <div class="col-12">
        <label class="form-label">Story body</label>
        <div class="ugfx-editor-toolbar" data-editor-toolbar>
          <button type="button" class="btn ugfx-btn-outline btn-sm" data-editor-cmd="bold">Bold</button>
          <button type="button" class="btn ugfx-btn-outline btn-sm" data-editor-cmd="italic">Italic</button>
          <button type="button" class="btn ugfx-btn-outline btn-sm" data-editor-cmd="insertUnorderedList">Bullets</button>
          <button type="button" class="btn ugfx-btn-outline btn-sm" data-editor-cmd="formatBlock" data-editor-value="h2">H2</button>
          <button type="button" class="btn ugfx-btn-outline btn-sm" data-editor-cmd="createLink">Link</button>
        </div>
        <div class="ugfx-wysiwyg" contenteditable="true" data-editor-surface><?= $editing ? (string)($editing['content'] ?? '') : '' ?></div>
        <textarea class="form-control d-none" name="content" data-editor-target required><?= htmlspecialchars((string)($editing['content'] ?? '')) ?></textarea>
      </div>
      <div class="col-md-6"><input class="form-control" name="image" placeholder="Image URL (optional)" value="<?= htmlspecialchars((string)($editing['image'] ?? '')) ?>"></div>
      <div class="col-md-6"><input class="form-control" type="file" name="image_upload" accept=".jpg,.jpeg,.png,.gif,.webp"></div>
      <?php if (!empty($editing['image'])): ?><div class="col-12"><img src="../<?= htmlspecialchars(ltrim((string)$editing['image'], '/')) ?>" alt="News image" style="max-width:220px;border-radius:14px;"></div><?php endif; ?>
      <div class="col-md-6 d-flex align-items-center"><div class="form-check"><input class="form-check-input" type="checkbox" name="published" id="newsPublished" <?= !isset($editing['published']) || !empty($editing['published']) ? 'checked' : '' ?>><label class="form-check-label" for="newsPublished">Published</label></div></div>
      <div class="col-12 d-flex gap-2 flex-wrap"><button class="btn ugfx-btn-primary">Save news</button><?php if ($editing): ?><a class="btn ugfx-btn-outline" href="news.php">New item</a><?php endif; ?></div>
    </form>
  </div>
  <div class="ugfx-card p-4"><div class="ugfx-admin-toolbar"><div><div class="ugfx-micro-label">NEWS LIST</div><h3 class="mb-0">Manage updates</h3></div><span class="ugfx-chip"><?= count($items) ?> items</span></div><div class="ugfx-admin-list"><?php foreach (array_reverse($items) as $item): ?><div class="ugfx-admin-item"><h4><?= htmlspecialchars((string)($item['title'] ?? 'Untitled')) ?></h4><div class="ugfx-admin-meta"><span><?= htmlspecialchars((string)($item['date'] ?? '')) ?></span><span><?= htmlspecialchars((string)($item['author'] ?? '')) ?></span><span><?= !empty($item['published']) ? 'Published' : 'Draft' ?></span></div><div class="mt-2 text-secondary"><?= htmlspecialchars(ugfx_excerpt((string)($item['excerpt'] ?? $item['content'] ?? ''), 160)) ?></div><div class="ugfx-admin-actions"><a class="btn ugfx-btn-outline btn-sm" href="news.php?edit=<?= urlencode((string)($item['id'] ?? '')) ?>">Edit</a><form method="post" onsubmit="return confirm('Delete this news item?');"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= htmlspecialchars((string)($item['id'] ?? '')) ?>"><button class="btn btn-outline-danger btn-sm">Delete</button></form></div></div><?php endforeach; ?><?php if (!$items): ?><div class="ugfx-admin-empty">No news items yet.</div><?php endif; ?></div></div>
</div>
<script src="../assets/js/admin-editor.js"></script>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
