<?php
require_once 'includes/config.php';
if (isLoggedIn()) { header('Location: '.SITE_URL.'/dashboard.php'); exit; }

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    require_once 'includes/mailer.php';
    $name     = sanitize($_POST['name'] ?? '');
    $email    = filter_var(trim($_POST['email'] ?? ''), FILTER_SANITIZE_EMAIL);
    $password = $_POST['password'] ?? '';
    $confirm  = $_POST['confirm_password'] ?? '';
    if (!$name || !$email || !$password || !$confirm) jsonResponse(['success'=>false,'message'=>'All fields are required.']);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) jsonResponse(['success'=>false,'message'=>'Please enter a valid email address.']);
    if (strlen($password) < 8) jsonResponse(['success'=>false,'message'=>'Password must be at least 8 characters.']);
    if ($password !== $confirm) jsonResponse(['success'=>false,'message'=>'Passwords do not match.']);
    $stmt = $pdo->prepare("SELECT id FROM users WHERE email=?"); $stmt->execute([$email]);
    if ($stmt->fetch()) jsonResponse(['success'=>false,'message'=>'This email is already registered. Please sign in.']);
    $otp = str_pad(rand(0,999999),6,'0',STR_PAD_LEFT);
    $expires = date('Y-m-d H:i:s', strtotime('+'.OTP_EXPIRY_MINUTES.' minutes'));
    $hash = password_hash($password, PASSWORD_BCRYPT, ['cost'=>12]);
    $stmt = $pdo->prepare("INSERT INTO users (name,email,password,otp_code,otp_expires) VALUES (?,?,?,?,?)");
    $stmt->execute([$name,$email,$hash,$otp,$expires]);
    $userId = $pdo->lastInsertId();
    if (sendOTP($email,$name,$otp)) {
        $_SESSION['pending_verify_id']=$userId; $_SESSION['pending_verify_email']=$email;
        jsonResponse(['success'=>true,'redirect'=>SITE_URL.'/verify-otp.php']);
    } else {
        $pdo->prepare("DELETE FROM users WHERE id=?")->execute([$userId]);
        jsonResponse(['success'=>false,'message'=>'Failed to send OTP email. Please try again.']);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Create Account — <?= SITE_NAME ?></title>
<link rel="icon" type="image/png" href="https://studytrack.edurx.icu/studytrack/images/studytrack.png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Sora:wght@400;600;700;800;900&family=DM+Sans:ital,wght@0,400;0,500;0,600;1,400&display=swap" rel="stylesheet">
<link rel="stylesheet" href="<?= SITE_URL ?>/assets/auth-shared.css">
<style>
/* ── Scroll fix: left fixed, right scrolls ── */
html, body { height: 100%; overflow: hidden; }
body { height: 100vh; overflow: hidden; }
.auth-layout { height: 100vh; overflow: hidden; }
.auth-left {
  position: sticky; top: 0;
  height: 100vh; overflow: hidden;
}
.auth-right {
  height: 100vh;
  overflow-y: auto;
  overflow-x: hidden;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding: 40px 40px;
  scrollbar-width: thin;
  scrollbar-color: rgba(99,102,241,.3) transparent;
}
.auth-right::-webkit-scrollbar { width: 5px; }
.auth-right::-webkit-scrollbar-thumb { background: rgba(99,102,241,.3); border-radius: 99px; }
.auth-form-wrap { width: 100%; max-width: 420px; margin: auto 0; }

/* ── Mobile: allow normal page scroll ── */
@media (max-width: 900px) {
  html, body { height: auto; overflow: auto; }
  body { height: auto; overflow-x: hidden; }
  .auth-layout { height: auto; overflow: visible; display: block; }
  .auth-left { display: none; }
  .auth-right {
    height: auto; min-height: 100vh;
    overflow: visible;
    padding: 32px 20px 40px;
  }
  .auth-form-wrap { margin: 0 auto; }
}

/* ── Toast Notifications ── */
#auth-toast-wrap {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 99999;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  pointer-events: none;
  width: 100%;
  max-width: 460px;
  padding: 0 16px;
}
.auth-toast {
  width: 100%;
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 14px 16px;
  border-radius: 14px;
  font-size: 13px;
  font-weight: 500;
  line-height: 1.5;
  pointer-events: auto;
  box-shadow: 0 8px 32px rgba(0,0,0,.45), 0 2px 8px rgba(0,0,0,.3);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  animation: toastIn .35s cubic-bezier(.34,1.56,.64,1) both;
  cursor: pointer;
  border: 1px solid;
  position: relative;
  overflow: hidden;
}
.auth-toast::before {
  content: '';
  position: absolute;
  top: 0; left: 0; right: 0;
  height: 2px;
  border-radius: 14px 14px 0 0;
}
.auth-toast.hiding { animation: toastOut .3s ease forwards; }
.auth-toast.err {
  background: rgba(15,5,5,.95);
  border-color: rgba(239,68,68,.35);
  color: #fca5a5;
}
.auth-toast.err::before { background: linear-gradient(90deg,#ef4444,#f87171); }
.auth-toast.ok {
  background: rgba(2,12,10,.95);
  border-color: rgba(16,185,129,.35);
  color: #6ee7b7;
}
.auth-toast.ok::before { background: linear-gradient(90deg,#10b981,#34d399); }
.auth-toast-icon { flex-shrink: 0; margin-top: 1px; }
.auth-toast-body { flex: 1; }
.auth-toast-close {
  flex-shrink: 0; opacity: .5; font-size: 13px;
  cursor: pointer; padding: 2px; transition: opacity .15s;
}
.auth-toast-close:hover { opacity: 1; }
.auth-toast-progress {
  position: absolute;
  bottom: 0; left: 0;
  height: 2px;
  border-radius: 0 0 14px 14px;
  animation: toastProgress linear forwards;
}
.auth-toast.err .auth-toast-progress { background: rgba(239,68,68,.5); }
.auth-toast.ok  .auth-toast-progress { background: rgba(16,185,129,.5); }
@keyframes toastIn {
  from { opacity:0; transform:translateY(-16px) scale(.94); }
  to   { opacity:1; transform:translateY(0) scale(1); }
}
@keyframes toastOut {
  from { opacity:1; transform:translateY(0) scale(1); max-height:100px; margin-bottom:0; }
  to   { opacity:0; transform:translateY(-10px) scale(.94); max-height:0; margin-bottom:-10px; }
}
@keyframes toastProgress { from { width:100%; } to { width:0%; } }

/* hide old inline alert box */
.auth-alert { display: none !important; }
</style>
</head>
<body>

<!-- Toast container -->
<div id="auth-toast-wrap"></div>

<div class="auth-layout">

  <!-- ── LEFT PANEL ───────────────────────── -->
  <div class="auth-left">
    <div class="auth-left-grid"></div>
    <div class="auth-left-content">

      <div class="auth-logo">
        <img class="auth-logo-img" src="https://studytrack.edurx.icu/studytrack/images/studytrack.png" alt="StudyTrack">
        <div>
          <div class="auth-logo-name">StudyTrack</div>
          <div class="auth-logo-tag">by EduRX</div>
        </div>
      </div>

      <div class="auth-hero">
        <div class="auth-hero-label">Completely Free</div>
        <h1 class="auth-hero-title">
          Your A/L journey<br>
          <span>starts here.</span>
        </h1>
        <p class="auth-hero-sub">
          Create your free account in seconds and join thousands of Sri Lankan students already tracking their way to success.
        </p>

        <div class="auth-features">
          <div class="auth-feature">
            <div class="auth-feature-icon" style="background:rgba(16,185,129,.14)">✅</div>
            <span>Free forever — no hidden fees</span>
          </div>
          <div class="auth-feature">
            <div class="auth-feature-icon" style="background:rgba(99,102,241,.14)">📈</div>
            <span>Detailed progress analytics</span>
          </div>
          <div class="auth-feature">
            <div class="auth-feature-icon" style="background:rgba(245,158,11,.14)">🎯</div>
            <span>Set goals, track streaks, earn badges</span>
          </div>
          <div class="auth-feature">
            <div class="auth-feature-icon" style="background:rgba(6,182,212,.14)">🤝</div>
            <span>Campus community & leaderboard</span>
          </div>
        </div>
      </div>



    </div>
  </div>

  <!-- ── RIGHT PANEL ──────────────────────── -->
  <div class="auth-right">
    <div class="auth-form-wrap">

      <div class="auth-mobile-logo">
        <img src="https://studytrack.edurx.icu/studytrack/images/studytrack.png" alt="StudyTrack" style="width:34px;height:34px;border-radius:10px">
        <span style="font-family:'Sora',sans-serif;font-size:18px;font-weight:800;background:linear-gradient(135deg,#e0e7ff,#a5b4fc);-webkit-background-clip:text;-webkit-text-fill-color:transparent">StudyTrack</span>
      </div>

      <h2 class="auth-form-title">Create your account 🚀</h2>
      <p class="auth-form-sub">Start tracking your A/L journey today — it's completely free</p>

      <div class="auth-perks">
        <div class="auth-perk">✅ Free forever</div>
        <div class="auth-perk">📊 Live stats</div>
        <div class="auth-perk">🔒 Secure</div>
      </div>

      <div id="msgBox" class="auth-alert" style="display:none"></div>

      <form id="registerForm" novalidate>
        <div class="f-group">
          <label class="f-label">Full Name</label>
          <div class="f-input-wrap">
            <span class="f-icon">👤</span>
            <input type="text" name="name" class="f-input" placeholder="Your full name" required autofocus>
          </div>
        </div>
        <div class="f-group">
          <label class="f-label">Email Address</label>
          <div class="f-input-wrap">
            <span class="f-icon">✉️</span>
            <input type="email" name="email" class="f-input" placeholder="you@email.com" required>
          </div>
        </div>
        <div class="f-group">
          <label class="f-label">Password</label>
          <div class="f-input-wrap">
            <span class="f-icon">🔒</span>
            <input type="password" name="password" id="pwInput" class="f-input" placeholder="Min. 8 characters" required oninput="checkPw(this.value)">
            <button type="button" class="f-eye" onclick="togglePw('pwInput',this)">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
            </button>
          </div>
          <div class="pw-bar-wrap"><div class="pw-bar" id="pwBar"></div></div>
          <div class="pw-hint" id="pwHint"></div>
        </div>
        <div class="f-group">
          <label class="f-label">Confirm Password</label>
          <div class="f-input-wrap">
            <span class="f-icon">🔒</span>
            <input type="password" name="confirm_password" id="pw2Input" class="f-input" placeholder="Repeat password" required>
            <button type="button" class="f-eye" onclick="togglePw('pw2Input',this)">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
            </button>
          </div>
        </div>

        <label class="f-check">
          <input type="checkbox" id="agreeTerms">
          <span>I agree to the <a href="<?= SITE_URL ?>/terms" target="_blank">Terms &amp; Conditions</a> and <a href="<?= SITE_URL ?>/privacy" target="_blank">Privacy Policy</a></span>
        </label>

        <button type="submit" id="regBtn" class="btn-auth">Create Account →</button>
      </form>

      <div class="auth-divider"><span>or sign up with</span></div>
      <div style="display:flex;flex-direction:column;gap:10px">
        <a href="<?= SITE_URL ?>/google-auth.php" class="btn-social google">
          <svg width="17" height="17" viewBox="0 0 48 48"><path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"/><path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"/><path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"/><path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.18 1.48-4.97 2.31-8.16 2.31-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"/></svg>
          Continue with Google
        </a>
        <a href="<?= SITE_URL ?>/fb-auth.php" class="btn-social facebook">
          <svg width="17" height="17" viewBox="0 0 24 24" fill="#1877f2"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>
          Continue with Facebook
        </a>
      </div>

      <div class="auth-foot">Already have an account? <a href="<?= SITE_URL ?>/login">Sign In</a></div>

    </div>
  </div>
</div>

<script src="<?= SITE_URL ?>/assets/js/app.js"></script>
<script>
function togglePw(id, btn) {
  const inp = document.getElementById(id);
  inp.type = inp.type === 'password' ? 'text' : 'password';
  btn.innerHTML = inp.type === 'password'
    ? '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>'
    : '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>';
}
function checkPw(v) {
  const bar = document.getElementById('pwBar');
  const hint = document.getElementById('pwHint');
  let score = 0;
  if (v.length >= 8) score++;
  if (/[A-Z]/.test(v)) score++;
  if (/[0-9]/.test(v)) score++;
  if (/[^A-Za-z0-9]/.test(v)) score++;
  const levels = [
    { w:'0%', bg:'transparent', t:'' },
    { w:'25%', bg:'#ef4444', t:'Weak' },
    { w:'50%', bg:'#f97316', t:'Fair' },
    { w:'75%', bg:'#eab308', t:'Good' },
    { w:'100%', bg:'#10b981', t:'Strong 💪' },
  ];
  const l = levels[score];
  bar.style.width = l.w; bar.style.background = l.bg;
  hint.textContent = l.t; hint.style.color = l.bg;
}
(function(){
  const form = document.getElementById('registerForm');
  const msgBox = document.getElementById('msgBox');
  const btn = document.getElementById('regBtn');
  function showMsg(msg, type) {
    authToast(msg, type === 'error' ? 'err' : 'ok');
  }
  form.addEventListener('submit', async function(e) {
    e.preventDefault();
    if (!document.getElementById('agreeTerms').checked) { showMsg('Please agree to the Terms & Conditions to continue.','error'); return; }
    const pw = document.getElementById('pwInput').value;
    const pw2 = document.getElementById('pw2Input').value;
    if (pw !== pw2) { showMsg('Passwords do not match.','error'); return; }
    if (pw.length < 8) { showMsg('Password must be at least 8 characters.','error'); return; }
    btn.disabled = true; btn.innerHTML = '<span class="spinner"></span> Creating account…';
    msgBox.style.display = 'none';
    try {
      const res = await fetch(location.href, { method:'POST', body:new FormData(form), headers:{'X-Requested-With':'XMLHttpRequest'} });
      const data = await res.json();
      if (data.success) {
        showMsg('Account created! Redirecting to verify your email…','success');
        btn.innerHTML = '✓ Done';
        setTimeout(() => { window.location.href = data.redirect; }, 1000);
      } else {
        showMsg(data.message||'Registration failed. Please try again.','error');
        btn.disabled = false; btn.innerHTML = 'Create Account →';
      }
    } catch(err) {
      showMsg('Connection error. Please check your internet.','error');
      btn.disabled = false; btn.innerHTML = 'Create Account →';
    }
  });
})();
</script>
<script>
/* ── Toast System ─────────────────────────────────────────── */
(function() {
  var wrap = document.getElementById('auth-toast-wrap');
  var DURATION = 4500;

  window.authToast = function(msg, type) {
    type = type || 'err';
    var toast = document.createElement('div');
    toast.className = 'auth-toast ' + type;

    var icon = type === 'ok'
      ? '<svg class="auth-toast-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#34d399" stroke-width="2.5" stroke-linecap="round"><polyline points="20 6 9 17 4 12"/></svg>'
      : '<svg class="auth-toast-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#f87171" stroke-width="2.5" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>';

    toast.innerHTML = icon
      + '<div class="auth-toast-body">' + msg + '</div>'
      + '<div class="auth-toast-close" onclick="this.parentElement._dismiss()">&#10005;</div>'
      + '<div class="auth-toast-progress" style="animation-duration:' + DURATION + 'ms"></div>';

    toast._dismiss = function() {
      if (toast._dismissed) return;
      toast._dismissed = true;
      clearTimeout(toast._timer);
      toast.classList.add('hiding');
      setTimeout(function() { if (toast.parentNode) toast.parentNode.removeChild(toast); }, 320);
    };

    wrap.appendChild(toast);
    toast._timer = setTimeout(function() { toast._dismiss(); }, DURATION);
    toast.addEventListener('click', function(e) {
      if (!e.target.classList.contains('auth-toast-close')) toast._dismiss();
    });
  };
})();
</script>
</body>
</html>