<?php
// Sign-up — creates Firebase user + encrypted customer record (mirrors React app).
declare(strict_types=1);
require __DIR__ . '/inc/config.php';
require __DIR__ . '/inc/crypto.php';
require __DIR__ . '/inc/firebase.php';
require __DIR__ . '/inc/auth.php';
require __DIR__ . '/inc/layout.php';
require __DIR__ . '/inc/marketing.php';
cxa_boot();

if (cxa_user()) { header('Location: /dashboard'); exit; }

$error = null;
$discord = isset($_GET['discord']) ? trim((string)$_GET['discord']) : '';
$agree = isset($_POST['agree']);

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $email = trim((string)($_POST['email'] ?? ''));
    $password = (string)($_POST['password'] ?? '');
    $confirm = (string)($_POST['confirm'] ?? '');
    $token = (string)($_POST['cf-turnstile-response'] ?? '');
    if ($password !== $confirm) $error = 'Passwords do not match.';
    elseif (!$agree) $error = 'You must agree to the Terms of Service.';
    elseif (!fb_turnstile_ok($token)) $error = 'Please complete the security check.';
    else {
        $r = fb_signup($email, $password);
        if (isset($r['error'])) {
            $error = $r['error'];
        } else {
            cxa_login($r, $email);
            $u = cxa_user();
            fb_customer_write($email, [
                'email' => $email,
                'secret' => cxa_random_secret(),
                'plan' => 'Free Plan',
                'credits' => 0,
                'discordId' => $discord,
                'createdAt' => gmdate('Y-m-d\TH:i:s') . '.000Z',
            ], $u['idToken']);
            header('Location: /dashboard');
            exit;
        }
    }
}

cxa_m_head('Create account', 'Create a CXA account to issue licences, bind devices to hardware and revoke access from one encrypted console.', ['turnstile' => true]);
?>
<header class="auth-nav">
  <div class="container auth-nav__inner">
    <a href="/" class="brand"><?php echo cxa_m_mark(32); ?><span class="brand__type"><span class="brand__name">CXA</span><span class="brand__sub">CodeX Authentication</span></span></a>
    <div class="auth-nav__right">
      <span class="auth-nav__note">Already have an account?</span>
      <a href="/login.php" class="btn btn--ghost btn--sm" data-magnetic>Sign in<span class="btn__arrow"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 12h14M13 6l6 6-6 6"/></svg></span></a>
    </div>
  </div>
</header>

<main id="main" class="auth">
  <div class="auth__spot" aria-hidden="true"></div>
  <div class="container auth__grid">
    <section class="auth__aside">
      <span class="eyebrow">Console access</span>
      <h1 class="auth__title">Ship under <em>your keys.</em></h1>
      <p class="auth__lede">One account for every application, device and expiry you ship. Create it free, then mint licences, wire the SDK and watch sessions land in the console.</p>
      <ul class="auth__proof">
        <li><span class="auth__proof-n">01</span><div><b>A free plan on arrival</b><span>Sign up and land in the console with a Free Plan attached.</span></div></li>
        <li><span class="auth__proof-n">02</span><div><b>One secret per application</b><span>Every app gets its own master key and scoped endpoints.</span></div></li>
        <li><span class="auth__proof-n">03</span><div><b>Revocation that travels</b><span>Bans, pauses and expiries apply on the client's next call.</span></div></li>
      </ul>
      <div class="auth__status">
        <span><i></i>API v2 online</span>
        <span>30 routes</span>
        <span>AES-256 at rest</span>
      </div>
    </section>

    <section class="auth__panel" aria-labelledby="auth-heading">
      <div class="auth-card">
        <div class="auth-card__head">
          <span class="auth-card__tag">Account / Create</span>
          <span class="auth-card__status"><i></i>Free plan</span>
        </div>
        <h2 id="auth-heading">Create your account.</h2>
        <p class="auth-card__sub">Start free. Your first application takes about a minute.</p>

        <?php if ($error !== null): ?>
          <div class="auth-alert" role="alert">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>
            <span><?php echo cxa_e($error); ?></span>
          </div>
        <?php endif; ?>

        <form class="auth-form" method="post">
          <div class="auth-field">
            <label class="auth-field__label" for="auth-email">Email</label>
            <input id="auth-email" name="email" type="email" autocomplete="email" placeholder="you@studio.com" required value="<?php echo cxa_e((string)($_POST['email'] ?? '')); ?>" />
          </div>

          <div class="auth-form__row">
            <div class="auth-field">
              <label class="auth-field__label" for="auth-password">Password</label>
              <span class="auth-field__control">
                <input id="auth-password" name="password" type="password" autocomplete="new-password" placeholder="Password" required />
                <button type="button" class="auth-field__toggle" aria-label="Show password" aria-pressed="false" aria-controls="auth-password">Show</button>
              </span>
            </div>
            <div class="auth-field">
              <label class="auth-field__label" for="auth-confirm">Confirm</label>
              <span class="auth-field__control">
                <input id="auth-confirm" name="confirm" type="password" autocomplete="new-password" placeholder="Repeat" required aria-describedby="auth-match" />
                <button type="button" class="auth-field__toggle" aria-label="Show confirm password" aria-pressed="false" aria-controls="auth-confirm">Show</button>
              </span>
              <span class="auth-match" id="auth-match" aria-live="polite"></span>
            </div>
          </div>

          <label class="auth-check">
            <input type="checkbox" name="agree" value="1" required<?php echo $agree ? ' checked' : ''; ?> />
            <span>I agree to the <a href="/tos">Terms of Service</a> and understand my account is created under the Free Plan.</span>
          </label>

          <div class="auth-turnstile">
            <div class="cf-turnstile" data-sitekey="<?php echo cxa_e(CXA_TURNSTILE_SITE_KEY); ?>" data-theme="dark" data-appearance="always" data-error-callback="cxaTurnstileError" data-callback="cxaTurnstileOk"></div>
            <p class="auth-turnstile__fallback" id="turnstile-fallback" hidden>Security check unavailable. <a href="/signup.php">Reload the page</a> or disable your blocker.</p>
          </div>

          <button type="submit" class="btn btn--red auth-submit" data-loading-label="Creating account">
            <span class="auth-submit__label">Create account</span>
            <span class="auth-submit__spinner" aria-hidden="true"></span>
            <span class="btn__arrow"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 17 17 7M9 7h8v8"/></svg></span>
          </button>
        </form>

        <div class="auth-divider">Or sign up with</div>
        <div class="auth-socials">
          <button type="button" id="btn-google" class="auth-social">
            <svg viewBox="0 0 24 24" aria-hidden="true"><path fill="#4285F4" d="M23.49 12.27c0-.79-.07-1.54-.19-2.27H12v4.51h6.47a5.57 5.57 0 0 1-2.4 3.58v3h3.86c2.26-2.09 3.56-5.17 3.56-8.82Z"/><path fill="#34A853" d="M12 24c3.24 0 5.95-1.08 7.93-2.91l-3.86-3c-1.08.72-2.45 1.16-4.07 1.16-3.13 0-5.78-2.11-6.73-4.96H1.29v3.09A11.99 11.99 0 0 0 12 24Z"/><path fill="#FBBC05" d="M5.27 14.29A7.2 7.2 0 0 1 4.89 12c0-.8.14-1.57.38-2.29V6.62H1.29A11.99 11.99 0 0 0 0 12c0 1.94.46 3.77 1.29 5.38l3.98-3.09Z"/><path fill="#EA4335" d="M12 4.75c1.77 0 3.35.61 4.6 1.8l3.42-3.42C17.95 1.19 15.24 0 12 0 7.31 0 3.26 2.69 1.29 6.62l3.98 3.09C6.22 6.86 8.87 4.75 12 4.75Z"/></svg>
            Google
          </button>
          <button type="button" id="btn-github" class="auth-social">
            <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 .5C5.37.5 0 5.87 0 12.5c0 5.3 3.44 9.8 8.21 11.39.6.11.82-.26.82-.58v-2.02c-3.34.73-4.04-1.61-4.04-1.61-.55-1.39-1.34-1.76-1.34-1.76-1.09-.75.08-.73.08-.73 1.2.08 1.84 1.24 1.84 1.24 1.07 1.84 2.81 1.31 3.5 1 .11-.78.42-1.31.76-1.61-2.66-.3-5.47-1.33-5.47-5.92 0-1.31.47-2.38 1.24-3.22-.12-.3-.54-1.52.12-3.17 0 0 1.01-.32 3.3 1.23a11.5 11.5 0 0 1 6.01 0c2.29-1.55 3.3-1.23 3.3-1.23.66 1.65.24 2.87.12 3.17.77.84 1.24 1.91 1.24 3.22 0 4.6-2.81 5.61-5.48 5.91.43.37.81 1.1.81 2.22v3.29c0 .32.22.7.83.58A12 12 0 0 0 24 12.5C24 5.87 18.63.5 12 .5Z"/></svg>
            GitHub
          </button>
        </div>
        <p class="auth-social__note" id="social-error" role="alert" hidden></p>

        <p class="auth-card__foot">Already have an account? <a href="/login.php">Sign in</a></p>
      </div>
      <p class="auth-terms">Protected by Cloudflare Turnstile · <a href="/tos">Terms of service</a></p>
    </section>
  </div>
</main>

<footer class="auth-foot">
  <div class="container">
    <div class="auth-credit">
      <span>Designed &amp; engineered by</span>
      <b><a href="/developer">Aashiq <i>&amp;</i> Vishakh</a></b>
    </div>
    <div class="auth-foot__inner">
      <span class="auth-foot__live"><i></i>All systems nominal</span>
      <div class="auth-foot__links">
        <a href="/docs">Docs</a>
        <a href="/security">Security</a>
        <a href="/tos">Terms</a>
        <a href="https://discord.gg/gnbp3b7e4T" target="_blank" rel="noopener">Discord</a>
      </div>
      <span>© 2026 CXA · CodeX Authentication</span>
    </div>
  </div>
</footer>

<script>
window.cxaTurnstileError = function () {
  var wrap = document.querySelector('.auth-turnstile');
  var fb = document.getElementById('turnstile-fallback');
  if (wrap) wrap.classList.add('is-unavailable');
  if (fb) fb.hidden = false;
};
window.cxaTurnstileOk = function () {
  var wrap = document.querySelector('.auth-turnstile');
  var fb = document.getElementById('turnstile-fallback');
  if (wrap) wrap.classList.remove('is-unavailable');
  if (fb) fb.hidden = true;
};
</script>
<script type="module">
import { initializeApp } from 'https://www.gstatic.com/firebasejs/10.12.0/firebase-app.js';
import { getAuth, signInWithPopup, GoogleAuthProvider, GithubAuthProvider } from 'https://www.gstatic.com/firebasejs/10.12.0/firebase-auth.js';
const app = initializeApp({
  apiKey: <?php echo json_encode(CXA_FIREBASE_API_KEY); ?>,
  authDomain: <?php echo json_encode(CXA_FIREBASE_AUTH_DOMAIN); ?>,
  databaseURL: <?php echo json_encode(CXA_FIREBASE_DB_URL); ?>,
});
const auth = getAuth(app);
function socialError(msg) {
  const el = document.getElementById('social-error');
  if (!el) { alert(msg); return; }
  el.textContent = msg;
  el.hidden = false;
}
async function social(provider) {
  try {
    const cred = await signInWithPopup(auth, provider);
    const idToken = await cred.user.getIdToken();
    const refreshToken = cred.user.refreshToken || '';
    const res = await fetch('token.php', { method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ idToken, refreshToken, discord: <?php echo json_encode($discord); ?> }) });
    const data = await res.json();
    if (data.ok) window.location.href = '/dashboard';
    else socialError(data.error || 'Social sign-in failed. Try email and password.');
  } catch (e) { socialError('Social sign-in failed. Try email and password.'); }
}
document.getElementById('btn-google').onclick = () => social(new GoogleAuthProvider());
document.getElementById('btn-github').onclick = () => social(new GithubAuthProvider());
</script>
<?php cxa_m_foot(); ?>
