<?php
// admin/activate.php — new admin sets their password via emailed token
require_once __DIR__ . '/../config.php';
startSecureSession();

// Already logged in → go to dashboard
if (!empty($_SESSION['admin_id'])) {
    header('Location: ' . BASE_URL . '/admin/dashboard.php');
    exit;
}

$token = trim($_GET['token'] ?? '');
$error = '';
$done  = false;

if (!$token) {
    $error = 'Invalid or missing activation link.';
} else {
    $db   = db();
    $stmt = $db->prepare(
        'SELECT id, name, email, status, activation_token FROM admins
         WHERE activation_token = ? AND role = \'admin\' AND status = \'pending\'
         LIMIT 1'
    );
    $stmt->execute([$token]);
    $admin = $stmt->fetch();

    if (!$admin) {
        $error = 'This activation link is invalid or has already been used.';
    } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $pass1 = $_POST['password'] ?? '';
        $pass2 = $_POST['password_confirm'] ?? '';

        if (!csrfValid()) {
            $error = 'Security token expired. Please try again.';
        } elseif (strlen($pass1) < 6) {
            $error = 'Password must be at least 6 characters.';
        } elseif ($pass1 !== $pass2) {
            $error = 'Passwords do not match.';
        } else {
            $hash = password_hash($pass1, PASSWORD_BCRYPT);
            $db->prepare(
                'UPDATE admins SET password=?, status=\'active\', activation_token=NULL WHERE id=?'
            )->execute([$hash, $admin['id']]);

            // Auto log in
            session_regenerate_id(true);
            $_SESSION['admin_id']   = $admin['id'];
            $_SESSION['admin_name'] = $admin['name'];
            $_SESSION['admin_role'] = 'admin';
            $done = true;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Activate Account — RSVP System</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" media="print" onload="this.media='all'" href="https://fonts.googleapis.com/css2?family=Syne:wght@400;600;700;800&family=DM+Sans:wght@300;400;500&display=swap">
<link rel="stylesheet" href="<?= BASE_URL ?>/assets/css/main.css">
</head>
<body>
<div class="login-wrap">
  <div class="login-card">
    <div class="login-logo">
      <div class="name">RSVP</div>
      <div class="sub">Account Activation</div>
    </div>

    <?php if ($done): ?>

      <div class="alert alert-success">
        Your account is now active. Welcome, <?= htmlspecialchars($admin['name']) ?>!
      </div>
      <a href="<?= BASE_URL ?>/admin/dashboard.php" class="btn btn-gold w-100 mt-3">
        Go to Dashboard
      </a>

    <?php elseif ($error && !isset($admin)): ?>

      <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
      <p class="text-muted text-sm" style="text-align:center;margin-top:16px">
        Contact your super admin for a new activation link.
      </p>

    <?php else: ?>

      <p style="color:var(--muted);font-size:.9rem;margin-bottom:24px;text-align:center">
        Hi <strong style="color:var(--white)"><?= htmlspecialchars($admin['name']) ?></strong>,
        create a password to activate your account.
      </p>

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

      <form method="POST">
        <?= csrfField() ?>
        <div class="form-group">
          <label class="form-label">New Password</label>
          <input class="form-control" type="password" name="password"
                 autocomplete="new-password" placeholder="Min 6 characters" required>
        </div>
        <div class="form-group">
          <label class="form-label">Confirm Password</label>
          <input class="form-control" type="password" name="password_confirm"
                 autocomplete="new-password" placeholder="Repeat password" required>
        </div>
        <button class="btn btn-gold w-100 mt-3" type="submit">Activate Account</button>
      </form>

    <?php endif; ?>
  </div>
</div>
</body>
</html>
