<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/mailer.php';

$step    = $_GET['step']  ?? 'request';
$token   = trim($_GET['token'] ?? '');
$error   = '';
$success = '';

// Validate token when on reset step
if ($step === 'reset') {
    if (!$token) { $step = 'request'; }
    else {
        $stmt = db()->prepare("SELECT id,name,email FROM managers WHERE reset_token=? AND reset_expires>NOW() AND is_active=1 LIMIT 1");
        $stmt->execute([$token]);
        $mgr = $stmt->fetch();
        if (!$mgr) { $step = 'request'; $error = 'This reset link has expired or is invalid. Request a new one.'; }
    }
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    if (!verifyCsrf($_POST['csrf_token'] ?? '')) { $error = 'Session expired. Refresh.'; }
    else {
        $act = $_POST['action'] ?? '';

        // ── Step 1: send email ────────────────────────────────
        if ($act === 'request') {
            $email = trim($_POST['email'] ?? '');
            if (!filter_var($email, FILTER_VALIDATE_EMAIL))
                $error = 'Please enter a valid email address.';
            else {
                $stmt = db()->prepare("SELECT id,name,email,is_active FROM managers WHERE email=? LIMIT 1");
                $stmt->execute([$email]);
                $m = $stmt->fetch();
                if ($m) {
                    if ((int)$m['is_active']) {
                        $tok = bin2hex(random_bytes(32));
                        $exp = date('Y-m-d H:i:s', time() + 1800);
                        db()->prepare("UPDATE managers SET reset_token=?,reset_expires=? WHERE id=?")
                           ->execute([$tok, $exp, $m['id']]);
                        $link = BASE_URL . '/forgot_password.php?step=reset&token=' . $tok;
                        try {
                            $sent = mailPasswordReset($m['email'], $m['name'], $link);
                            if (!$sent) {
                                error_log("Password reset: mailPasswordReset returned false for {$email}");
                            } else {
                                error_log("Password reset: Email successfully sent to {$email}");
                            }
                        } catch (Throwable $mailError) {
                            error_log('Password reset email failed: ' . $mailError->getMessage());
                        }
                    } else {
                        error_log("Password reset request ignored: Manager account is inactive/suspended for email {$email}");
                    }
                } else {
                    error_log("Password reset request ignored: Email address {$email} is not registered in the managers table");
                }
                $success = 'If that email is registered, a reset link has been sent. Check your inbox (and spam folder).';
            }
        }

        // ── Step 2: update password ────────────────────────────
        elseif ($act === 'reset') {
            $tok = $_POST['token'] ?? '';
            $p1  = $_POST['password']  ?? '';
            $p2  = $_POST['password2'] ?? '';
            $stmt = db()->prepare("SELECT id,name FROM managers WHERE reset_token=? AND reset_expires>NOW() AND is_active=1 LIMIT 1");
            $stmt->execute([$tok]);
            $m = $stmt->fetch();
            if (!$m)           $error = 'Reset link expired. Please request a new one.';
            elseif(strlen($p1) < 8) $error = 'Password must be at least 8 characters.';
            elseif($p1 !== $p2) $error = 'Passwords do not match.';
            else {
                $hash = password_hash($p1, PASSWORD_BCRYPT, ['cost' => 12]);
                db()->prepare("UPDATE managers SET password_hash=?,reset_token=NULL,reset_expires=NULL WHERE id=?")
                   ->execute([$hash, $m['id']]);
                logEvent('manager', $m['id'], '', 'password_reset');
                $success = 'Password updated! You can now log in with your new password.';
                $step = 'done';
            }
        }
    }
}

$csrf = csrfToken();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Reset Password — Hammerhead Protection</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
:root {
  --bg-gradient: linear-gradient(135deg, #020813 0%, #071527 50%, #0d2545 100%);
  --card-bg: rgba(15, 30, 54, 0.75);
  --card-border: rgba(255, 255, 255, 0.08);
  --input-bg: rgba(9, 18, 32, 0.6);
  --input-border: rgba(255, 255, 255, 0.15);
  --input-focus: #26a0f5;
  --text-main: #ffffff;
  --text-muted: #94a3b8;
  --text-label: #cbd5e1;
  --btn-gradient: linear-gradient(135deg, #0e5e9e 0%, #1678c7 50%, #26a0f5 100%);
  --btn-hover: linear-gradient(135deg, #1268a7 0%, #1678c7 50%, #3caeff 100%);
  --err-bg: rgba(239, 68, 68, 0.15);
  --err-border: rgba(239, 68, 68, 0.3);
  --err-text: #fca5a5;
  --ok-bg: rgba(16, 185, 129, 0.15);
  --ok-border: rgba(16, 185, 129, 0.3);
  --ok-text: #a7f3d0;
}

html, body { height: 100%; }
body {
  font-family: 'Inter', system-ui, -apple-system, sans-serif;
  background: var(--bg-gradient) !important;
  color: var(--text-main) !important;
  display: flex; align-items: center; justify-content: center;
  min-height: 100vh; overflow: hidden;
}

/* Ambient blobs with deep blue and cyan/indigo glows */
.blob { position: fixed; border-radius: 50%; filter: blur(100px); pointer-events: none; opacity: 0.25; }
.blob1 { width: 550px; height: 550px; background: radial-gradient(circle, #0e5e9e, transparent 70%); top: -150px; right: -100px; animation: bm 10s ease-in-out infinite alternate; }
.blob2 { width: 450px; height: 450px; background: radial-gradient(circle, #102a45, transparent 70%); bottom: -120px; left: -80px; animation: bm 12s ease-in-out infinite alternate-reverse; }
.blob3 { width: 350px; height: 350px; background: radial-gradient(circle, #26a0f5, transparent 70%); top: 50%; left: 50%; transform: translate(-50%, -50%); animation: bm 8s ease-in-out infinite alternate; }
@keyframes bm { 0% { transform: scale(1) translate(0,0); } 100% { transform: scale(1.1) translate(20px, -20px); } }

/* The glassmorphic card */
.card {
  width: min(430px, 96vw);
  background: var(--card-bg) !important;
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border: 1px solid var(--card-border) !important;
  border-radius: 28px !important;
  padding: 44px 38px 36px !important;
  position: relative; z-index: 10;
  box-shadow: 0 24px 60px rgba(0, 0, 0, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;
}

/* Headings and text */
.head { text-align: center; margin-bottom: 26px; }
.shield-wrap {
  display: inline-flex; align-items: center; justify-content: center;
  width: 72px; height: 72px; border-radius: 20px; margin-bottom: 16px;
  background: linear-gradient(145deg, #102644, #0b1a2e);
  border: 1px solid rgba(255, 255, 255, 0.08);
  box-shadow: 0 8px 24px rgba(0,0,0,0.3);
  font-size: 2.2rem;
}
.head h1 { color: var(--text-main) !important; font-size: 1.2rem; font-weight: 700; line-height: 1.3; }
.head p { color: var(--text-muted) !important; font-size: 0.82rem; margin-top: 5px; opacity: 1 !important; }
.orange-line {
  height: 2px; margin: 0 0 26px;
  background: linear-gradient(90deg, transparent, #26a0f5 40%, #0e5e9e 60%, transparent);
  border-radius: 2px;
}
.green-line {
  height: 2px; margin: 0 0 26px;
  background: linear-gradient(90deg, transparent, #22c55e 40%, #16a34a 60%, transparent);
  border-radius: 2px;
}

/* Alert styling */
.alert {
  display: flex; gap: 10px; align-items: flex-start;
  border-radius: 12px; padding: 12px 15px; font-size: 0.82rem; margin-bottom: 20px;
}
.alert-err {
  background: var(--err-bg); border: 1px solid var(--err-border); color: var(--err-text);
}
.alert-ok {
  background: var(--ok-bg); border: 1px solid var(--ok-border); color: var(--ok-text);
}

/* Form fields */
.field { margin-bottom: 18px; }
label.lbl {
  display: block; font-size: 0.72rem; font-weight: 700;
  text-transform: uppercase; letter-spacing: 0.8px;
  color: var(--text-label); margin-bottom: 8px;
}
.inp-w { position: relative; }
.inp-ico {
  position: absolute; left: 15px; top: 50%; transform: translateY(-50%);
  font-size: 0.95rem; opacity: 0.6; pointer-events: none; line-height: 1;
}
input.inp {
  width: 100%;
  padding: 13px 15px 13px 44px;
  background: var(--input-bg) !important;
  border: 1.5px solid var(--input-border) !important;
  border-radius: 14px;
  color: var(--text-main) !important; font-size: 0.88rem;
  outline: none; transition: all 0.2s;
  box-shadow: inset 0 2px 4px rgba(0,0,0,0.2);
}
input.inp:focus {
  border-color: var(--input-focus) !important;
  box-shadow: inset 0 2px 4px rgba(0,0,0,0.2), 0 0 0 4px rgba(38, 160, 245, 0.2) !important;
}
input.inp::placeholder { color: rgba(255,255,255,0.3); }
.pw-eye {
  position: absolute; right: 14px; top: 50%; transform: translateY(-50%);
  background: none; border: none; cursor: pointer;
  color: var(--text-muted); font-size: 0.95rem; padding: 3px;
  transition: color 0.15s; line-height: 1;
}
.pw-eye:hover { color: var(--text-main); }

/* Captcha Badge */
.cap-row { display: flex; gap: 10px; align-items: flex-end; }
.cap-row .field { flex: 1; margin-bottom: 0; }
.cap-badge {
  background: linear-gradient(145deg, #102644, #0b1a2e);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 14px; padding: 0 16px;
  height: 48px; display: flex; flex-direction: column; align-items: center; justify-content: center;
  min-width: 96px; box-shadow: 0 4px 12px rgba(0,0,0,0.2); flex-shrink: 0;
}
.cap-badge .cq { color: #26a0f5; font-size: 1.05rem; font-weight: 700; line-height: 1; }
.cap-badge .ce { color: var(--text-muted); font-size: 0.62rem; letter-spacing: 0.4px; margin-top: 2px; }

/* Buttons */
.btn-login, .btn-sa, .btn-primary {
  width: 100%; padding: 14px; margin-top: 6px;
  border: none; border-radius: 14px;
  background: var(--btn-gradient) !important;
  color: #ffffff !important; font-size: 0.92rem; font-weight: 700; letter-spacing: 0.3px;
  cursor: pointer; transition: all 0.2s;
  box-shadow: 0 6px 20px rgba(22, 120, 214, 0.3), inset 0 1px 0 rgba(255,255,255,0.15);
  position: relative; overflow: hidden;
  text-align: center; text-decoration: none; display: block;
}
.btn-login:hover, .btn-sa:hover, .btn-primary:hover {
  transform: translateY(-2px);
  background: var(--btn-hover) !important;
  box-shadow: 0 8px 24px rgba(22, 120, 214, 0.45), inset 0 1px 0 rgba(255,255,255,0.15);
}
.btn-login:active, .btn-sa:active, .btn-primary:active { transform: translateY(0); }
.btn-login:disabled, .btn-sa:disabled, .btn-primary:disabled { opacity: 0.55; cursor: not-allowed; transform: none; }

/* Extras and links */
.extras, .back-link { text-align: center; margin-top: 18px; }
.extras a, .back-link a { color: #60a5fa; font-size: 0.82rem; text-decoration: none; transition: color 0.15s; }
.extras a:hover, .back-link a:hover { color: #93c5fd; text-decoration: underline; }
.footer { text-align: center; margin-top: 26px; padding-top: 18px; border-top: 1px solid rgba(255,255,255,0.08); }
.footer p { color: var(--text-muted); font-size: 0.68rem; }
.big-icon { text-align: center; font-size: 2.6rem; margin-bottom: 12px; }
.str-bar { height: 4px; border-radius: 2px; background: rgba(255,255,255,0.08); margin-top: 6px; overflow: hidden; }
.str-inner { height: 100%; border-radius: 2px; transition: 0.3s; width: 0; }
.spin{display:inline-block;width:14px;height:14px;border:2px solid rgba(255,255,255,.25);border-top-color:#fff;border-radius:50%;animation:sp .6s linear infinite;vertical-align:middle;margin-right:7px;}
@keyframes sp{to{transform:rotate(360deg);}}
</style>
</head>
<body>
<div class="blob blob1"></div>
<div class="blob blob2"></div>

<div class="card">
  <div class="head">
    <div class="shield-wrap">🛡️</div>
    <h1>Hammerhead Protection Inc.</h1>
    <p><?= $step === 'reset' ? 'Set New Password' : ($step === 'done' ? 'Password Updated' : 'Reset Password') ?></p>
  </div>
  <div class="orange-line"></div>

  <?php if ($error): ?>
    <div class="alert alert-err"><span>⚠</span><span><?= htmlspecialchars($error) ?></span></div>
  <?php endif; ?>
  <?php if ($success): ?>
    <div class="alert alert-ok"><span>✓</span><span><?= htmlspecialchars($success) ?></span></div>
  <?php endif; ?>

  <?php if ($step === 'request' && !$success): ?>
  <form method="POST">
    <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
    <input type="hidden" name="action" value="request">
    <div class="field">
      <label class="lbl">Registered Email Address</label>
      <div class="inp-w">
        <span class="inp-ico">📧</span>
        <input class="inp" type="email" name="email" placeholder="your@email.com" required
               value="<?= htmlspecialchars($_POST['email'] ?? '') ?>">
      </div>
    </div>
    <button type="submit" class="btn-primary">Send Reset Link →</button>
  </form>

  <?php elseif ($step === 'reset' && isset($mgr) && !$success): ?>
  <form method="POST" id="rf">
    <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
    <input type="hidden" name="action" value="reset">
    <input type="hidden" name="token" value="<?= htmlspecialchars($token) ?>">
    <p style="color:var(--txt2);font-size:.82rem;margin-bottom:20px;">
      Resetting password for <strong style="color:var(--txt)"><?= htmlspecialchars($mgr['name']) ?></strong>
    </p>
    <div class="field">
      <label class="lbl">New Password</label>
      <div class="inp-w">
        <span class="inp-ico">🔒</span>
        <input class="inp" type="password" id="p1" name="password"
               placeholder="Min 8 characters" required oninput="strength(this.value)">
        <button type="button" class="pw-eye" onclick="tpw('p1')">👁</button>
      </div>
      <div class="str-bar"><div class="str-inner" id="sbar"></div></div>
    </div>
    <div class="field">
      <label class="lbl">Confirm Password</label>
      <div class="inp-w">
        <span class="inp-ico">🔒</span>
        <input class="inp" type="password" id="p2" name="password2"
               placeholder="Repeat new password" required>
        <button type="button" class="pw-eye" onclick="tpw('p2')">👁</button>
      </div>
    </div>
    <button type="submit" class="btn-primary">Update Password →</button>
  </form>

  <?php elseif ($step === 'done'): ?>
    <div class="big-icon">✅</div>
    <p style="color:var(--txt);text-align:center;font-size:.9rem;">Your password has been successfully updated.</p>
  <?php endif; ?>

  <div class="back-link"><a href="/login.php">← Back to Login</a></div>
  <div class="footer"><p>© <?= date('Y') ?> Hammerhead Protection Inc.</p></div>
</div>

<script>
function tpw(id){var e=document.getElementById(id);e.type=e.type==='password'?'text':'password';}
function strength(v){
  var s=0;
  if(v.length>=8)s++;if(v.length>=12)s++;
  if(/[A-Z]/.test(v))s++;if(/[0-9]/.test(v))s++;if(/[^a-zA-Z0-9]/.test(v))s++;
  var bar=document.getElementById('sbar');
  var col=['#ef4444','#f97316','#eab308','#22c55e','#16a34a'];
  bar.style.width=(s*20)+'%';
  bar.style.background=col[Math.max(s-1,0)];
}
</script>
</body>
</html>
