<?php
// admin/add-invitees.php

session_start();

// Check if user is authenticated
if (!isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true) {
    header("Location: login.php");
    exit;
}

// Database connection
$host = 'localhost';
$db   = 'georizmj_wedding_TM';
$user = 'georizmj_wedadmin';
$pass = 'wedadminP@ss';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// Handle form submission
$successMessage = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = trim($_POST['token'] ?? '');
    $invitees = $_POST['invitees'] ?? [];

    if (!$token) {
        $error = "Token is required.";
    } else {
        // Check if token already exists
        $stmt = $pdo->prepare("SELECT invitation_id FROM invitations WHERE token = ?");
        $stmt->execute([$token]);
        $group = $stmt->fetch();

        if (!$group) {
            // Create new token
            $pdo->prepare("INSERT INTO invitations (token) VALUES (?)")
                ->execute([$token]);
            $invitation_id = $pdo->lastInsertId();
        } else {
            $invitation_id = $group['invitation_id'];
        }

        // Insert invitees
        $stmt = $pdo->prepare("INSERT INTO invitees (invitation_id, name) VALUES (?, ?)");

        foreach ($invitees as $name) {
            $name = trim($name);
            if (!empty($name)) {
                $stmt->execute([$invitation_id, $name]);
            }
        }

        $successMessage = "Invitees successfully added!";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Add Invitees</title>
  <link rel="stylesheet" href="../css/admin.css" />
</head>
<body>

<h1>Add Invitees</h1>

<!-- Success / Error Message -->
<?php if ($successMessage): ?>
  <div class="success"><?= htmlspecialchars($successMessage) ?></div>
  <div class="token-link">
    <p>Preview Link:</p>
    <code> http://onvite.digital/TarekMichella/index.html?token=<?= urlencode($token) ?></code>
  </div>
<?php elseif ($error): ?>
  <div class="error"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>

<!-- Form -->
<form method="post">
  <!-- Token Input -->
  <label for="token">Enter Token (e.g., abc123):<br />
    <input type="text" id="token" name="token" placeholder="Your custom token here" required />
  </label><br />

  <!-- Invitee Names -->
  <div id="inviteeContainer">
    <div class="invitee-input">
      <input type="text" name="invitees[]" placeholder="Invitee Name" required />
      <button type="button" onclick="removeField(this)">Remove</button>
    </div>
  </div>

  <!-- Add More Button -->
  <button type="button" onclick="addField()">+ Add Another Person</button><br /><br />

  <!-- Submit Button -->
  <button type="submit">Save Invitees</button>
</form>

<!-- Add / Remove JS -->
<script>
function addField() {
  const container = document.getElementById('inviteeContainer');
  const div = document.createElement('div');
  div.className = 'invitee-input';
  div.innerHTML = `
    <input type="text" name="invitees[]" placeholder="Invitee Name" required />
    <button type="button" onclick="removeField(this)">Remove</button>
  `;
  container.appendChild(div);
}

function removeField(button) {
  button.parentNode.remove();
}
</script>

</body>
</html>