<?php
// superadmin/manage-invitees.php
session_start();
require_once '../includes/config.php';
require_once '../includes/sa_auth.php';
require_once '../includes/db.php';
requireSuperAdmin();

$pdo = getDB();
$id  = intval($_GET['id'] ?? 0);
$proj = $pdo->prepare("SELECT * FROM projects WHERE id=?");
$proj->execute([$id]);
$p = $proj->fetch();
if (!$p) { header('Location: index.php'); exit; }

$msg = '';
$err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token    = trim($_POST['token'] ?? '');
    $invitees = array_filter(array_map('trim', $_POST['invitees'] ?? []));
    if ($token && $invitees) {
        $stmt = $pdo->prepare("SELECT id FROM invitations WHERE project_id=? AND token=?");
        $stmt->execute([$id, $token]);
        $inv = $stmt->fetch();
        if (!$inv) {
            $pdo->prepare("INSERT INTO invitations (project_id,token) VALUES (?,?)")->execute([$id, $token]);
            $inv_id = $pdo->lastInsertId();
        } else {
            $inv_id = $inv['id'];
        }
        $iStmt = $pdo->prepare("INSERT INTO invitees (invitation_id,name) VALUES (?,?)");
        foreach ($invitees as $name) $iStmt->execute([$inv_id, $name]);
        $msg = "Added " . count($invitees) . " invitees. Link: <code>" . PROJECTS_URL . "/" . urlencode($p['directory_name']) . "/index.html?token=" . urlencode($token) . "</code>";
    } else {
        $err = 'Token and at least one name are required.';
    }
}

$rows = $pdo->prepare("SELECT i.token, iv.id, iv.name, iv.response_status FROM invitations i JOIN invitees iv ON i.id=iv.invitation_id WHERE i.project_id=? ORDER BY i.created_at DESC, iv.id");
$rows->execute([$id]);
$all = $rows->fetchAll();
$grouped = [];
foreach ($all as $r) $grouped[$r['token']][] = $r;
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Manage Invitees</title>
  <link rel="stylesheet" href="sa.css"/>
</head>
<body>
<div class="sa-wrapper">
  <?php include 'sidebar.php'; ?>
  <div class="sa-main">
    <?php include 'topbar.php'; ?>
    <div class="sa-content">

      <div class="alert alert-info">
        <strong><?= htmlspecialchars($p['groom_name']) ?> &amp; <?= htmlspecialchars($p['bride_name']) ?></strong>
      </div>

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

      <div class="card">
        <div class="card-header"><span class="card-title">➕ Add Invitees</span></div>
        <div class="tabs">
          <button class="tab-btn active" onclick="showTab('manual',this)">Manual Entry</button>
          <button class="tab-btn" onclick="showTab('excel',this)">Import Excel</button>
        </div>

        <div id="tab-manual" class="tab-pane active">
          <form method="post">
            <div class="form-group" style="max-width:400px;margin-bottom:16px;">
              <label>Token / Group ID (unique per invitation link)</label>
              <input type="text" name="token" placeholder="e.g. family_smith_a1b2" required/>
            </div>
            <div id="inviteeContainer">
              <div class="invitee-row">
                <input type="text" name="invitees[]" placeholder="Full Name" required/>
                <button type="button" class="btn btn-danger btn-sm" onclick="removeRow(this)">✕</button>
              </div>
            </div>
            <button type="button" class="btn btn-outline btn-sm" onclick="addRow()" style="margin:12px 0;">+ Add Person</button><br/>
            <button type="submit" class="btn btn-primary">Save Invitees</button>
          </form>
        </div>

        <div id="tab-excel" class="tab-pane">
          <p style="color:var(--text-muted);font-size:14px;margin-bottom:16px;">
            Upload an Excel file (.xlsx) with two columns: <strong>Token</strong> (col A) and <strong>Name</strong> (col B). Row 1 = headers.
          </p>
          <a href="download-template.php" class="btn btn-outline btn-sm" style="margin-bottom:20px;">⬇ Download Excel Template</a>
          <form method="post" action="import-excel.php?id=<?= $id ?>" enctype="multipart/form-data">
            <div class="file-zone" style="max-width:400px;">
              <div class="file-icon">📊</div>
              <p>Click to upload <strong>.xlsx</strong> file</p>
              <input type="file" name="excel_file" accept=".xlsx,.xls" required/>
            </div>
            <br/>
            <button type="submit" class="btn btn-primary">Import</button>
          </form>
        </div>
      </div>

      <!-- Current invitees -->
      <div class="card">
        <div class="card-header">
          <span class="card-title">Current Invitees (<?= count($all) ?>)</span>
        </div>
        <?php if (empty($grouped)): ?>
          <p style="color:var(--text-muted);text-align:center;padding:24px;">No invitees yet.</p>
        <?php else: foreach ($grouped as $token => $invitees): ?>
          <div style="margin-bottom:20px;padding:16px;background:var(--dark4);border-radius:8px;">
            <div style="margin-bottom:8px;">
              <strong style="color:var(--gold);"><?= htmlspecialchars($token) ?></strong>
              <span style="font-size:12px;color:var(--text-muted);margin-left:10px;">
                Link: <?= PROJECTS_URL ?>/<?= urlencode($p['directory_name']) ?>/index.html?token=<?= urlencode($token) ?>
              </span>
            </div>
            <table class="sa-table">
              <?php foreach ($invitees as $iv): ?>
              <tr>
                <td><?= htmlspecialchars($iv['name']) ?></td>
                <td>
                  <?php if ($iv['response_status'] === 'Accept'): ?>
                    <span class="badge-status badge-accept">Accepted</span>
                  <?php elseif ($iv['response_status'] === 'Decline'): ?>
                    <span class="badge-status badge-decline">Declined</span>
                  <?php else: ?>
                    <span class="badge-status badge-pending">Pending</span>
                  <?php endif; ?>
                </td>
              </tr>
              <?php endforeach; ?>
            </table>
          </div>
        <?php endforeach; endif; ?>
      </div>

      <a href="index.php" class="btn btn-outline">← Dashboard</a>

    </div>
  </div>
</div>

<script>
function showTab(id, btn) {
  document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('active'));
  document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
  document.getElementById('tab-'+id).classList.add('active');
  btn.classList.add('active');
}
function addRow() {
  const c = document.getElementById('inviteeContainer');
  const d = document.createElement('div');
  d.className = 'invitee-row';
  d.innerHTML = '<input type="text" name="invitees[]" placeholder="Full Name" required/><button type="button" class="btn btn-danger btn-sm" onclick="removeRow(this)">✕</button>';
  c.appendChild(d);
}
function removeRow(b) { b.parentNode.remove(); }
</script>
</body>
</html>
