<?php
require_once __DIR__ . '/server/db.php';

$code = strtoupper(trim($_GET['code'] ?? ''));
if ($code === '' || !preg_match('/^[A-Z0-9]{6,32}$/', $code)) {
  http_response_code(404);
  echo "Invalid share code.";
  exit;
}

$stmt = $conn->prepare("SELECT id, name, share_code FROM organizations WHERE share_code = ? LIMIT 1");
$stmt->bind_param("s", $code);
$stmt->execute();
$org = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$org) {
  http_response_code(404);
  echo "Organization not found.";
  exit;
}
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>Subscribe — <?= h($org['name']) ?> | Event Notis</title>
    <link rel="manifest" href="/main/manifest.webmanifest">
  <meta name="theme-color" content="#0b1020" />
  <link rel="stylesheet" href="<?= APP_BASE ?>assets/css/base.css" />
  <link rel="stylesheet" href="<?= APP_BASE ?>assets/css/subscribe.css" />
  <script>
    window.APP_BASE = <?= json_encode(APP_BASE) ?>;
    window.ORG = <?= json_encode($org) ?>;
    window.VAPID_PUBLIC_KEY = <?= json_encode(VAPID_PUBLIC_KEY) ?>;
  </script>
</head>
<body>
  <div class="wrap narrow">
    <div class="card">
      <h1>Enable notifications</h1>
      <p class="muted">
        You’re subscribing to: <b><?= h($org['name']) ?></b>
      </p>

      <div id="iosHelp" class="notice" hidden>
        <b>iPhone users:</b> Add this site to your Home Screen first (Share → “Add to Home Screen”),
        then open it from the Home Screen and come back to enable notifications.
      </div>

      <div class="actions">
        <button class="btn primary" id="enableBtn" type="button">Enable notifications</button>
      </div>

      <div class="muted tiny" id="status">Not subscribed yet.</div>
    </div>
  </div>

  <script src="<?= APP_BASE ?>assets/js/subscribe.js" defer></script>
</body>
</html>
