<?php
// resend_verify.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
if (isLoggedIn()) { header('Location: dashboard.php'); exit; }

$msg     = '';
$msgType = '';
$sent    = false;
$emailVal = strtolower(trim($_GET['email'] ?? $_POST['email'] ?? ''));

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

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

    $emailVal = strtolower(trim($_POST['email'] ?? ''));

    if (!filter_var($emailVal, FILTER_VALIDATE_EMAIL)) {
        $msg = 'Please enter a valid email address.'; $msgType = 'e'; goto render;
    }

    try {
        $q = db()->prepare("SELECT user_id, first_name, last_name, is_email_verified FROM users WHERE email = ? LIMIT 1");
        $q->execute([$emailVal]);
        $u = $q->fetch();

        if (!$u) {
            // Don't reveal if email exists
            $msg  = 'If this email is registered and unverified, we\'ve sent a new verification link. Check your inbox.';
            $msgType = 'i'; $sent = true; goto render;
        }

        if ($u['is_email_verified']) {
            $msg  = 'This email is already verified. <a href="login.php" style="color:inherit;font-weight:700">Sign in →</a>';
            $msgType = 's'; goto render;
        }

        // Generate fresh token
        $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=?, updated_at=NOW() WHERE user_id=?")
           ->execute([$token, $exp, $u['user_id']]);

        $name   = trim($u['first_name'] . ' ' . $u['last_name']);
        $ok     = sendVerificationMail($emailVal, $name, $token);

        if ($ok) {
            $msg  = "✅ Verification email sent to <strong>{$emailVal}</strong>. Please check your inbox and spam folder.";
            $msgType = 's'; $sent = true;
        } else {
            // Mail failed — give direct verify link
            $uid  = $u['user_id'];
            $msg  = "Mail send nahi ho saka. <a href='verify_email.php?direct=1&uid={$uid}' style='color:inherit;font-weight:700;text-decoration:underline'>Yahan click karo direct verify karne ke liye →</a>";
            $msgType = 'w';
        }

    } catch(PDOException $e) {
        $msg = 'Server error. Please try again.'; $msgType = 'e';
        error_log('Resend verify error: ' . $e->getMessage());
    }
}
render:
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Resend Verification — 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{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)}

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

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

.card-body{padding:28px 32px 36px}

.fg{margin-bottom:18px}
.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)}
.fi:focus{border-color:var(--teal);box-shadow:0 0 0 3px rgba(26,127,142,.12)}
.fi::placeholder{color:#9CA3AF}

.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}

.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-w{background:#FFFBEB;border:1px solid #FDE68A;color:#92400E}
.alert-i{background:#EFF6FF;border:1px solid #BFDBFE;color:#1E40AF}

.hp{position:absolute;left:-9999px;opacity:0;pointer-events:none}
.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)}}
.back-link{display:block;text-align:center;margin-top:18px;font-size:13.5px;color:var(--muted)}
.footer{text-align:center;padding:14px;font-size:12px;color:var(--muted)}

/* Success state */
.success-box{text-align:center;padding:8px 0}
.success-icon{font-size:52px;margin-bottom:14px}
.success-title{font-size:19px;font-weight:700;color:var(--text);margin-bottom:8px}
.success-desc{font-size:13.5px;color:var(--muted);line-height:1.7;margin-bottom:22px}
</style>
</head>
<body>

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


<div class="page">
  <div class="card">

    <div class="card-hdr">
      <div class="card-hdr-title">📧 Resend Verification</div>
      <div class="card-hdr-sub">Enter your email to receive a new verification link</div>
    </div>

    <div class="card-body">

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

      <?php if (!$sent): ?>
      <!-- Form -->
      <form method="POST" id="resendForm" novalidate>
        <div class="hp" aria-hidden="true">
          <input type="text" name="website" tabindex="-1" autocomplete="off">
        </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($emailVal) ?>"
                 placeholder="you@university.edu"
                 autocomplete="email" required>
        </div>

        <button type="submit" class="btn" id="resendBtn">
          Send verification link
        </button>
      </form>

      <?php else: ?>
      <!-- Sent success state -->
      <div class="success-box">
        <div class="success-icon">✉️</div>
        <div class="success-title">Email sent!</div>
        <div class="success-desc">
          Check <strong><?= htmlspecialchars($emailVal) ?></strong><br>
          for the verification link.<br>
          <span style="font-size:12px">(Spam folder bhi check karo)</span>
        </div>
        <a href="login.php" class="btn" style="text-decoration:none;display:inline-flex;width:auto;padding:11px 32px">
          Go to Sign in →
        </a>
      </div>
      <?php endif; ?>

      <a href="login.php" class="back-link">← Back to Sign in</a>

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



<script>
document.getElementById('resendForm')?.addEventListener('submit', function() {
  const btn = document.getElementById('resendBtn');
  btn.disabled = true;
  btn.innerHTML = '<span class="spin"></span> Sending...';
});
</script>
</body>
</html>

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