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

$db    = db();
$msg   = '';
$error = '';
$cred  = null;   // credential "save once" card data

// ── Get all events for dropdown ──────────────────────────────
$eventsAll = $db->prepare('SELECT id, title FROM events WHERE admin_id=? ORDER BY title');
$eventsAll->execute([$_SESSION['admin_id']]);
$eventsAll = $eventsAll->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (isset($_POST['add_checker'])) {
        $eventId  = (int)$_POST['event_id'];
        $name     = trim($_POST['name'] ?? '');
        $username = trim($_POST['username'] ?? '');
        $password = trim($_POST['password'] ?? '');

        if (!$name || !$username || !$password) {
            $error = 'All fields are required.';
        } else {
            // Verify event belongs to admin
            $ev = $db->prepare('SELECT id FROM events WHERE id=? AND admin_id=?');
            $ev->execute([$eventId, $_SESSION['admin_id']]);
            if (!$ev->fetch()) {
                $error = 'Invalid event.';
            } else {
                try {
                    $db->prepare(
                        'INSERT INTO checkers (event_id,name,username,password) VALUES (?,?,?,?)'
                    )->execute([
                        $eventId, $name, $username, password_hash($password, PASSWORD_BCRYPT)
                    ]);
                    adminLog('checker.create', 'checker', (int)$db->lastInsertId(), $username . ' / event #' . $eventId);
                    $cred = ['title' => "Door staff login created for {$name}",
                             'rows'  => [['Username', $username], ['Password', $password]]];
                } catch (\PDOException $e) {
                    $error = 'Username already exists for this event.';
                }
            }
        }
    }

    if (isset($_POST['delete_checker'])) {
        $id = (int)$_POST['checker_id'];
        // Ensure checker belongs to admin's event
        $check = $db->prepare(
            'SELECT c.id FROM checkers c JOIN events e ON e.id=c.event_id WHERE c.id=? AND e.admin_id=?'
        );
        $check->execute([$id, $_SESSION['admin_id']]);
        if ($check->fetch()) {
            $db->prepare('DELETE FROM checkers WHERE id=?')->execute([$id]);
            adminLog('checker.delete', 'checker', $id);
            $msg = 'Checker removed.';
        }
    }

    if (isset($_POST['reset_password'])) {
        $id       = (int)$_POST['checker_id'];
        $newPass  = trim($_POST['new_password'] ?? '');
        if (strlen($newPass) >= 4) {
            $check = $db->prepare(
                'SELECT c.id FROM checkers c JOIN events e ON e.id=c.event_id WHERE c.id=? AND e.admin_id=?'
            );
            $check->execute([$id, $_SESSION['admin_id']]);
            if ($check->fetch()) {
                $db->prepare('UPDATE checkers SET password=? WHERE id=?')
                   ->execute([password_hash($newPass, PASSWORD_BCRYPT), $id]);
                $cred = ['title' => 'Password reset', 'rows' => [['New password', $newPass]]];
            }
        } else {
            $error = 'Password must be at least 4 characters.';
        }
    }
}

// ── Fetch checkers ───────────────────────────────────────────
$filterEvent = (int)($_GET['event_id'] ?? 0);
$sql = 'SELECT c.*, e.title AS event_title,
               COUNT(DISTINCT cl.guest_id) AS checkins_done
        FROM checkers c
        JOIN events e ON e.id=c.event_id
        LEFT JOIN checkin_log cl ON cl.checker_id=c.id
        WHERE e.admin_id=?';
$params = [$_SESSION['admin_id']];
if ($filterEvent) { $sql .= ' AND c.event_id=?'; $params[] = $filterEvent; }
$sql .= ' GROUP BY c.id ORDER BY e.title, c.name';
$stmt = $db->prepare($sql);
$stmt->execute($params);
$checkers = $stmt->fetchAll();

$wsTitle = '';
foreach ($eventsAll as $ev) { if ((int)$ev['id'] === $filterEvent) { $wsTitle = $ev['title']; break; } }
layout_start('Door Staff', 'doorstaff');
event_tabs((int)$filterEvent, 'doorstaff', $wsTitle);
?>

<div class="page-header">
  <div>
    <div class="page-header-sub">Door Staff</div>
    <h1>Door Staff</h1>
  </div>
</div>

<?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 ($cred): ?>
  <div class="cred-card">
    <div class="cred-head">⚠ Save these now — the password won't be shown again</div>
    <div class="text-muted text-sm" style="margin-bottom:10px"><?= htmlspecialchars($cred['title']) ?></div>
    <?php foreach ($cred['rows'] as [$label, $val]): ?>
      <div class="cred-row">
        <span class="text-muted text-sm" style="width:90px"><?= htmlspecialchars($label) ?></span>
        <code id="cred-<?= md5($label) ?>"><?= htmlspecialchars($val) ?></code>
        <button class="btn btn-outline btn-sm" type="button" data-no-loader
                onclick="navigator.clipboard.writeText('<?= htmlspecialchars(addslashes($val)) ?>').then(()=>showToast('Copied','success'))">Copy</button>
      </div>
    <?php endforeach; ?>
  </div>
<?php endif; ?>

<div class="grid-2">

  <!-- Add checker form -->
  <div class="card">
    <div class="card-header">
      <span class="card-title">Create Door Staff Login</span>
    </div>
    <form method="POST">
      <?php if ($filterEvent): ?>
        <!-- Event is already in context — lock it, no dropdown needed -->
        <input type="hidden" name="event_id" value="<?= (int)$filterEvent ?>">
        <div class="form-group">
          <label class="form-label">Event</label>
          <div class="form-control" style="opacity:.75;pointer-events:none"><?= htmlspecialchars($wsTitle ?: 'This event') ?></div>
        </div>
      <?php else: ?>
        <div class="form-group">
          <label class="form-label">Event</label>
          <select class="form-control" name="event_id" required>
            <option value="">— Select Event —</option>
            <?php foreach ($eventsAll as $ev): ?>
              <option value="<?= $ev['id'] ?>"><?= htmlspecialchars($ev['title']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      <?php endif; ?>
      <div class="form-group">
        <label class="form-label">Full Name</label>
        <input class="form-control" type="text" name="name" required>
      </div>
      <div class="form-group">
        <label class="form-label">Username</label>
        <input class="form-control" type="text" name="username" required
               placeholder="e.g. checker01">
      </div>
      <div class="form-group">
        <label class="form-label">Password</label>
        <input class="form-control" type="text" name="password" required
               placeholder="min. 4 characters">
        <div class="form-hint">Write this down — it's shown only once after creation.</div>
      </div>
      <input type="hidden" name="add_checker" value="1">
      <button class="btn btn-gold" type="submit">Create Login</button>
    </form>
  </div>

  <!-- Checkers list -->
  <div class="card">
    <div class="card-header">
      <span class="card-title">All Door Staff</span>
      <?php if (count($eventsAll) > 1): ?>
      <form method="GET" style="display:flex;gap:6px">
        <select class="form-control" name="event_id" style="padding:6px 10px;font-size:.8rem">
          <option value="">All Events</option>
          <?php foreach ($eventsAll as $ev): ?>
            <option value="<?= $ev['id'] ?>" <?= $filterEvent===$ev['id']?'selected':'' ?>>
              <?= htmlspecialchars($ev['title']) ?>
            </option>
          <?php endforeach; ?>
        </select>
        <button class="btn btn-outline btn-sm" type="submit">Filter</button>
      </form>
      <?php endif; ?>
    </div>

    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Username</th>
            <th>Event</th>
            <th>Check-ins</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          <?php if (empty($checkers)): ?>
            <tr><td colspan="5" class="text-muted" style="padding:24px;text-align:center">No door staff yet. Create a login so your team can scan guests in.</td></tr>
          <?php endif; ?>
          <?php foreach ($checkers as $ch): ?>
          <tr>
            <td style="font-weight:500"><?= htmlspecialchars($ch['name']) ?></td>
            <td><code style="color:var(--gold);font-size:.82rem"><?= htmlspecialchars($ch['username']) ?></code></td>
            <td class="text-muted text-sm"><?= htmlspecialchars($ch['event_title']) ?></td>
            <td><span class="badge badge-info"><?= $ch['checkins_done'] ?></span></td>
            <td>
              <!-- Reset password inline -->
              <form method="POST" style="display:flex;gap:4px;align-items:center;flex-wrap:wrap">
                <input type="hidden" name="checker_id" value="<?= $ch['id'] ?>">
                <input class="form-control" type="text" name="new_password"
                       placeholder="New pass" style="width:90px;padding:5px 8px;font-size:.78rem">
                <input type="hidden" name="reset_password" value="1">
                <button class="btn btn-outline btn-sm" type="submit">Reset</button>
                <button class="btn btn-danger btn-sm" name="delete_checker" type="submit"
                        onclick="return confirm('Remove this checker?')">✕</button>
              </form>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

</div>

<div class="card mt-4 card-sm">
  <div class="label-ui mb-2">Checker Login URL</div>
  <code style="color:var(--info)"><?= BASE_URL ?>/checker/login.php</code>
  <div class="text-muted text-sm mt-2">Give checkers this URL along with their username and password for the event they're working.</div>
</div>

<?php layout_end(); ?>
