<?php
// ============================================================
//  admin/import_ebabe.php
//  Pull "Yes" RSVPs from the public E-Babe RSVP site's database
//  and turn them into guest rows (one ticket per head) on a
//  chosen event, ready for the Ticket Designer + Generate Invites.
//
//  Additive & self-contained: reads the E-Babe DB via ebabeDb()
//  (separate creds in config.local.php), writes only into this
//  system's own `guests` table using the standard schema.
// ============================================================
require_once __DIR__ . '/../config.php';
adminGuard();
requireCsrf();
require_once __DIR__ . '/_layout.php';

$db    = db();
$msg   = '';
$error = '';

// ── Events belonging to this admin (for the target picker) ───
$evStmt = $db->prepare('SELECT id, title FROM events WHERE admin_id=? ORDER BY title');
$evStmt->execute([$_SESSION['admin_id']]);
$myEvents = $evStmt->fetchAll();

// ── Admin guest-limit ────────────────────────────────────────
$adminData = $db->prepare('SELECT * FROM admins WHERE id=?');
$adminData->execute([$_SESSION['admin_id']]);
$limits    = planLimits($adminData->fetch());
$maxGuests = $limits['max_guests']; // null = unlimited

$ebabe   = ebabeDb();
$srcEvent = EBABE_EVENT_ID;

// ── Fetch the source "Yes" RSVPs (attending only) ────────────
$rsvps = [];
$srcError = '';
if (!$ebabe) {
    $srcError = 'The E-Babe RSVP database is not configured. Add EBABE_DB_* values to config.local.php.';
} else {
    try {
        $q = $ebabe->prepare(
            "SELECT id, full_name, email, phone, category, party_size, note, created_at
             FROM rsvp_responses
             WHERE event_id = :eid AND attendance = 'yes'
             ORDER BY created_at DESC, id DESC"
        );
        $q->execute(['eid' => $srcEvent]);
        $rsvps = $q->fetchAll();
    } catch (Throwable $e) {
        $srcError = 'Could not read the E-Babe RSVP database: ' . $e->getMessage();
    }
}

/**
 * Guests already present in the target event, keyed by the
 * primary RSVP identity (email + full name) so re-running the
 * import skips whole parties that were brought over before.
 */
function importedKeys(PDO $db, int $eventId): array {
    $seen = [];
    $s = $db->prepare('SELECT name, email FROM guests WHERE event_id=?');
    $s->execute([$eventId]);
    foreach ($s->fetchAll() as $r) {
        $seen[rsvpKey($r['name'], $r['email'])] = true;
    }
    return $seen;
}

/** Normalised identity for an RSVP / guest primary row. */
function rsvpKey(?string $name, ?string $email): string {
    return mb_strtolower(trim((string)$name)) . '|' . mb_strtolower(trim((string)$email));
}

// ── Handle import ────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['import_rsvps'])) {
    $targetId = (int)($_POST['target_event'] ?? 0);

    // Verify the target event belongs to this admin
    $chk = $db->prepare('SELECT id, title FROM events WHERE id=? AND admin_id=?');
    $chk->execute([$targetId, $_SESSION['admin_id']]);
    $targetEvent = $chk->fetch();

    if (!$targetEvent) {
        $error = 'Please choose one of your events as the destination.';
    } elseif (!$ebabe) {
        $error = 'The E-Babe RSVP database is not configured.';
    } else {
        // Which RSVP ids did the admin tick? (empty = all shown)
        $picked = array_filter(array_map('intval', (array)($_POST['rsvp_ids'] ?? [])));
        $pickSet = $picked ? array_flip($picked) : null;

        // Live guest count for limit enforcement
        $cntStmt = $db->prepare('SELECT COUNT(*) FROM guests WHERE event_id=?');
        $cntStmt->execute([$targetId]);
        $liveCount = (int)$cntStmt->fetchColumn();

        $seen = importedKeys($db, $targetId);

        $ins = $db->prepare(
            'INSERT INTO guests (event_id,name,email,phone,category,token)
             VALUES (?,?,?,?,?,?)'
        );

        $rsvpCount = 0;   // RSVPs brought over
        $headCount = 0;   // total guest rows created (one per head)
        $skippedDup = 0;
        $skippedLimit = 0;
        $limitHit = false;

        foreach ($rsvps as $r) {
            if ($pickSet !== null && !isset($pickSet[(int)$r['id']])) continue;

            $primaryName = trim((string)$r['full_name']);
            if ($primaryName === '') continue;

            // Skip whole party if this RSVP was already imported
            if (isset($seen[rsvpKey($primaryName, $r['email'])])) { $skippedDup++; continue; }

            $party = max(1, min(20, (int)$r['party_size'])); // safety clamp
            $category = trim((string)$r['category']);
            $email = trim((string)$r['email']);
            $phone = trim((string)$r['phone']);

            for ($i = 1; $i <= $party; $i++) {
                if ($maxGuests !== null && $liveCount >= $maxGuests) { $limitHit = true; break; }

                // Primary head keeps the real name / email / phone.
                // Additional heads get a distinct name so each has its own QR,
                // and no email/phone (they belong to the primary contact).
                $rowName  = $i === 1 ? $primaryName : $primaryName . ' (guest ' . $i . ')';
                $rowEmail = $i === 1 && $email !== '' ? $email : null;
                $rowPhone = $i === 1 && $phone !== '' ? $phone : null;

                $ins->execute([
                    $targetId,
                    $rowName,
                    $rowEmail,
                    $rowPhone,
                    $category !== '' ? $category : null,
                    generateToken(),
                ]);
                $liveCount++;
                $headCount++;
            }

            // Mark the primary identity as seen so a re-run won't duplicate
            $seen[rsvpKey($primaryName, $email)] = true;

            if ($limitHit) { $skippedLimit++; break; }
            $rsvpCount++;
        }

        adminLog('ebabe.import', 'event', $targetId,
            "{$rsvpCount} RSVPs / {$headCount} guests from E-Babe");

        $msg = "Imported {$rsvpCount} RSVP(s) as {$headCount} guest(s) into "
             . $targetEvent['title'] . '.';
        $notes = [];
        if ($skippedDup)   $notes[] = "{$skippedDup} already imported (skipped)";
        if ($skippedLimit || $limitHit) {
            $notes[] = "guest limit of {$maxGuests} reached — remaining RSVPs skipped";
        }
        if ($notes) $error = ucfirst(implode('; ', $notes)) . '.';

        // Refresh the list so imported rows visibly drop to "already imported"
        // on the next render for whichever event is chosen.
    }
}

// Precompute per-target "already imported" sets for the currently
// selected event so the table can flag rows without a re-import.
$selectedTarget = (int)($_POST['target_event'] ?? ($myEvents[0]['id'] ?? 0));
$alreadySet = [];
if ($selectedTarget) {
    try { $alreadySet = importedKeys($db, $selectedTarget); } catch (Throwable $e) {}
}

$totalHeads = 0;
foreach ($rsvps as $r) { $totalHeads += max(1, (int)$r['party_size']); }

layout_start('Import E-Babe RSVPs', 'import_ebabe');
?>
<div style="max-width:1080px">
  <div class="event-workspace-head">
    <div class="event-workspace-title">
      <span class="ews-name">Import E-Babe RSVPs</span>
    </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 ($srcError): ?><div class="alert alert-danger"><?= htmlspecialchars($srcError) ?></div><?php endif; ?>

  <div class="alert alert-info" style="font-size:.82rem;margin-bottom:20px">
    Guests who RSVP’d <strong>“Yes”</strong> on the public E-Babe site are listed below.
    Choose one of your events, tick the people to bring over (or leave all ticked), and
    import. Each RSVP becomes <strong>one guest row per head</strong> in the party — every
    attendee gets their own QR ticket. Already-imported guests are skipped automatically,
    so it’s safe to run this again as more RSVPs arrive. After importing, open
    <strong>Tickets</strong> to design the QR ticket, then <strong>Guests → Generate invites</strong>.
  </div>

  <?php if ($ebabe && !$srcError): ?>
  <form method="post">
    <?= csrfField() ?>
    <div style="display:flex;gap:14px;align-items:flex-end;flex-wrap:wrap;margin-bottom:18px">
      <div>
        <label style="display:block;font-size:.72rem;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);margin-bottom:6px">Destination event</label>
        <select name="target_event" style="min-width:260px;padding:10px 12px" onchange="this.form.submit()">
          <?php if (!$myEvents): ?>
            <option value="">— you have no events yet —</option>
          <?php else: foreach ($myEvents as $ev): ?>
            <option value="<?= (int)$ev['id'] ?>" <?= $ev['id'] == $selectedTarget ? 'selected' : '' ?>>
              <?= htmlspecialchars($ev['title']) ?>
            </option>
          <?php endforeach; endif; ?>
        </select>
      </div>
      <div style="color:var(--muted);font-size:.82rem;padding-bottom:10px">
        <strong style="color:var(--white)"><?= count($rsvps) ?></strong> attending RSVP(s)
        · <strong style="color:var(--white)"><?= $totalHeads ?></strong> total head(s)
      </div>
    </div>

    <?php if (!$rsvps): ?>
      <div class="alert alert-info">No “Yes” RSVPs found for event <code><?= htmlspecialchars($srcEvent) ?></code> yet.</div>
    <?php else: ?>
    <div style="overflow-x:auto">
      <table class="data-table" style="width:100%">
        <thead>
          <tr>
            <th style="width:34px"><input type="checkbox" id="chkAll" checked onclick="document.querySelectorAll('.rsvpchk:not(:disabled)').forEach(c=>c.checked=this.checked)"></th>
            <th>Name</th>
            <th>Category</th>
            <th>Party</th>
            <th>Email</th>
            <th>Phone</th>
            <th>RSVP’d</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($rsvps as $r):
            $already = isset($alreadySet[rsvpKey($r['full_name'], $r['email'])]); ?>
          <tr<?= $already ? ' style="opacity:.5"' : '' ?>>
            <td>
              <input type="checkbox" class="rsvpchk" name="rsvp_ids[]" value="<?= (int)$r['id'] ?>"
                     <?= $already ? 'disabled' : 'checked' ?>>
            </td>
            <td><?= htmlspecialchars($r['full_name']) ?></td>
            <td><?= htmlspecialchars($r['category'] ?: '—') ?></td>
            <td><?= max(1, (int)$r['party_size']) ?></td>
            <td><?= htmlspecialchars($r['email'] ?: '—') ?></td>
            <td><?= htmlspecialchars($r['phone'] ?: '—') ?></td>
            <td style="white-space:nowrap"><?= htmlspecialchars($r['created_at']) ?></td>
            <td><?= $already ? '<span class="badge badge-muted">Imported</span>' : '<span class="badge badge-success">New</span>' ?></td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>

    <div style="margin-top:20px">
      <button type="submit" name="import_rsvps" value="1" class="btn btn-gold"
              <?= $myEvents ? '' : 'disabled' ?>>
        Import selected → guests
      </button>
    </div>
    <?php endif; ?>
  </form>
  <?php endif; ?>
</div>
<?php layout_end(); ?>
