<?php
// admin/forgot_password.php
if (session_status() === PHP_SESSION_NONE) session_start();

include __DIR__ . '/config/journal_config.php';   // provides $pdo
include __DIR__ . '/config/mailer.php';            // provides send_mail()

$step    = 'request';   // request | sent | reset | done
$error   = '';
$success = '';

// ── STEP 1 – User submits email ───────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {

    /* ---- 1a: send reset link ---- */
    if ($_POST['action'] === 'send_link') {
        $email = trim($_POST['email'] ?? '');

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Please enter a valid email address.';
        } else {
            $stmt = $pdo->prepare("SELECT id, first_name FROM admin_users WHERE email = ? AND is_active = 1 LIMIT 1");
            $stmt->execute([$email]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user) {
                $token   = bin2hex(random_bytes(32));          // 64-char hex
                $expires = date('Y-m-d H:i:s', time() + 3600); // 1 hour

                $pdo->prepare("UPDATE admin_users SET reset_token = ?, reset_token_expires = ? WHERE id = ?")
                    ->execute([$token, $expires, $user['id']]);

                $resetLink = "https://{$_SERVER['HTTP_HOST']}/journals/common/admin/forgot_password.php?token=$token";

                $body = "
                    <p>Hi {$user['first_name']},</p>
                    <p>We received a request to reset your password for the RSIS Submission System.</p>
                    <p><a href=\"$resetLink\" style=\"background:#1a3c5e;color:#fff;padding:10px 20px;border-radius:6px;text-decoration:none;\">Reset My Password</a></p>
                    <p>This link expires in <strong>1 hour</strong>.</p>
                    <p>If you didn't request this, you can safely ignore this email.</p>
                ";

                send_mail($email, 'Reset your RSIS password', $body);
            }

            // Always show "sent" — don't reveal if email exists
            $step = 'sent';
        }
    }

    /* ---- 1b: set new password ---- */
    elseif ($_POST['action'] === 'reset_password') {
        $token    = trim($_POST['token']    ?? '');
        $password = $_POST['new_password']  ?? '';
        $confirm  = $_POST['confirm_password'] ?? '';

        $stmt = $pdo->prepare("
            SELECT id FROM admin_users
            WHERE  reset_token = ?
              AND  reset_token_expires > NOW()
              AND  is_active = 1
            LIMIT 1
        ");
        $stmt->execute([$token]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            $error = 'This reset link is invalid or has expired. Please request a new one.';
            $step  = 'request';

        } elseif (strlen($password) < 8) {
            $error = 'Password must be at least 8 characters.';
            $step  = 'reset';

        } elseif (!preg_match('/[A-Z]/', $password) || !preg_match('/[0-9]/', $password)) {
            $error = 'Password must contain at least one uppercase letter and one number.';
            $step  = 'reset';

        } elseif ($password !== $confirm) {
            $error = 'Passwords do not match.';
            $step  = 'reset';

        } else {
            $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
            $pdo->prepare("
                UPDATE admin_users
                SET    password_hash = ?,
                       reset_token   = NULL,
                       reset_token_expires = NULL
                WHERE  id = ?
            ")->execute([$hash, $user['id']]);

            $step = 'done';
        }
    }
}

// ── STEP 2 – Token arrives via GET ───────────────────────────
elseif (isset($_GET['token'])) {
    $token = trim($_GET['token']);
    $stmt  = $pdo->prepare("
        SELECT id FROM admin_users
        WHERE  reset_token = ?
          AND  reset_token_expires > NOW()
          AND  is_active = 1
        LIMIT 1
    ");
    $stmt->execute([$token]);
    if ($stmt->fetch()) {
        $step = 'reset';
    } else {
        $error = 'This reset link is invalid or has expired.';
        $step  = 'request';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Reset Password — RSIS</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
  <style>
    :root { --brand: #1a3c5e; --brand-dark: #122d47; }
    body {
      font-family: 'Inter', sans-serif;
      background: #eef1f5;
      min-height: 100vh;
      display: flex;
      align-items: center;
    }
    .auth-card {
      width: 100%; max-width: 440px; margin: auto;
      border: none; border-radius: 14px; overflow: hidden;
      box-shadow: 0 8px 32px rgba(0,0,0,.12);
    }
    .auth-header {
      background: var(--brand); color: #fff;
      padding: 28px 28px 20px; text-align: center;
    }
    .auth-header h4 { font-weight: 700; font-size: 1.1rem; margin: 0; }
    .auth-header p  { font-size: .82rem; opacity: .75; margin: 5px 0 0; }
    .auth-body      { padding: 28px; background: #fff; }
    .form-label     { font-size: .875rem; font-weight: 500; color: #374151; }
    .form-control   { font-size: .9rem; border-radius: 8px; border-color: #d1d5db; }
    .form-control:focus {
      border-color: var(--brand);
      box-shadow: 0 0 0 3px rgba(26,60,94,.12);
    }
    .btn-brand {
      background: var(--brand); border: none; border-radius: 8px;
      font-weight: 600; padding: 10px;
    }
    .btn-brand:hover { background: var(--brand-dark); }
    .strength-bar { height: 4px; border-radius: 4px; transition: all .3s; }
    .pw-wrap { position: relative; }
    .pw-toggle {
      position: absolute; right: 12px; top: 50%;
      transform: translateY(-50%);
      background: none; border: none; color: #9ca3af; cursor: pointer; padding: 0;
    }
    .pw-toggle:hover { color: #374151; }
  </style>
</head>
<body>
<div class="container px-3">
  <div class="auth-card card">

    <!-- Header -->
    <div class="auth-header">
      <?php if ($step === 'sent'): ?>
        <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,.9)" stroke-width="1.8" class="mb-2"><path d="M4 4h16v16H4z"/><path d="M4 4l8 8 8-8"/></svg>
        <h4>Check your inbox</h4>
        <p>Reset instructions sent</p>
      <?php elseif ($step === 'reset'): ?>
        <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,.9)" stroke-width="1.8" class="mb-2"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
        <h4>Set new password</h4>
        <p>Choose a strong password</p>
      <?php elseif ($step === 'done'): ?>
        <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,.9)" stroke-width="1.8" class="mb-2"><path d="M20 6L9 17l-5-5"/></svg>
        <h4>Password updated!</h4>
        <p>You can now sign in</p>
      <?php else: ?>
        <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,.9)" stroke-width="1.8" class="mb-2"><circle cx="12" cy="12" r="10"/><path d="M12 8v4m0 4h.01"/></svg>
        <h4>Forgot password?</h4>
        <p>Enter your email to reset</p>
      <?php endif; ?>
    </div>

    <!-- Body -->
    <div class="auth-body">

      <?php if ($error): ?>
        <div class="alert alert-danger py-2 px-3 mb-3 d-flex align-items-center gap-2">
          <svg width="15" height="15" fill="currentColor" viewBox="0 0 16 16"><path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0-11a.75.75 0 0 0-.75.75v4.5a.75.75 0 0 0 1.5 0v-4.5A.75.75 0 0 0 8 4zm0 7.5a.875.875 0 1 0 0-1.75.875.875 0 0 0 0 1.75z"/></svg>
          <small><?= htmlspecialchars($error) ?></small>
        </div>
      <?php endif; ?>

      <!-- ── STEP: request ── -->
      <?php if ($step === 'request'): ?>
        <p class="small text-muted mb-4">Enter the email address associated with your account and we'll send you a reset link.</p>
        <form method="POST" novalidate>
          <input type="hidden" name="action" value="send_link">
          <div class="mb-4">
            <label for="email" class="form-label">Email address</label>
            <input type="email" name="email" id="email" class="form-control"
                   value="<?= htmlspecialchars($_POST['email'] ?? '') ?>"
                   placeholder="you@example.com" required autofocus>
          </div>
          <button type="submit" class="btn btn-brand btn-primary w-100">Send reset link</button>
          <div class="text-center mt-3">
            <a href="login.php" class="small text-muted">← Back to login</a>
          </div>
        </form>

      <!-- ── STEP: sent ── -->
      <?php elseif ($step === 'sent'): ?>
        <p class="text-center text-muted small mb-4">
          If <strong><?= htmlspecialchars($_POST['email'] ?? 'that email') ?></strong> is registered,
          you'll receive a reset link shortly.<br>
          The link expires in <strong>1 hour</strong>.
        </p>
        <a href="login.php" class="btn btn-brand btn-primary w-100">Back to login</a>
        <div class="text-center mt-3">
          <small class="text-muted">Didn't receive it?
            <a href="forgot_password.php" class="text-decoration-none">Try again</a>
          </small>
        </div>

      <!-- ── STEP: reset ── -->
      <?php elseif ($step === 'reset'): ?>
        <form method="POST" novalidate id="resetForm">
          <input type="hidden" name="action" value="reset_password">
          <input type="hidden" name="token" value="<?= htmlspecialchars($_GET['token'] ?? $_POST['token'] ?? '') ?>">

          <div class="mb-3">
            <label for="new_password" class="form-label">New password</label>
            <div class="pw-wrap">
              <input type="password" name="new_password" id="new_password"
                     class="form-control pe-5" placeholder="Min 8 chars" required
                     oninput="checkStrength(this.value)">
              <button type="button" class="pw-toggle" onclick="togglePw('new_password')">
                <svg width="17" height="17" fill="currentColor" viewBox="0 0 16 16"><path d="M16 8s-3-5.5-8-5.5S0 8 0 8s3 5.5 8 5.5S16 8 16 8zM8 11a3 3 0 1 1 0-6 3 3 0 0 1 0 6z"/></svg>
              </button>
            </div>
            <!-- Strength bar -->
            <div class="mt-2">
              <div class="strength-bar w-100 bg-light border">
                <div id="strengthBar" class="strength-bar" style="width:0%;background:#ef4444"></div>
              </div>
              <small id="strengthText" class="text-muted" style="font-size:.75rem"></small>
            </div>
            <div class="form-text" style="font-size:.75rem">
              At least 8 characters, one uppercase letter, one number.
            </div>
          </div>

          <div class="mb-4">
            <label for="confirm_password" class="form-label">Confirm password</label>
            <div class="pw-wrap">
              <input type="password" name="confirm_password" id="confirm_password"
                     class="form-control pe-5" placeholder="Repeat password" required>
              <button type="button" class="pw-toggle" onclick="togglePw('confirm_password')">
                <svg width="17" height="17" fill="currentColor" viewBox="0 0 16 16"><path d="M16 8s-3-5.5-8-5.5S0 8 0 8s3 5.5 8 5.5S16 8 16 8zM8 11a3 3 0 1 1 0-6 3 3 0 0 1 0 6z"/></svg>
              </button>
            </div>
          </div>

          <button type="submit" class="btn btn-brand btn-primary w-100">Update password</button>
        </form>

      <!-- ── STEP: done ── -->
      <?php elseif ($step === 'done'): ?>
        <p class="text-center text-muted small mb-4">
          Your password has been updated successfully. You can now sign in with your new password.
        </p>
        <a href="login.php?reset=success" class="btn btn-brand btn-primary w-100">Go to login</a>

      <?php endif; ?>

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

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
function togglePw(id) {
  const el = document.getElementById(id);
  el.type = el.type === 'password' ? 'text' : 'password';
}

function checkStrength(pw) {
  const bar  = document.getElementById('strengthBar');
  const text = document.getElementById('strengthText');
  let score  = 0;
  if (pw.length >= 8)              score++;
  if (/[A-Z]/.test(pw))           score++;
  if (/[0-9]/.test(pw))           score++;
  if (/[^A-Za-z0-9]/.test(pw))   score++;
  const levels = [
    { w: '0%',   c: '#ef4444', t: '' },
    { w: '25%',  c: '#ef4444', t: 'Weak' },
    { w: '50%',  c: '#f97316', t: 'Fair' },
    { w: '75%',  c: '#eab308', t: 'Good' },
    { w: '100%', c: '#22c55e', t: 'Strong' },
  ];
  bar.style.width      = levels[score].w;
  bar.style.background = levels[score].c;
  text.textContent     = levels[score].t;
  text.style.color     = levels[score].c;
}
</script>
</body>
</html>