<?php
require_once __DIR__ . '/lib.php';
arrow_require_login();

$file   = arrow_data_path('events.json');
$events = arrow_read_json($file, []);
$notice = '';

$action = $_POST['_action'] ?? '';
if ($action && $action !== 'login') {
    arrow_csrf_check();
}

if ($action === 'add' || $action === 'edit') {
    $title = trim($_POST['title'] ?? '');
    $start = trim($_POST['start'] ?? '');
    if ($title === '' || $start === '') {
        $notice = 'Title and start are required.';
    } else {
        $row = [
            'id'          => $action === 'edit' ? ($_POST['id'] ?? ('ev-' . uniqid())) : ('ev-' . uniqid()),
            'title'       => $title,
            'start'       => $start,
            'end'         => trim($_POST['end'] ?? '') ?: $start,
            'location'    => trim($_POST['location'] ?? ''),
            'description' => trim($_POST['description'] ?? ''),
        ];
        $found = false;
        foreach ($events as $i => $e) {
            if (($e['id'] ?? '') === $row['id']) { $events[$i] = $row; $found = true; break; }
        }
        if (!$found) $events[] = $row;
        // keep chronological
        usort($events, function ($a, $b) { return strcmp($a['start'] ?? '', $b['start'] ?? ''); });
        $notice = arrow_write_json($file, $events) ? 'Saved.' : 'Write failed (check data/ permissions).';
    }
} elseif ($action === 'delete') {
    $id = $_POST['id'] ?? '';
    $events = array_values(array_filter($events, function ($e) use ($id) { return ($e['id'] ?? '') !== $id; }));
    $notice = arrow_write_json($file, $events) ? 'Deleted.' : 'Write failed.';
}

$edit = null;
if (($_GET['edit'] ?? '') !== '') {
    foreach ($events as $e) { if (($e['id'] ?? '') === $_GET['edit']) { $edit = $e; break; } }
}
$csrf = arrow_csrf_token();
function h($s) { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
?>
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Manage Events — Arrow Admin</title>
<style>
 :root{--teal:#0F4C5C;--amber:#D68910;--ink:#1C2326;--bg:#F7F4EE;--border:#E2DED5}
 *{box-sizing:border-box}body{font-family:system-ui,sans-serif;margin:0;background:var(--bg);color:var(--ink)}
 header{background:var(--teal);color:#fff;padding:16px 24px;display:flex;justify-content:space-between;align-items:center}
 header a{color:#fff}main{max-width:860px;margin:0 auto;padding:24px}
 .notice{background:#e7f5e9;border:1px solid #b6e0bf;padding:10px 14px;border-radius:6px;margin-bottom:16px}
 form.card,table{background:#fff;border:1px solid var(--border);border-radius:8px}
 form.card{padding:20px;margin-bottom:28px}
 label{display:block;font-weight:600;margin:12px 0 4px;font-size:.9rem}
 input,textarea{width:100%;padding:10px;border:1px solid #ccc;border-radius:6px;font:inherit}
 button{padding:10px 18px;border:0;border-radius:6px;font-weight:700;cursor:pointer}
 .btn{background:var(--amber);color:var(--ink)}.btn-del{background:#c0392b;color:#fff}
 .btn-sm{padding:6px 12px;font-size:.85rem}
 table{width:100%;border-collapse:collapse;overflow:hidden}
 th,td{text-align:left;padding:10px 12px;border-bottom:1px solid var(--border);font-size:.92rem;vertical-align:top}
 th{background:#f0ece4}.row-actions{display:flex;gap:8px}
 .grid2{display:grid;grid-template-columns:1fr 1fr;gap:12px}@media(max-width:600px){.grid2{grid-template-columns:1fr}}
</style></head><body>
<header>
  <strong>Arrow · Manage Events</strong>
  <span><a href="index.html">View site</a> &nbsp;·&nbsp; <a href="?logout=1">Sign out</a></span>
</header>
<main>
  <?php if ($notice): ?><div class="notice"><?= h($notice) ?></div><?php endif; ?>

  <form class="card" method="post">
    <h2 style="margin:0 0 4px"><?= $edit ? 'Edit event' : 'Add an event' ?></h2>
    <input type="hidden" name="_csrf" value="<?= h($csrf) ?>">
    <input type="hidden" name="_action" value="<?= $edit ? 'edit' : 'add' ?>">
    <?php if ($edit): ?><input type="hidden" name="id" value="<?= h($edit['id']) ?>"><?php endif; ?>
    <label>Title</label>
    <input name="title" required value="<?= h($edit['title'] ?? '') ?>" placeholder="Free Estimate Day">
    <div class="grid2">
      <div><label>Start (date &amp; time)</label>
        <input type="datetime-local" name="start" required value="<?= h(substr($edit['start'] ?? '', 0, 16)) ?>"></div>
      <div><label>End (optional)</label>
        <input type="datetime-local" name="end" value="<?= h(substr($edit['end'] ?? '', 0, 16)) ?>"></div>
    </div>
    <label>Location (optional)</label>
    <input name="location" value="<?= h($edit['location'] ?? '') ?>" placeholder="412 Birch Ave">
    <label>Description (optional)</label>
    <textarea name="description" rows="3" placeholder="Walk-ins welcome…"><?= h($edit['description'] ?? '') ?></textarea>
    <p style="margin-top:16px"><button class="btn" type="submit"><?= $edit ? 'Save changes' : 'Add event' ?></button>
    <?php if ($edit): ?> &nbsp;<a href="manage-events.php">Cancel</a><?php endif; ?></p>
  </form>

  <h2>Current events (<?= count($events) ?>)</h2>
  <table>
    <tr><th>When</th><th>Title</th><th>Where</th><th></th></tr>
    <?php if (!$events): ?><tr><td colspan="4" style="color:#888">No events yet.</td></tr><?php endif; ?>
    <?php foreach ($events as $e): ?>
      <tr>
        <td><?= h(str_replace('T', ' ', $e['start'] ?? '')) ?></td>
        <td><?= h($e['title'] ?? '') ?></td>
        <td><?= h($e['location'] ?? '') ?></td>
        <td><div class="row-actions">
          <a class="btn btn-sm" style="text-decoration:none" href="?edit=<?= urlencode($e['id'] ?? '') ?>">Edit</a>
          <form method="post" onsubmit="return confirm('Delete this event?')">
            <input type="hidden" name="_csrf" value="<?= h($csrf) ?>">
            <input type="hidden" name="_action" value="delete">
            <input type="hidden" name="id" value="<?= h($e['id'] ?? '') ?>">
            <button class="btn-del btn-sm" type="submit">Delete</button>
          </form>
        </div></td>
      </tr>
    <?php endforeach; ?>
  </table>
</main></body></html>
