<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/config/mail.php';
startSession();

if (isLoggedIn()) { header('Location: dashboard.php'); exit; }

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    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_active
             FROM users WHERE email = ? LIMIT 1"
        );
        $q->execute([$emailVal]);
        $u = $q->fetch();

        if ($u && $u['is_active']) {
            $token = bin2hex(random_bytes(32));
            $exp   = date('Y-m-d H:i:s', strtotime('+1 hour'));

            // UPDATE with raw column names — no ALTER TABLE needed
            // Columns must already exist (run setup_auth_tables.sql first)
            try {
                db()->prepare(
                    "UPDATE users
                     SET password_reset_token = ?,
                         password_reset_expires = ?,
                         updated_at = NOW()
                     WHERE user_id = ?"
                )->execute([$token, $exp, $u['user_id']]);
            } catch(PDOException $colErr) {
                // Columns don't exist yet — tell user to run SQL
                $msg = '⚠️ Setup incomplete. Please run <strong>setup_auth_tables.sql</strong> in phpMyAdmin first, then try again.<br><small>Error: ' . htmlspecialchars($colErr->getMessage()) . '</small>';
                $msgType = 'e';
                goto render;
            }

            $name = trim($u['first_name'] . ' ' . $u['last_name']);
            $link = APP_URL . '/reset_password.php?token=' . urlencode($token);

            // Beautiful email HTML
            $html = '
            <div style="font-family:Arial,sans-serif;max-width:520px;margin:0 auto;border-radius:8px;overflow:hidden;border:1px solid #e5e7eb">
              <div style="background:#E05A2B;padding:22px 30px;text-align:center">
                <span style="font-size:24px;font-weight:700;color:#fff">🌿 communeglobal</span>
              </div>
              <div style="background:#fff;padding:32px 30px">
                <h2 style="color:#222;font-size:20px;margin:0 0 14px">Reset your password</h2>
                <p style="color:#555;font-size:14px;line-height:1.7;margin:0 0 24px">
                  Hi <strong>' . htmlspecialchars($name) . '</strong>,<br><br>
                  We received a request to reset your communeglobal account password.
                  Click the button below to set a new password.
                </p>
                <div style="text-align:center;margin-bottom:28px">
                  <a href="' . $link . '" style="display:inline-block;padding:14px 36px;background:#1A7F8E;color:#fff;border-radius:6px;font-size:15px;font-weight:700;text-decoration:none">
                    🔑 Reset My Password
                  </a>
                </div>
                <p style="color:#aaa;font-size:12px;line-height:1.7">
                  ⏰ This link expires in <strong>1 hour</strong>.<br>
                  If you did not request this, you can safely ignore this email.<br><br>
                  Or copy this link:<br>
                  <a href="' . $link . '" style="color:#1A7F8E;word-break:break-all">' . $link . '</a>
                </p>
              </div>
              <div style="background:#f9f9f9;padding:12px 20px;text-align:center;font-size:11px;color:#999">
                © 2026 communeglobal Journals
              </div>
            </div>';

            $ok = sendMail($emailVal, $name, 'Reset your communeglobal password', $html);

            if (!$ok) {
                // Mail failed — show direct link (good for localhost)
                $msg = '⚠️ Mail send nahi ho saka (SMTP issue).<br><br>
                    <strong>Direct reset link (localhost ke liye):</strong><br>
                    <a href="reset_password.php?token=' . htmlspecialchars($token) . '"
                       style="color:#1A7F8E;font-weight:700;word-break:break-all">
                       👉 Yahan click karo — Password Reset Karo
                    </a>';
                $msgType = 'w';
                goto render;
            }
        }

        // Always show success (even if email not found — security)
        $sent = true;

    } 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>Forgot Password — 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;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}
.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.7;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}
.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-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">🔑 Forgot Password?</div>
      <div class="card-hdr-sub">Enter your email — we'll send a reset link</div>
    </div>
    <div class="card-body">

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

      <?php if (!$sent): ?>
      <form method="POST" id="fpForm" 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">Registered email address</label>
          <input class="fi" type="email" id="email" name="email"
                 value="<?= htmlspecialchars($emailVal) ?>"
                 placeholder="you@university.edu"
                 autocomplete="email" required autofocus>
        </div>
        <button type="submit" class="btn" id="fpBtn">Send reset link</button>
      </form>

      <?php else: ?>
      <div class="success-box">
        <div class="success-icon">📬</div>
        <div class="success-title">Check your inbox!</div>
        <div class="success-desc">
          If <strong><?= htmlspecialchars($emailVal) ?></strong> is registered,<br>
          we've sent a password reset link.<br>
          <span style="font-size:12px;color:#9CA3AF">(Spam folder bhi check karo · Link 1 hour valid)</span>
        </div>
        <a href="login.php" class="btn" style="text-decoration:none;display:inline-flex;width:auto;padding:11px 32px">
          Back 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('fpForm')?.addEventListener('submit', function() {
  const btn = document.getElementById('fpBtn');
  btn.disabled = true;
  btn.innerHTML = '<span class="spin"></span> Sending...';
});
</script>
</body>
</html>


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