<?php require_once __DIR__ . '/includes/admin_bootstrap.php';
ugfx_require_permission('events');
$items = ugfx_read_json($ugfx['storage']['events'], []);
$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'] ?? $item['title'] ?? '') !== $id));
        ugfx_write_json($ugfx['storage']['events'], $items);
        $message = 'Event 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'] ?? '')),
            'start' => trim((string)($_POST['start'] ?? '')),
            'end' => trim((string)($_POST['end'] ?? '')),
            'description' => trim((string)($_POST['description'] ?? '')),
            'image' => $image,
            'published' => isset($_POST['published']) ? 1 : 0,
            'featured_home' => isset($_POST['featured_home']) ? 1 : 0,
            'show_entry_form' => isset($_POST['show_entry_form']) ? 1 : 0,
            'show_external_link' => isset($_POST['show_external_link']) ? 1 : 0,
            'external_url' => trim((string)($_POST['external_url'] ?? '')),
            'external_label' => trim((string)($_POST['external_label'] ?? 'Open event')),
            'prizes' => array_values(array_filter(array_map('trim', preg_split('/\r\n|\r|\n/', (string)($_POST['prizes'] ?? ''))))),
        ];
        $updated = false;
        foreach ($items as &$item) { if ((string)($item['id'] ?? $item['title'] ?? '') === $id) { $item = $entry; $updated = true; break; } }
        unset($item);
        if (!$updated) $items[] = $entry;
        ugfx_write_json($ugfx['storage']['events'], array_values($items));
        $message = $updated ? 'Event updated.' : 'Event created.';
    }
    $items = ugfx_read_json($ugfx['storage']['events'], []);
}
$editId = (string)($_GET['edit'] ?? '');
foreach ($items as $item) { if ((string)($item['id'] ?? $item['title'] ?? '') === $editId) { $editing = $item; break; } }
$adminTitle='Events'; 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">EVENT CONTROL</div><h3><?= $editing ? 'Edit event' : 'Create event' ?></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="Event title" required value="<?= htmlspecialchars((string)($editing['title'] ?? '')) ?>"></div><div class="col-md-6"><input class="form-control" name="start" placeholder="2026-04-03 00:00" value="<?= htmlspecialchars((string)($editing['start'] ?? '')) ?>"></div><div class="col-md-6"><input class="form-control" name="end" placeholder="2026-04-06 22:00" value="<?= htmlspecialchars((string)($editing['end'] ?? '')) ?>"></div><div class="col-12"><label class="form-label">Event description</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['description'] ?? '') : '' ?></div><textarea class="form-control d-none" name="description" data-editor-target required><?= htmlspecialchars((string)($editing['description'] ?? '')) ?></textarea></div><div class="col-12"><textarea class="form-control" name="prizes" rows="4" placeholder="One prize per line"><?= htmlspecialchars(implode(PHP_EOL, (array)($editing['prizes'] ?? []))) ?></textarea></div><div class="col-md-6"><input class="form-control" name="image" placeholder="Image URL" 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="Event image" style="max-width:220px;border-radius:14px;"></div><?php endif; ?><div class="col-md-6"><input class="form-control" name="external_url" placeholder="External link" value="<?= htmlspecialchars((string)($editing['external_url'] ?? '')) ?>"></div><div class="col-md-6"><input class="form-control" name="external_label" placeholder="External link label" value="<?= htmlspecialchars((string)($editing['external_label'] ?? 'Open event')) ?>"></div><div class="col-md-6 d-flex align-items-center"><div class="form-check"><input class="form-check-input" type="checkbox" name="published" id="eventPublished" <?= !isset($editing['published']) || !empty($editing['published']) ? 'checked' : '' ?>><label class="form-check-label" for="eventPublished">Published</label></div></div><div class="col-md-6 d-flex align-items-center"><div class="form-check"><input class="form-check-input" type="checkbox" name="featured_home" id="eventFeatured" <?= !empty($editing['featured_home']) ? 'checked' : '' ?>><label class="form-check-label" for="eventFeatured">Feature on home</label></div></div><div class="col-md-6 d-flex align-items-center"><div class="form-check"><input class="form-check-input" type="checkbox" name="show_entry_form" id="eventEntry" <?= !empty($editing['show_entry_form']) ? 'checked' : '' ?>><label class="form-check-label" for="eventEntry">Show entry form</label></div></div><div class="col-md-6 d-flex align-items-center"><div class="form-check"><input class="form-check-input" type="checkbox" name="show_external_link" id="eventExternal" <?= !empty($editing['show_external_link']) ? 'checked' : '' ?>><label class="form-check-label" for="eventExternal">Show external link</label></div></div><div class="col-12 d-flex gap-2 flex-wrap"><button class="btn ugfx-btn-primary">Save event</button><?php if ($editing): ?><a class="btn ugfx-btn-outline" href="events.php">New event</a><?php endif; ?></div></form></div>
  <div class="ugfx-card p-4"><div class="ugfx-admin-toolbar"><div><div class="ugfx-micro-label">EVENT LIST</div><h3 class="mb-0">Manage events</h3></div><span class="ugfx-chip"><?= count($items) ?> events</span></div><div class="ugfx-admin-list"><?php foreach (array_reverse($items) as $item): ?><div class="ugfx-admin-item"><h4><?= htmlspecialchars((string)($item['title'] ?? 'Event')) ?></h4><div class="ugfx-admin-meta"><span><?= htmlspecialchars((string)($item['start'] ?? '')) ?></span><span><?= !empty($item['featured_home']) ? 'Featured home' : 'Standard' ?></span><span><?= !empty($item['published']) ? 'Published' : 'Draft' ?></span></div><div class="mt-2 text-secondary"><?= htmlspecialchars(ugfx_excerpt((string)($item['description'] ?? ''), 180)) ?></div><div class="ugfx-admin-actions"><a class="btn ugfx-btn-outline btn-sm" href="events.php?edit=<?= urlencode((string)($item['id'] ?? $item['title'] ?? '')) ?>">Edit</a><form method="post" onsubmit="return confirm('Delete this event?');"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= htmlspecialchars((string)($item['id'] ?? $item['title'] ?? '')) ?>"><button class="btn btn-outline-danger btn-sm">Delete</button></form></div></div><?php endforeach; ?><?php if (!$items): ?><div class="ugfx-admin-empty">No events yet.</div><?php endif; ?></div></div>
</div>
<script src="../assets/js/admin-editor.js"></script>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
