<?php
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/channel.php';
chat247_start_session();

// Dual-payment-channel detection. Resolves referrer + URL params + existing
// cookie into a channel tag, (re)writes the 30-day cb_channel cookie, and
// returns the value we POST as the hidden `channel` field. Must run BEFORE any
// output so the Set-Cookie header isn't dropped.
$signupChannel = chat247_resolve_channel();

// Affiliate referral override: if the visitor arrived via 247ch.at/?ref=<code>
// (tcms_ref cookie set by chat247_capture_referral_cookie in auth.php) AND no
// stronger ClickBank channel is in play, tag the signup as aff_<refcode> so
// the Node relay credits our own affiliate. CB channels still win — CB pays
// its own affiliate, our ledger no-ops on cb_*. Only direct gets upgraded.
if ($signupChannel === 'direct' && !empty($_COOKIE['tcms_ref'])) {
    $tcmsRef = strtolower(preg_replace('/[^a-f0-9]/', '', (string)$_COOKIE['tcms_ref']) ?? '');
    $tcmsRef = substr($tcmsRef, 0, 8);
    if ($tcmsRef !== '') $signupChannel = 'aff_' . $tcmsRef;
}

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

// Plan picker: pre-select from ?plan=, fall back to monthly. Validated server-side.
$ALLOWED_PLANS = ['free' => 1, 'monthly' => 1, 'annual' => 1];
$plan = $_POST['plan'] ?? $_GET['plan'] ?? 'monthly';
if (!isset($ALLOWED_PLANS[$plan])) { $plan = 'monthly'; }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm = $_POST['confirm'] ?? '';
    $terms = !empty($_POST['terms']);
    if (!$terms) {
        $err = 'You must accept the terms.';
    } elseif ($password !== $confirm) {
        $err = 'Passwords do not match.';
    } elseif (strlen($password) < 8) {
        $err = 'Password must be at least 8 characters.';
    } else {
        $relay = chat247_relay_url();
        $ch = curl_init("$relay/api/signup");
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_POSTFIELDS => json_encode(['email'=>$email,'password'=>$password,'channel'=>($_POST['channel'] ?? $signupChannel)]),
            CURLOPT_TIMEOUT => 10,
        ]);
        $resp = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        $data = $resp ? json_decode($resp, true) : null;
        if ($code === 200) {
            // Free plan -> usual "verify your email" path. Paid plans send the
            // user straight to dashboard.php with ?subscribe=<plan>&autostart=1
            // so the dashboard JS auto-fires the Stripe Checkout POST.
            if ($plan === 'free') {
                $msg = 'Check your email to verify your account.';
            } else {
                // Account was created via /api/signup but is unverified. We still
                // want them to land on dashboard.php for the checkout autostart;
                // they'll be prompted to verify after they finish billing.
                header('Location: /dashboard.php?subscribe=' . urlencode($plan) . '&autostart=1');
                exit;
            }
        } else {
            $err = $data['error'] ?? 'Signup failed';
        }
    }
}
?><!doctype html>
<html lang="en"><head>
<base href="https://<?= htmlspecialchars($_SERVER['HTTP_HOST'] ?? '', ENT_QUOTES) ?>/"><meta charset="utf-8"><title>Create account — 247ch.at</title>
<link rel="icon" href="/favicon.ico?v=<?= @filemtime(__DIR__ . '/favicon.ico') ?: time() ?>">
<style>
 body { font-family:-apple-system,sans-serif; background:#0b0f1a; color:#f3f4f6; display:flex; flex-direction:column; align-items:center; justify-content:flex-start; min-height:100vh; margin:0; padding:48px 16px; }
 h1.title { margin:0 0 8px; font-size:28px; text-align:center; }
 p.sub { margin:0 0 28px; color:#9ca3af; font-size:15px; text-align:center; max-width:640px; }
 .plans { display:grid; grid-template-columns:repeat(3, 1fr); gap:16px; width:100%; max-width:920px; margin-bottom:32px; }
 @media (max-width:760px) { .plans { grid-template-columns:1fr; } }
 .plan { background:#111827; border:1px solid #1f2937; border-radius:12px; padding:20px; cursor:pointer; transition:border-color 0.15s, transform 0.15s; position:relative; display:flex; flex-direction:column; }
 .plan:hover { border-color:#3b82f6; }
 .plan.selected { border-color:#3b82f6; box-shadow:0 0 0 1px #3b82f6; }
 .plan.popular { border-color:#3b82f6; }
 .plan .badge { position:absolute; top:-12px; left:50%; transform:translateX(-50%); background:#3b82f6; color:#fff; font-size:11px; padding:3px 10px; border-radius:999px; font-weight:600; letter-spacing:0.4px; }
 .plan h3 { margin:0 0 4px; font-size:18px; }
 .plan .tag { color:#9ca3af; font-size:13px; margin:0 0 14px; }
 .plan .price { font-size:28px; font-weight:700; margin:0 0 2px; }
 .plan .price small { font-size:13px; color:#9ca3af; font-weight:400; }
 .plan .recurring { color:#9ca3af; font-size:12px; margin:0 0 12px; font-style:italic; }
 .plan ul { list-style:none; padding:0; margin:0 0 16px; flex:1; }
 .plan li { padding:4px 0; font-size:13px; color:#d1d5db; }
 .plan li::before { content:"\2713 "; color:#34d399; }
 .plan .pick-btn { display:block; padding:10px; text-align:center; border-radius:6px; background:#1f2937; color:#fff; font-weight:600; font-size:14px; border:1px solid #2a3142; }
 .plan.selected .pick-btn { background:#3b82f6; border-color:#3b82f6; }
 .card { background:#111827; padding:28px; border-radius:12px; width:100%; max-width:380px; }
 .card h2 { margin:0 0 18px; font-size:18px; text-align:center; }
 .google { display:block; width:100%; padding:11px; background:#fff; color:#111; border:none; border-radius:8px; font-weight:600; text-align:center; text-decoration:none; }
 .or { text-align:center; color:#9ca3af; margin:14px 0; font-size:13px; }
 label { display:block; font-size:13px; color:#9ca3af; margin-top:12px; }
 input[type=email],input[type=password] { width:100%; padding:10px; background:#0b0f1a; border:1px solid #2a3142; color:#f3f4f6; border-radius:6px; }
 .terms { font-size:13px; color:#9ca3af; margin-top:12px; }
 button.submit { width:100%; margin-top:14px; padding:12px; background:#3b82f6; color:#fff; border:none; border-radius:8px; font-weight:600; cursor:pointer; }
 .err { color:#f87171; font-size:13px; margin-top:12px; text-align:center; }
 .ok  { color:#34d399; font-size:13px; margin-top:12px; text-align:center; }
 .links { text-align:center; margin-top:14px; font-size:13px; }
 .links a { color:#9ca3af; text-decoration:none; }
 .legal-mini { margin-top:20px; font-size:12px; color:#6b7280; text-align:center; }
 .legal-mini a { color:#6b7280; text-decoration:none; margin:0 6px; }
 .summary-pill { text-align:center; color:#9ca3af; font-size:13px; margin-bottom:14px; }
 .summary-pill strong { color:#f3f4f6; }
</style></head><body>
<h1 class="title">Create your 247ch.at account</h1>
<p class="sub">Pick a plan, then set up your login. You can change plans anytime from your dashboard.</p>

<form method="post" id="signupForm" style="width:100%; display:flex; flex-direction:column; align-items:center;">
  <input type="hidden" name="plan" id="planField" value="<?= htmlspecialchars($plan) ?>">
  <input type="hidden" name="channel" id="channelField" value="<?= htmlspecialchars($signupChannel) ?>">

  <div class="plans" id="plans">
    <div class="plan" data-plan="free">
      <h3>Free</h3>
      <p class="tag">Try it out</p>
      <div class="price">$0<small> / forever</small></div>
      <p class="recurring">No card. No subscription.</p>
      <ul>
        <li>1 site</li>
        <li>Manual operator replies</li>
        <li>"Powered by 247ch.at" badge</li>
      </ul>
      <div class="pick-btn">Pick Free</div>
    </div>

    <div class="plan popular" data-plan="monthly">
      <div class="badge">MOST POPULAR</div>
      <h3>Pro Monthly</h3>
      <p class="tag">Always-on AI coverage</p>
      <div class="price">$19<small> / month</small></div>
      <p class="recurring">Auto-renews monthly &middot; cancel anytime</p>
      <ul>
        <li>Unlimited sites</li>
        <li>2,500 AI replies / month</li>
        <li>Offline email pings</li>
        <li>No "Powered by" badge</li>
      </ul>
      <div class="pick-btn">Pick Pro Monthly</div>
    </div>

    <div class="plan" data-plan="annual">
      <h3>Pro Annual</h3>
      <p class="tag">Save $29 vs monthly</p>
      <div class="price">$199<small> / year</small></div>
      <p class="recurring">Auto-renews yearly &middot; cancel anytime</p>
      <ul>
        <li>Everything in Pro Monthly</li>
        <li>2,500 AI replies / month</li>
        <li>Save $29 ($228 -&gt; $199)</li>
      </ul>
      <div class="pick-btn">Pick Pro Annual</div>
    </div>
  </div>

  <div class="summary-pill" id="planSummary"></div>

  <div class="card">
    <h2>Your login</h2>
    <a class="google" href="/oauth/google" id="googleLink">Sign up with Google</a>
    <div class="or">or</div>
    <label>Email</label>
    <input type="email" name="email" required value="<?= htmlspecialchars($_POST['email'] ?? '') ?>">
    <label>Password (8+ chars)</label>
    <input type="password" name="password" required>
    <label>Confirm password</label>
    <input type="password" name="confirm" required>
    <div class="terms"><label><input type="checkbox" name="terms"> I accept the terms of service.</label></div>
    <button type="submit" class="submit" id="submitBtn">Create account</button>
    <?php if ($err): ?><div class="err"><?=htmlspecialchars($err)?></div><?php endif; ?>
    <?php if ($msg): ?><div class="ok"><?=htmlspecialchars($msg)?></div><?php endif; ?>
    <div class="links"><a href="/login">Already have an account? Sign in</a></div>
  </div>
</form>

<div class="legal-mini">
  By creating an account you agree to our
  <a href="/terms">Terms</a> and <a href="/privacy">Privacy Policy</a>.
  &middot; <a href="/pricing">Pricing</a>
  <br>
  Paid plans are <strong>recurring subscriptions</strong>. Cancel anytime from your dashboard.
</div>

<script>
(function() {
  const PLAN_COPY = {
    free:    { label: 'Free',        line: '$0 forever &mdash; no card, no subscription.' },
    monthly: { label: 'Pro Monthly', line: '<strong>$19/month</strong>, auto-renews monthly &middot; cancel anytime.' },
    annual:  { label: 'Pro Annual',  line: '<strong>$199/year</strong>, auto-renews yearly &middot; save $29 vs monthly.' },
  };
  const plans = document.querySelectorAll('.plan');
  const field = document.getElementById('planField');
  const summary = document.getElementById('planSummary');
  const submitBtn = document.getElementById('submitBtn');
  const googleLink = document.getElementById('googleLink');

  function syncSelection() {
    const cur = field.value;
    plans.forEach(p => p.classList.toggle('selected', p.dataset.plan === cur));
    const copy = PLAN_COPY[cur] || PLAN_COPY.monthly;
    summary.innerHTML = 'Selected: <strong>' + copy.label + '</strong> &mdash; ' + copy.line;
    submitBtn.textContent = cur === 'free' ? 'Create free account' : 'Create account &amp; continue to checkout';
    // Pass plan through Google OAuth too so the callback redirect can autostart.
    googleLink.href = '/oauth/google.php?plan=' + encodeURIComponent(cur);
  }
  plans.forEach(p => p.addEventListener('click', () => {
    field.value = p.dataset.plan;
    syncSelection();
  }));
  syncSelection();
})();
</script>
</body></html>
