<?php
// register.php
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/config/mail.php';
startSession();

// Already logged in → dashboard
if (isLoggedIn()) { header('Location: dashboard.php'); exit; }

// reCAPTCHA — test keys (localhost pe kaam karte hain)
// Production mein apni real keys daalo
define('RECAPTCHA_SITE_KEY',   '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI');
define('RECAPTCHA_SECRET_KEY', '6LeIxAcTAAAAAGG-vFI1TnRWxMXnb6byBKTKoKz');

$msg = ''; $msgType = ''; $success = false;
$fields = ['title'=>'','first_name'=>'','last_name'=>'','email'=>''];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // ── Honeypot (bots pakdo)
    if (!empty($_POST['website'])) { header('Location: dashboard.php'); exit; }

    // ── Fields collect karo
    $fields = [
        'title'      => trim($_POST['title']      ?? ''),
        'first_name' => trim($_POST['first_name'] ?? ''),
        'last_name'  => trim($_POST['last_name']  ?? ''),
        'email'      => strtolower(trim($_POST['email'] ?? '')),
        'password'   => $_POST['password']  ?? '',
        'password2'  => $_POST['password2'] ?? '',
    ];

    // ── Validate
    $errs = [];
    if (!$fields['first_name'])                          $errs[] = 'First name is required.';
    if (!$fields['last_name'])                           $errs[] = 'Last name is required.';
    if (!filter_var($fields['email'], FILTER_VALIDATE_EMAIL)) $errs[] = 'Enter a valid email address.';
    if (strlen($fields['password']) < 8)                 $errs[] = 'Password must be at least 8 characters.';
    if ($fields['password'] !== $fields['password2'])    $errs[] = 'Passwords do not match.';
    if (!preg_match('/[A-Z]/', $fields['password']))     $errs[] = 'Password needs at least one uppercase letter.';
    if (!preg_match('/[0-9]/', $fields['password']))     $errs[] = 'Password needs at least one number.';

    if ($errs) { $msg = implode('<br>', $errs); $msgType = 'e'; goto render; }

    try {
        // ── Check duplicate email
        $q = db()->prepare("SELECT user_id, is_email_verified FROM users WHERE email=? LIMIT 1");
        $q->execute([$fields['email']]);
        $existing = $q->fetch();

        if ($existing) {
            if (!$existing['is_email_verified']) {
                // Resend verification
                $token = bin2hex(random_bytes(32));
                $exp   = date('Y-m-d H:i:s', strtotime('+24 hours'));
                db()->prepare("UPDATE users SET email_verify_token=?, email_verify_expires=? WHERE user_id=?")
                   ->execute([$token, $exp, $existing['user_id']]);
                sendVerificationMail($fields['email'], $fields['first_name'].' '.$fields['last_name'], $token);
                $msg = 'This email is registered but not verified. We have resent the verification email — check your inbox.';
                $msgType = 'i'; $success = true; goto render;
            }
            $msg = 'This email is already registered. <a href="login.php" style="color:inherit;font-weight:700">Sign in instead →</a>';
            $msgType = 'e'; goto render;
        }

        // ── Create user
        $token    = bin2hex(random_bytes(32));
        $exp      = date('Y-m-d H:i:s', strtotime('+24 hours'));
        $passHash = password_hash($fields['password'], PASSWORD_BCRYPT, ['cost'=>12]);

        // Auto-create columns if missing
        try {
            db()->exec("ALTER TABLE users
                ADD COLUMN IF NOT EXISTS is_email_verified TINYINT(1) NOT NULL DEFAULT 0,
                ADD COLUMN IF NOT EXISTS email_verify_token VARCHAR(100) NULL,
                ADD COLUMN IF NOT EXISTS email_verify_expires DATETIME NULL");
        } catch(PDOException $e){}

        $q = db()->prepare(
            "INSERT INTO users
             (email, password_hash, first_name, last_name, title,
              is_active, is_email_verified, email_verify_token, email_verify_expires,
              created_at, updated_at)
             VALUES (?,?,?,?,?,1,0,?,?,NOW(),NOW())"
        );
        $q->execute([
            $fields['email'], $passHash,
            $fields['first_name'], $fields['last_name'], $fields['title'],
            $token, $exp
        ]);

        $name = trim($fields['first_name'].' '.$fields['last_name']);
        $sent = sendVerificationMail($fields['email'], $name, $token);

        $msg     = $sent
            ? "✅ Account created! Verification email sent to <strong>{$fields['email']}</strong> — please check your inbox."
            : "✅ Account created! <em>Mail send nahi ho saka</em> — <a href='verify_email.php?direct=1&uid=".db()->lastInsertId()."' style='color:inherit;font-weight:700'>Yahan click karo verify karne ke liye</a>.";
        $msgType = 's';
        $success = true;
        $fields  = ['title'=>'','first_name'=>'','last_name'=>'','email'=>''];

    } catch(PDOException $e) {
        $msg = 'Server error: ' . $e->getMessage();
        $msgType = 'e';
    }
}
render:
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Create account — communeglobal</title>
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600;700&display=swap" rel="stylesheet">
<style>
:root{--primary:#E05A2B;--blue:#1B3F6E;--teal:#1A7F8E;--teal-dk:#136070;--text:#222;--muted:#666;--border:#D1D5DB;--bg:#F0F4F8;--white:#fff;--error:#DC2626;--font:'Open Sans',sans-serif;}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
body{font-family:var(--font);background:var(--bg);min-height:100vh;display:flex;flex-direction:column}
a{color:var(--teal);text-decoration:none}
a:hover{text-decoration:underline}

/* Nav */
.nav{background:var(--white);border-bottom:1px solid var(--border);padding:0 32px;height:54px;display:flex;align-items:center;justify-content:space-between;flex-shrink:0;box-shadow:0 1px 4px rgba(0,0,0,.06)}
.logo{font-size:22px;font-weight:700;color:var(--primary);display:flex;align-items:center;gap:8px}

/* Page */
.page{flex:1;display:flex;align-items:flex-start;justify-content:center;padding:32px 16px 48px}
.card{background:var(--white);border-radius:12px;box-shadow:0 4px 32px rgba(0,0,0,.1);width:100%;max-width:500px;overflow:hidden}

/* Card header */
.card-hdr{background:linear-gradient(135deg,var(--blue) 0%,#1A5276 100%);padding:26px 32px}
.card-hdr-title{font-size:22px;font-weight:700;color:#fff;margin-bottom:4px}
.card-hdr-sub{font-size:13.5px;color:rgba(255,255,255,.75)}

/* Card body */
.card-body{padding:28px 32px 36px}
.sec-label{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.6px;color:#9CA3AF;margin-bottom:12px;padding-bottom:6px;border-bottom:1px solid var(--border)}

/* Form elements */
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.fg{margin-bottom:16px}
.fl{display:block;font-size:13px;font-weight:600;color:var(--text);margin-bottom:5px}
.req{color:var(--error)}
.fi{width:100%;padding:10px 14px;border:1.5px solid var(--border);border-radius:6px;font-family:var(--font);font-size:14px;color:var(--text);outline:none;transition:border-color .15s;background:var(--white);-webkit-appearance:none}
.fi:focus{border-color:var(--teal);box-shadow:0 0 0 3px rgba(26,127,142,.12)}
.fi::placeholder{color:#9CA3AF}
select.fi{background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6'%3E%3Cpath fill='%236b7280' d='M5 6L0 0h10z'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 12px center;padding-right:32px;cursor:pointer}

/* Password eye */
.pw-wrap{position:relative}
.pw-wrap .fi{padding-right:44px}
.pw-eye{position:absolute;right:12px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:var(--muted);font-size:16px;padding:4px;line-height:1;display:flex;align-items:center}

/* Password strength bar */
.pw-str{height:3px;background:#E5E7EB;border-radius:2px;margin-top:6px;overflow:hidden}
.pw-str-bar{height:100%;width:0;border-radius:2px;transition:all .3s}
.pw-hint{font-size:11.5px;color:var(--muted);margin-top:4px}

/* Terms */
.terms-row{display:flex;align-items:flex-start;gap:9px;font-size:12.5px;color:var(--muted);margin-bottom:18px;line-height:1.5}
.terms-row input[type=checkbox]{width:15px;height:15px;flex-shrink:0;margin-top:2px;accent-color:var(--teal);cursor:pointer}

/* Button */
.btn{width:100%;padding:13px;background:var(--teal);color:#fff;border:none;border-radius:6px;font-family:var(--font);font-size:15px;font-weight:700;cursor:pointer;transition:background .15s;display:flex;align-items:center;justify-content:center;gap:8px}
.btn:hover{background:var(--teal-dk)}
.btn:disabled{opacity:.5;cursor:not-allowed}

/* Alerts */
.alert{padding:13px 16px;border-radius:7px;font-size:13.5px;line-height:1.6;margin-bottom:20px}
.alert-e{background:#FEF2F2;border:1px solid #FECACA;color:#991B1B}
.alert-s{background:#F0FDF4;border:1px solid #BBF7D0;color:#166534}
.alert-i{background:#EFF6FF;border:1px solid #BFDBFE;color:#1E40AF}
.alert-w{background:#FFFBEB;border:1px solid #FDE68A;color:#92400E}

/* Honeypot */
.hp{position:absolute;left:-9999px;top:-9999px;width:0;height:0;overflow:hidden;opacity:0}

/* Success screen */
.success-box{text-align:center;padding:10px 0 6px}
.success-icon{font-size:56px;margin-bottom:16px;line-height:1}
.success-title{font-size:20px;font-weight:700;color:var(--text);margin-bottom:10px}
.success-desc{font-size:14px;color:var(--muted);line-height:1.7;margin-bottom:24px}

/* Spinner */
.spin{width:16px;height:16px;border:2.5px solid rgba(255,255,255,.35);border-top-color:#fff;border-radius:50%;animation:sp .6s linear infinite;flex-shrink:0}
@keyframes sp{to{transform:rotate(360deg)}}

/* Divider */
.divider{display:flex;align-items:center;gap:10px;margin:22px 0;color:#CBD5E1;font-size:12px}
.divider::before,.divider::after{content:'';flex:1;height:1px;background:var(--border)}

/* Footer */
.footer{text-align:center;padding:14px;font-size:12px;color:var(--muted)}
</style>
</head>
<body>

<?php include __DIR__ . '/../include/header.php'; ?>


<div class="page">
  <div class="card">
    <div class="card-hdr">
      <div class="card-hdr-title">Create your account</div>
      <div class="card-hdr-sub">Join communeglobal to submit and manage your research</div>
    </div>

    <div class="card-body">

      <!-- Alert -->
      <?php if ($msg): ?>
      <div class="alert alert-<?= $msgType ?>"><?= $msg ?></div>
      <?php endif; ?>

      <?php if (!$success): ?>
      <!-- ── REGISTRATION FORM ── -->
      <form method="POST" id="regForm" novalidate>

        <!-- Honeypot -->
        <div class="hp" aria-hidden="true">
          <input type="text" name="website" tabindex="-1" autocomplete="off">
        </div>

        <!-- Personal info -->
        <div class="sec-label">Personal information</div>
        <div class="grid2">
          <div class="fg">
            <label class="fl" for="title">Title</label>
            <select class="fi" id="title" name="title">
              <option value="">— Select —</option>
              <?php foreach(['Mr','Mrs','Ms','Dr','Prof','Prof Dr'] as $t): ?>
              <option value="<?= $t ?>" <?= ($fields['title']===$t)?'selected':'' ?>><?= $t ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div></div><!-- spacer -->

          <div class="fg">
            <label class="fl" for="first_name">First name <span class="req">*</span></label>
            <input class="fi" type="text" id="first_name" name="first_name"
                   value="<?= htmlspecialchars($fields['first_name']) ?>"
                   placeholder="Jane" autocomplete="given-name" required>
          </div>
          <div class="fg">
            <label class="fl" for="last_name">Last name <span class="req">*</span></label>
            <input class="fi" type="text" id="last_name" name="last_name"
                   value="<?= htmlspecialchars($fields['last_name']) ?>"
                   placeholder="Smith" autocomplete="family-name" required>
          </div>
        </div>

        <!-- Account info -->
        <div class="sec-label" style="margin-top:4px">Account</div>
        <div class="fg">
          <label class="fl" for="email">Email address <span class="req">*</span></label>
          <input class="fi" type="email" id="email" name="email"
                 value="<?= htmlspecialchars($fields['email']) ?>"
                 placeholder="you@university.edu" autocomplete="email" required>
        </div>

        <div class="fg">
          <label class="fl" for="password">Password <span class="req">*</span></label>
          <div class="pw-wrap">
            <input class="fi" type="password" id="password" name="password"
                   placeholder="Min 8 characters" autocomplete="new-password"
                   oninput="checkStr(this.value)" required>
            <button type="button" class="pw-eye" onclick="togglePw('password',this)" title="Show/hide">👁️</button>
          </div>
          <div class="pw-str"><div class="pw-str-bar" id="strBar"></div></div>
          <div class="pw-hint" id="strHint">Min 8 chars · 1 uppercase · 1 number</div>
        </div>

        <div class="fg">
          <label class="fl" for="password2">Confirm password <span class="req">*</span></label>
          <div class="pw-wrap">
            <input class="fi" type="password" id="password2" name="password2"
                   placeholder="Repeat password" autocomplete="new-password" required>
            <button type="button" class="pw-eye" onclick="togglePw('password2',this)" title="Show/hide">👁️</button>
          </div>
          <div id="matchHint" style="font-size:11.5px;margin-top:4px"></div>
        </div>

        <!-- Terms -->
        <div class="terms-row">
          <input type="checkbox" id="terms" name="terms" required>
          <label for="terms">
            I agree to the <a href="#">Terms of Service</a> and <a href="#">Privacy Policy</a>.
            I consent to receiving emails from communeglobal.
          </label>
        </div>

        <!-- Submit -->
        <button type="submit" class="btn" id="regBtn">Create account</button>

      </form>

      <div class="divider">already have an account?</div>
      <div style="text-align:center">
        <a href="login.php" style="font-size:14px;font-weight:700;color:var(--teal)">Sign in →</a>
      </div>

      <?php else: ?>
      <!-- ── SUCCESS SCREEN ── -->
      <div class="success-box">
        <div class="success-icon">📧</div>
        <div class="success-title">Check your inbox!</div>
        <div class="success-desc">
          We've sent a verification link to<br>
          <strong style="color:var(--text)"><?= htmlspecialchars($_POST['email'] ?? '') ?></strong><br><br>
          Click the link in the email to activate your account.<br>
          <span style="font-size:12.5px">(Spam folder bhi check karo)</span>
        </div>
        <a href="login.php" class="btn" style="display:inline-flex;width:auto;padding:11px 32px;text-decoration:none">
          Go to Sign in →
        </a>
        <div style="margin-top:16px;font-size:12.5px;color:var(--muted)">
          Email nahi mili? <a href="resend_verify.php">Resend karo</a>
        </div>
      </div>
      <?php endif; ?>

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



<script>
function togglePw(id, btn) {
  const f = document.getElementById(id);
  f.type = (f.type === 'password') ? 'text' : 'password';
  btn.textContent = (f.type === 'password') ? '👁️' : '🙈';
}

const strColors = ['','#EF4444','#F97316','#EAB308','#22C55E','#16A34A'];
const strLabels = ['','Weak','Fair','Good','Strong','Very strong'];

function checkStr(v) {
  let s = 0;
  if (v.length >= 8)           s++;
  if (/[A-Z]/.test(v))         s++;
  if (/[0-9]/.test(v))         s++;
  if (/[^A-Za-z0-9]/.test(v)) s++;
  if (v.length >= 12)          s++;
  document.getElementById('strBar').style.cssText = `width:${s*20}%;background:${strColors[s]||'#E5E7EB'}`;
  const h = document.getElementById('strHint');
  h.textContent = strLabels[s] || 'Min 8 chars · 1 uppercase · 1 number';
  h.style.color = strColors[s] || 'var(--muted)';
}

document.getElementById('password2')?.addEventListener('input', function() {
  const p1 = document.getElementById('password').value;
  const h  = document.getElementById('matchHint');
  if (!this.value) { h.textContent = ''; return; }
  if (p1 === this.value) { h.textContent = '✅ Passwords match'; h.style.color = '#22C55E'; }
  else                   { h.textContent = '❌ Passwords do not match'; h.style.color = '#EF4444'; }
});

document.getElementById('regForm')?.addEventListener('submit', function(e) {
  const terms = document.getElementById('terms');
  if (!terms.checked) { e.preventDefault(); alert('Please accept the Terms of Service to continue.'); return; }
  const p1 = document.getElementById('password').value;
  const p2 = document.getElementById('password2').value;
  if (p1 !== p2) { e.preventDefault(); alert('Passwords do not match.'); return; }
  const btn = document.getElementById('regBtn');
  btn.disabled = true;
  btn.innerHTML = '<span class="spin"></span> Creating account...';
});
</script>
</body>
</html>


<?php include __DIR__ . '/../include/footer.php'; ?>
