<?php
require_once __DIR__ . '/../config.php';
adminGuard();
requireCsrf();  // reject POSTs without a valid CSRF token
require_once __DIR__ . '/_layout.php';

$db     = db();
$action = $_GET['action'] ?? 'list';
$msg    = '';
$error  = '';

// ── Load current admin's limits ─────────────────────────────
$adminData = $db->prepare('SELECT * FROM admins WHERE id=?');
$adminData->execute([$_SESSION['admin_id']]);
$currentAdmin = $adminData->fetch();
$limits = planLimits($currentAdmin);

// ── Handle form submissions ─────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (isset($_POST['create_event'])) {
        $title    = trim($_POST['title'] ?? '');
        $slug     = slugify(trim($_POST['slug'] ?? ''));
        $desc     = trim($_POST['description'] ?? '');
        $date     = trim($_POST['event_date'] ?? '') ?: null;
        $venue    = trim($_POST['venue'] ?? '');
        $status   = in_array($_POST['status'] ?? '', ['draft','active','closed']) ? $_POST['status'] : 'draft';

        if (!$title || !$slug) {
            $error = 'Title and slug are required.';
        } elseif ($limits['max_events'] !== null) {
            // Enforce event limit
            $evCount = $db->prepare('SELECT COUNT(*) FROM events WHERE admin_id=?');
            $evCount->execute([$_SESSION['admin_id']]);
            if ((int)$evCount->fetchColumn() >= $limits['max_events']) {
                $error = "You have reached your event limit ({$limits['max_events']} events). Please contact the super admin to upgrade your account.";
            }
        }
        if (!$error) {
            // Check slug unique
            $exists = $db->prepare('SELECT id FROM events WHERE slug = ?');
            $exists->execute([$slug]);
            if ($exists->fetch()) {
                $error = 'That slug is already taken. Choose another.';
            } else {
                // Handle invite template upload
                $templatePath = null;
                $up = $_FILES['invite_template'] ?? null;
                if (!empty($up['name']) && $up['error'] === UPLOAD_ERR_OK) {
                    $ext = strtolower(pathinfo($up['name'], PATHINFO_EXTENSION));
                    if (in_array($ext, ['jpg','jpeg','png'])) {
                        $dir = null;
                        foreach ([
                            BASE_PATH . '/uploads/templates',
                            ($_SERVER['DOCUMENT_ROOT'] ?? '') . '/uploads/templates',
                        ] as $c) {
                            $c = preg_replace('#/{2,}#', '/', $c);
                            if (is_dir($c) || @mkdir($c, 0755, true)) {
                                if (is_writable($c)) { $dir = $c; break; }
                            }
                        }
                        if ($dir) {
                            $fname = $slug . '_' . time() . '.' . $ext;
                            if (move_uploaded_file($up['tmp_name'], $dir . '/' . $fname)) {
                                $templatePath = 'uploads/templates/' . $fname;
                            } else {
                                $error = 'Template upload failed — check folder permissions on uploads/templates/.';
                            }
                        } else {
                            $error = 'Cannot write to uploads/templates/ directory. Check server permissions.';
                        }
                    } else {
                        $error = 'Invite template must be JPG or PNG.';
                    }
                } elseif (!empty($up['name']) && $up['error'] !== UPLOAD_ERR_NO_FILE) {
                    $error = 'Upload error (code ' . $up['error'] . '). Check server upload settings.';
                }

                if (!$error) {
                    $ins = $db->prepare(
                        'INSERT INTO events (admin_id,title,slug,description,event_date,venue,invite_template,status)
                         VALUES (?,?,?,?,?,?,?,?)'
                    );
                    $ins->execute([
                        $_SESSION['admin_id'], $title, $slug, $desc, $date, $venue, $templatePath, $status
                    ]);
                    $newId = $db->lastInsertId();
                    adminLog('event.create', 'event', (int)$newId, $title);
                    header('Location: ' . BASE_URL . '/admin/events.php?action=view&id=' . $newId . '&msg=created');
                    exit;
                }
            }
        }
    }

    if (isset($_POST['update_event'])) {
        $id     = (int)$_POST['event_id'];
        $title  = trim($_POST['title'] ?? '');
        $slug   = slugify(trim($_POST['slug'] ?? ''));
        $desc   = trim($_POST['description'] ?? '');
        $date   = trim($_POST['event_date'] ?? '') ?: null;
        $venue  = trim($_POST['venue'] ?? '');
        $status = in_array($_POST['status'] ?? '', ['draft','active','closed']) ? $_POST['status'] : 'draft';

        // Advanced settings
        $tzIn      = trim($_POST['timezone'] ?? '');
        $timezone  = ($tzIn && in_array($tzIn, timezone_identifiers_list(), true)) ? $tzIn : null;
        $singleUse = isset($_POST['single_use_tokens']) ? 1 : 0;
        $opensAt   = trim($_POST['checkin_opens_at']  ?? '') ?: null;
        $closesAt  = trim($_POST['checkin_closes_at'] ?? '') ?: null;
        $webhook   = trim($_POST['webhook_url'] ?? '');
        $webhook   = ($webhook && filter_var($webhook, FILTER_VALIDATE_URL)) ? $webhook : null;

        $exists = $db->prepare('SELECT id FROM events WHERE slug = ? AND id != ?');
        $exists->execute([$slug, $id]);
        if ($exists->fetch()) {
            $error = 'Slug already taken.';
        } else {
            // Handle invite template upload on update
            $up = $_FILES['invite_template'] ?? null;
            if (!empty($up['name']) && $up['error'] === UPLOAD_ERR_OK) {
                $ext = strtolower(pathinfo($up['name'], PATHINFO_EXTENSION));
                if (!in_array($ext, ['jpg','jpeg','png'])) {
                    $error = 'Invite template must be JPG or PNG.';
                } else {
                    $dir = null;
                    foreach ([
                        BASE_PATH . '/uploads/templates',
                        ($_SERVER['DOCUMENT_ROOT'] ?? '') . '/uploads/templates',
                    ] as $c) {
                        $c = preg_replace('#/{2,}#', '/', $c);
                        if (is_dir($c) || @mkdir($c, 0755, true)) {
                            if (is_writable($c)) { $dir = $c; break; }
                        }
                    }
                    if ($dir) {
                        $fname = $slug . '_' . time() . '.' . $ext;
                        if (move_uploaded_file($up['tmp_name'], $dir . '/' . $fname)) {
                            $db->prepare('UPDATE events SET invite_template=? WHERE id=? AND admin_id=?')
                               ->execute(['uploads/templates/' . $fname, $id, $_SESSION['admin_id']]);
                            $msg = 'Invite template updated.';
                        } else {
                            $error = 'Template upload failed — check uploads/templates/ permissions.';
                        }
                    } else {
                        $error = 'Cannot write to uploads/templates/. Check server permissions.';
                    }
                }
            } elseif (!empty($up['name']) && $up['error'] !== UPLOAD_ERR_NO_FILE) {
                $error = 'Upload error (code ' . $up['error'] . ').';
            }

            if (!$error) {
                $upd = $db->prepare(
                    'UPDATE events SET title=?,slug=?,description=?,event_date=?,venue=?,status=?,
                        timezone=?,single_use_tokens=?,checkin_opens_at=?,checkin_closes_at=?,webhook_url=?
                     WHERE id=? AND admin_id=?'
                );
                $upd->execute([$title, $slug, $desc, $date, $venue, $status,
                    $timezone, $singleUse, $opensAt, $closesAt, $webhook,
                    $id, $_SESSION['admin_id']]);
                adminLog('event.update', 'event', $id, $title);
                $msg = $msg ?: 'Event updated.';
            }
        }
        $action = 'edit';
    }

    if (isset($_POST['delete_event'])) {
        $id = (int)$_POST['event_id'];
        $db->prepare('DELETE FROM events WHERE id=? AND admin_id=?')->execute([$id, $_SESSION['admin_id']]);
        adminLog('event.delete', 'event', $id);
        header('Location: ' . BASE_URL . '/admin/events.php?msg=deleted');
        exit;
    }
}

if (isset($_GET['msg'])) {
    $msgMap = ['created'=>'Event created.','deleted'=>'Event deleted.'];
    $msg = $msgMap[$_GET['msg']] ?? '';
}

// ── Fetch data for views ────────────────────────────────────
$eventId = (int)($_GET['id'] ?? 0);
$event   = null;

if ($action === 'edit' || $action === 'view') {
    $stmt = $db->prepare('SELECT * FROM events WHERE id=? AND admin_id=?');
    $stmt->execute([$eventId, $_SESSION['admin_id']]);
    $event = $stmt->fetch();
    if (!$event) { header('Location: ' . BASE_URL . '/admin/events.php'); exit; }
}

// List all events
$allEvents = $db->prepare(
    'SELECT e.*, COUNT(g.id) AS guest_count, SUM(g.checked_in) AS checked_count
     FROM events e LEFT JOIN guests g ON g.event_id=e.id
     WHERE e.admin_id=?
     GROUP BY e.id ORDER BY e.created_at DESC'
);
$allEvents->execute([$_SESSION['admin_id']]);
$events = $allEvents->fetchAll();

layout_start('Events', 'events');
?>

<?php if ($msg): ?><div class="alert alert-success"><?= htmlspecialchars($msg) ?></div><?php endif; ?>
<?php if ($error): ?><div class="alert alert-danger"><?= htmlspecialchars($error) ?></div><?php endif; ?>

<?php if ($action === 'create' || ($action === 'edit' && $event)): ?>

<!-- ── Create / Edit Form ───────────────────────────────── -->
<div class="page-header">
  <div>
    <div class="page-header-sub">Events</div>
    <h1><?= $action === 'create' ? 'Create Event' : 'Edit Event' ?></h1>
  </div>
  <a href="<?= BASE_URL ?>/admin/events.php" class="btn btn-outline btn-sm">← Back</a>
</div>

<div class="card" style="max-width:680px">
  <form method="POST" enctype="multipart/form-data">
    <?php if ($action === 'edit'): ?>
      <input type="hidden" name="event_id" value="<?= $event['id'] ?>">
    <?php endif; ?>

    <div class="grid-2">
      <div class="form-group">
        <label class="form-label">Event Title *</label>
        <input class="form-control" type="text" name="title"
               value="<?= htmlspecialchars($event['title'] ?? '') ?>"
               id="titleInput" required>
      </div>
      <div class="form-group">
        <label class="form-label">URL Slug *</label>
        <input class="form-control" type="text" name="slug"
               value="<?= htmlspecialchars($event['slug'] ?? '') ?>"
               id="slugInput" placeholder="my-event-2026" required>
        <div class="form-hint">Only lowercase letters, numbers, hyphens</div>
      </div>
    </div>

    <div class="form-group">
      <label class="form-label">Description</label>
      <textarea class="form-control" name="description" rows="3"><?= htmlspecialchars($event['description'] ?? '') ?></textarea>
    </div>

    <div class="grid-2">
      <div class="form-group">
        <label class="form-label">Event Date & Time</label>
        <input class="form-control" type="datetime-local" name="event_date"
               value="<?= $event['event_date'] ? date('Y-m-d\TH:i', strtotime($event['event_date'])) : '' ?>">
      </div>
      <div class="form-group">
        <label class="form-label">Venue</label>
        <input class="form-control" type="text" name="venue"
               value="<?= htmlspecialchars($event['venue'] ?? '') ?>">
      </div>
    </div>

    <div class="form-group">
      <label class="form-label">Invite Template (JPG/PNG) — optional <span class="text-muted" style="font-weight:400">(legacy — prefer the Ticket Designer)</span></label>
      <input class="form-control" type="file" name="invite_template" accept=".jpg,.jpeg,.png">
      <div class="form-hint">The QR code will be overlaid onto this image. If left empty, a default branded card is generated. For full control over layout, use the <strong>Ticket Designer</strong>.</div>
      <?php if (!empty($event['invite_template'])): ?>
        <div class="mt-2 text-muted text-sm">Current: <?= htmlspecialchars($event['invite_template']) ?></div>
      <?php endif; ?>
    </div>

    <div class="form-group">
      <label class="form-label">Status</label>
      <select class="form-control" name="status">
        <?php foreach (['draft','active','closed'] as $s): ?>
          <option value="<?= $s ?>" <?= ($event['status'] ?? 'draft') === $s ? 'selected' : '' ?>><?= ucfirst($s) ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <!-- ── Advanced settings ─────────────────────────────── -->
    <details <?= !empty($event['single_use_tokens']) || !empty($event['timezone']) || !empty($event['webhook_url']) || !empty($event['checkin_opens_at']) ? 'open' : '' ?>
             style="margin:8px 0 20px;border:1px solid var(--border);border-radius:8px;padding:14px 16px">
      <summary style="cursor:pointer;font-family:var(--font-ui);font-size:.75rem;font-weight:700;letter-spacing:.1em;text-transform:uppercase;color:var(--gold)">Advanced settings</summary>
      <div style="margin-top:16px">
        <div class="form-group">
          <label class="form-label">Timezone</label>
          <?php
            $commonTz = ['Africa/Lagos','Africa/Accra','Africa/Nairobi','Africa/Johannesburg','Europe/London',
                         'Europe/Paris','America/New_York','America/Chicago','America/Los_Angeles','Asia/Dubai',
                         'Asia/Kolkata','Asia/Singapore','Australia/Sydney','UTC'];
            $curTz = $event['timezone'] ?? '';
          ?>
          <input class="form-control" list="tzlist" name="timezone" value="<?= htmlspecialchars($curTz) ?>"
                 placeholder="<?= DEFAULT_TZ ?> (default)">
          <datalist id="tzlist">
            <?php foreach ($commonTz as $tz): ?><option value="<?= $tz ?>"><?php endforeach; ?>
          </datalist>
          <div class="form-hint">IANA name used to display event dates &amp; check-in times.</div>
        </div>
        <div class="grid-2">
          <div class="form-group">
            <label class="form-label">Check-in opens</label>
            <input class="form-control" type="datetime-local" name="checkin_opens_at"
                   value="<?= !empty($event['checkin_opens_at']) ? date('Y-m-d\TH:i', strtotime($event['checkin_opens_at'])) : '' ?>">
          </div>
          <div class="form-group">
            <label class="form-label">Check-in closes</label>
            <input class="form-control" type="datetime-local" name="checkin_closes_at"
                   value="<?= !empty($event['checkin_closes_at']) ? date('Y-m-d\TH:i', strtotime($event['checkin_closes_at'])) : '' ?>">
          </div>
        </div>
        <div class="form-group">
          <label style="display:flex;align-items:center;gap:8px;cursor:pointer">
            <input type="checkbox" name="single_use_tokens" value="1" <?= !empty($event['single_use_tokens']) ? 'checked' : '' ?>>
            <span>Single-use QR (disable undo — a checked-in ticket can't be reversed)</span>
          </label>
        </div>
        <div class="form-group" style="margin-bottom:0">
          <label class="form-label">Check-in webhook URL — optional</label>
          <input class="form-control" type="url" name="webhook_url"
                 value="<?= htmlspecialchars($event['webhook_url'] ?? '') ?>" placeholder="https://example.com/hook">
          <div class="form-hint">A JSON payload is POSTed here on every check-in.</div>
        </div>
      </div>
    </details>

    <div class="flex gap-2">
      <?php if ($action === 'create'): ?>
        <button class="btn btn-gold" name="create_event" type="submit">Create Event</button>
      <?php else: ?>
        <button class="btn btn-gold" name="update_event" type="submit">Save Changes</button>
        <form method="POST" style="display:inline"
              onsubmit="return confirm('Delete this event and all guests? This cannot be undone.')">
          <input type="hidden" name="event_id" value="<?= $event['id'] ?>">
          <button class="btn btn-danger" name="delete_event" type="submit">Delete Event</button>
        </form>
      <?php endif; ?>
    </div>
  </form>
</div>

<script>
// Auto-populate slug from title on create
<?php if ($action === 'create'): ?>
document.getElementById('titleInput').addEventListener('input', function() {
  const slug = this.value.toLowerCase().trim()
    .replace(/[^a-z0-9\s-]/g,'').replace(/\s+/g,'-').replace(/-+/g,'-');
  document.getElementById('slugInput').value = slug;
});
<?php endif; ?>
</script>

<?php elseif ($action === 'view' && $event): ?>

<!-- ── Event Detail View (Overview hub) ──────────────────── -->
<?php event_tabs((int)$event['id'], 'overview', $event['title']); ?>
<div class="page-header">
  <div>
    <div class="page-header-sub">Overview</div>
    <h1><?= htmlspecialchars($event['title']) ?></h1>
  </div>
  <div class="flex gap-2">
    <a href="<?= BASE_URL ?>/admin/events.php?action=edit&id=<?= $event['id'] ?>" class="btn btn-outline btn-sm">Edit details</a>
    <a href="<?= BASE_URL ?>/admin/guests.php?event_id=<?= $event['id'] ?>" class="btn btn-gold">Manage guests</a>
  </div>
</div>

<div class="grid-2">
  <div class="card card-sm">
    <div class="label-ui mb-2">Event Info</div>
    <table style="font-size:.85rem">
      <tr><td class="text-muted" style="padding:5px 0;width:100px">Slug</td><td><code style="color:var(--gold)">/<?= htmlspecialchars($event['slug']) ?></code></td></tr>
      <tr><td class="text-muted" style="padding:5px 0">Date</td><td><?= $event['event_date'] ? date('D, M j Y · H:i', strtotime($event['event_date'])) : '—' ?></td></tr>
      <tr><td class="text-muted" style="padding:5px 0">Venue</td><td><?= htmlspecialchars($event['venue'] ?? '—') ?></td></tr>
      <tr><td class="text-muted" style="padding:5px 0">Status</td><td><span class="badge badge-success"><?= $event['status'] ?></span></td></tr>
    </table>
  </div>
  <div class="card card-sm">
    <div class="label-ui mb-2">Event URL (for guests)</div>
    <code style="color:var(--gold);word-break:break-all;font-size:.85rem">
      <?= BASE_URL ?>/event/<?= htmlspecialchars($event['slug']) ?>
    </code>
    <div class="label-ui mt-3 mb-2">Checker Login</div>
    <code style="color:var(--info);font-size:.85rem">
      <?= BASE_URL ?>/checker/login.php
    </code>
  </div>
</div>

<?php else: ?>

<!-- ── Events List ───────────────────────────────────────── -->
<?php
$eventCount    = count($events);
$atEventLimit  = $limits['max_events'] !== null && $eventCount >= $limits['max_events'];
?>
<div class="page-header">
  <div>
    <div class="page-header-sub">Management</div>
    <h1>Events</h1>
    <?php if ($limits['max_events'] !== null): ?>
      <div class="text-muted text-sm mt-1">
        <?= $eventCount ?> / <?= $limits['max_events'] ?> events used
      </div>
    <?php endif; ?>
  </div>
  <?php if ($atEventLimit): ?>
    <span class="btn btn-outline btn-sm" style="opacity:.5;cursor:not-allowed"
          title="Event limit reached. Contact super admin to upgrade.">
      + New Event
    </span>
  <?php else: ?>
    <a href="<?= BASE_URL ?>/admin/events.php?action=create" class="btn btn-gold">
      + New Event
    </a>
  <?php endif; ?>
</div>
<?php if ($atEventLimit): ?>
  <div class="alert alert-danger" style="margin-bottom:16px">
    You have reached your event limit (<?= $limits['max_events'] ?> events). Contact the super admin to increase your limit.
  </div>
<?php endif; ?>

<div class="card">
  <div class="table-wrap">
    <table>
      <thead>
        <tr>
          <th>Event</th>
          <th>Slug</th>
          <th>Date</th>
          <th>Guests</th>
          <th>Checked In</th>
          <th>Status</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <?php if (empty($events)): ?>
          <tr><td colspan="7" class="text-muted" style="padding:32px;text-align:center">No events yet. <a href="?action=create" style="color:var(--gold)">Create one</a>.</td></tr>
        <?php endif; ?>
        <?php foreach ($events as $ev): ?>
        <tr>
          <td style="font-weight:500">
            <a href="?action=view&id=<?= $ev['id'] ?>" style="color:var(--white);text-decoration:none"><?= htmlspecialchars($ev['title']) ?></a>
          </td>
          <td><code style="color:var(--gold);font-size:.8rem">/<?= htmlspecialchars($ev['slug']) ?></code></td>
          <td class="text-muted text-sm"><?= $ev['event_date'] ? date('M j, Y', strtotime($ev['event_date'])) : '—' ?></td>
          <td><?= (int)$ev['guest_count'] ?></td>
          <td>
            <?= (int)$ev['checked_count'] ?>
            <?php if ($ev['guest_count'] > 0): ?>
              <span class="text-muted text-sm">(<?= round($ev['checked_count']/$ev['guest_count']*100) ?>%)</span>
            <?php endif; ?>
          </td>
          <td><span class="badge <?= ['draft'=>'badge-muted','active'=>'badge-success','closed'=>'badge-danger'][$ev['status']] ?>"><?= $ev['status'] ?></span></td>
          <td>
            <a href="<?= BASE_URL ?>/admin/guests.php?event_id=<?= $ev['id'] ?>" class="btn btn-outline btn-sm">Guests</a>
            <a href="?action=edit&id=<?= $ev['id'] ?>" class="btn btn-outline btn-sm">Edit</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<?php endif; ?>

<?php layout_end(); ?>
