<?php
session_start();
$page_title = 'Change Password';
$active_nav = 'profile';
include("includes/header.php");
$uid = (int)$_SESSION['user_id'];

$error = $success = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $current = (string)($_POST['current_password'] ?? '');
    $new     = (string)($_POST['new_password'] ?? '');
    $confirm = (string)($_POST['confirm_password'] ?? '');

    // Load the stored hash for this user.
    $stmt = $conn->prepare("SELECT password FROM users WHERE id=?");
    $stmt->bind_param("i", $uid);
    $stmt->execute();
    $row  = $stmt->get_result()->fetch_assoc();
    $hash = $row['password'] ?? '';

    if ($current === '' || $new === '' || $confirm === '') {
        $error = "Please fill in all three fields.";
    } elseif (!$hash || !password_verify($current, $hash)) {
        $error = "Your current password is incorrect.";
    } elseif (!preg_match('/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d)(?=.*[^A-Za-z0-9]).{8,}$/', $new)) {
        $error = "Password must be at least 8 characters and include an uppercase letter, a lowercase letter, a number, and a special character.";
    } elseif ($new !== $confirm) {
        $error = "The new passwords don't match.";
    } elseif (password_verify($new, $hash)) {
        $error = "Your new password must be different from your current one.";
    } else {
        $new_hash = password_hash($new, PASSWORD_BCRYPT, ['cost' => 12]);
        $upd = $conn->prepare("UPDATE users SET password=? WHERE id=?");
        $upd->bind_param("si", $new_hash, $uid);
        if ($upd->execute()) {
            $success = "Your password has been updated.";
        } else {
            $error = "We couldn't update your password right now. Please try again.";
        }
    }
}
?>

<style>
.app-topbar { display: none; }
.main-content { padding-top: calc(env(safe-area-inset-top) + 6px); }
.cp-wrap { max-width: 600px; margin: 0 auto; }

.sub-topbar { display: flex; align-items: center; justify-content: space-between; padding: 4px 2px 10px; }
.sub-topbar-left { display: flex; align-items: center; gap: 12px; min-width: 0; }
.sub-topbar .sub-back { width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: var(--primary); background: var(--primary-bg); flex-shrink: 0; }
.sub-topbar .icon-btn { color: var(--primary); }

.cp-hero { text-align: center; margin: 6px 0 20px; }
.cp-hero-icon { width: 64px; height: 64px; border-radius: 20px; background: var(--primary); display: flex; align-items: center; justify-content: center; margin: 0 auto 14px; color: #fff; box-shadow: 0 8px 22px rgba(34,90,227,.3); }
.cp-hero h1 { font-size: 1.5rem; font-weight: 800; letter-spacing: -.03em; margin-bottom: 6px; }
.cp-hero p { font-size: .86rem; color: var(--text-muted); line-height: 1.5; max-width: 340px; margin: 0 auto; }

.cp-card { background: #fff; border: 1px solid var(--border); border-radius: 18px; box-shadow: 0 4px 18px rgba(15,23,42,.06); padding: 20px; margin-bottom: 14px; }

.cp-field { margin-bottom: 16px; }
.cp-field:last-of-type { margin-bottom: 0; }
.cp-field label { display: block; font-size: .85rem; font-weight: 700; color: var(--text); margin-bottom: 8px; }
.cp-input-wrap { position: relative; }
.cp-input { width: 100%; height: 54px; border: 1.5px solid var(--border); background: var(--field-bg, #F7F9FC); border-radius: 13px; padding: 0 48px 0 16px; font-size: max(16px, .95rem); font-family: var(--font); color: var(--text); outline: none; transition: border-color .2s, box-shadow .2s, background .2s; }
.cp-input:focus { border-color: var(--primary); background: #fff; box-shadow: 0 0 0 3px rgba(34,90,227,.1); }
.cp-eye { position: absolute; right: 8px; top: 50%; transform: translateY(-50%); width: 40px; height: 40px; border: none; background: none; color: var(--text-light); display: flex; align-items: center; justify-content: center; cursor: pointer; touch-action: manipulation; }

.cp-divider { display: flex; align-items: center; gap: 12px; margin: 22px 0 18px; }
.cp-divider::before, .cp-divider::after { content: ''; flex: 1; height: 1px; background: var(--border); }
.cp-divider span { font-size: .66rem; font-weight: 800; letter-spacing: .12em; text-transform: uppercase; color: var(--text-light); }

.cp-meter { display: flex; gap: 6px; margin-top: 10px; }
.cp-meter .bar { flex: 1; height: 5px; border-radius: 3px; background: var(--border); transition: background .2s; }
.cp-meter.s1 .bar:nth-child(1) { background: var(--error); }
.cp-meter.s2 .bar:nth-child(-n+2) { background: var(--warning, #F59E0B); }
.cp-meter.s3 .bar:nth-child(-n+3) { background: #3B82F6; }
.cp-meter.s4 .bar { background: var(--success); }
.cp-meter-label { font-size: .74rem; color: var(--text-muted); margin-top: 8px; min-height: 16px; }

.cp-submit { width: 100%; height: 54px; border: none; border-radius: 14px; background: var(--primary); color: #fff; font-family: var(--font); font-weight: 700; font-size: .98rem; display: flex; align-items: center; justify-content: center; gap: 8px; cursor: pointer; box-shadow: 0 8px 22px rgba(34,90,227,.3); margin-top: 4px; }
.cp-submit:active { background: var(--primary-dark); }

.cp-forgot { display: block; text-align: center; color: var(--primary); font-weight: 700; font-size: .9rem; padding: 16px 8px; }

.cp-enc { display: flex; gap: 14px; align-items: flex-start; background: #fff; border: 1px solid var(--border); border-radius: 16px; padding: 16px; box-shadow: 0 4px 18px rgba(15,23,42,.05); }
.cp-enc .e-ic { width: 38px; height: 38px; border-radius: 11px; background: var(--primary-bg); color: var(--primary); display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
.cp-enc .e-title { font-weight: 700; font-size: .9rem; margin-bottom: 3px; }
.cp-enc .e-desc { font-size: .78rem; color: var(--text-muted); line-height: 1.45; }
/* Dark mode: card must darken so its text stays readable (was white-on-white). */
html.dark .cp-enc { background: var(--surface); border-color: var(--border); box-shadow: none; }
html.dark .cp-enc .e-title { color: var(--text); }
html.dark .cp-enc .e-ic { background: rgba(34,90,227,.18); }
</style>

<div class="cp-wrap">

  <div class="sub-topbar">
    <div class="sub-topbar-left">
      <a href="profile.php" class="sub-back" aria-label="Back" onclick="return goBack(event)">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 12H5m0 0l7 7M5 12l7-7"/></svg>
      </a>
    </div>
    <a href="help_center.php" class="icon-btn" title="Help">
      <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 115.83 1c0 2-3 2-3 4"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
    </a>
  </div>

  <div class="cp-hero">
    <div class="cp-hero-icon">
      <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg>
    </div>
    <h1>Change Password</h1>
    <p>Ensure your account stays secure by using a strong, unique password.</p>
  </div>

  <?php if ($error): ?>
  <div class="alert alert-error" style="margin-bottom:16px"><?php echo htmlspecialchars($error); ?></div>
  <?php endif; ?>
  <?php if ($success): ?>
  <div class="alert alert-success" style="margin-bottom:16px">
    <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
    <?php echo htmlspecialchars($success); ?>
  </div>
  <?php endif; ?>

  <form method="POST" id="cpForm" autocomplete="off">
    <div class="cp-card">
      <div class="cp-field">
        <label for="current_password">Current Password</label>
        <div class="cp-input-wrap">
          <input type="password" name="current_password" id="current_password" class="cp-input" placeholder="Enter current password" autocomplete="current-password" required>
          <button type="button" class="cp-eye" data-target="current_password" aria-label="Show password"></button>
        </div>
      </div>

      <div class="cp-divider"><span>Security Standard</span></div>

      <div class="cp-field">
        <label for="new_password">New Password</label>
        <div class="cp-input-wrap">
          <input type="password" name="new_password" id="new_password" class="cp-input" placeholder="Min. 8 characters" autocomplete="new-password" data-pwmeter required>
          <button type="button" class="cp-eye" data-target="new_password" aria-label="Show password"></button>
        </div>
        <div class="cp-meter" id="cpMeter"><span class="bar"></span><span class="bar"></span><span class="bar"></span><span class="bar"></span></div>
        <div class="cp-meter-label" id="cpMeterLabel"></div>
      </div>

      <div class="cp-field">
        <label for="confirm_password">Confirm New Password</label>
        <div class="cp-input-wrap">
          <input type="password" name="confirm_password" id="confirm_password" class="cp-input" placeholder="Repeat new password" autocomplete="new-password" required>
          <button type="button" class="cp-eye" data-target="confirm_password" aria-label="Show password"></button>
        </div>
        <div class="cp-meter-label" id="cpMatchLabel"></div>
      </div>
    </div>

    <button type="submit" class="cp-submit">
      Update Password
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M12 5l7 7-7 7"/></svg>
    </button>
  </form>

  <a href="forgot-password.php?change=1" class="cp-forgot">I forgot my password</a>

  <div class="cp-enc">
    <span class="e-ic"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg></span>
    <div>
      <div class="e-title">End-to-End Encryption</div>
      <div class="e-desc">Your data is protected by industry-leading 256-bit encryption protocols.</div>
    </div>
  </div>

</div>

<script>
(function () {
  // Eye toggles
  const eyeOpen  = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>';
  const eyeOff   = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>';
  document.querySelectorAll('.cp-eye').forEach(btn => {
    btn.innerHTML = eyeOpen;
    btn.addEventListener('click', () => {
      const inp = document.getElementById(btn.dataset.target);
      const show = inp.type === 'password';
      inp.type = show ? 'text' : 'password';
      btn.innerHTML = show ? eyeOff : eyeOpen;
    });
  });

  // Strength meter
  const np    = document.getElementById('new_password');
  const cf    = document.getElementById('confirm_password');
  const meter = document.getElementById('cpMeter');
  const label = document.getElementById('cpMeterLabel');
  const match = document.getElementById('cpMatchLabel');
  const words = ['', 'Weak', 'Fair', 'Good', 'Strong'];

  function score(p) {
    if (!p) return 0;
    let s = 0;
    if (p.length >= 8) s++;
    if (p.length >= 12) s++;
    if (/[A-Z]/.test(p) && /[a-z]/.test(p)) s++;
    if (/\d/.test(p) && /[^A-Za-z0-9]/.test(p)) s++;
    return Math.min(4, s || (p.length ? 1 : 0));
  }
  function refresh() {
    const s = score(np.value);
    meter.className = 'cp-meter' + (s ? ' s' + s : '');
    label.textContent = np.value ? words[s] + ' password' : '';
    label.style.color = s >= 3 ? 'var(--success)' : (s === 2 ? 'var(--warning, #F59E0B)' : 'var(--text-muted)');
    if (cf.value) {
      const ok = cf.value === np.value;
      match.textContent = ok ? 'Passwords match' : 'Passwords don\'t match yet';
      match.style.color = ok ? 'var(--success)' : 'var(--error)';
    } else {
      match.textContent = '';
    }
  }
  np.addEventListener('input', refresh);
  cf.addEventListener('input', refresh);

  // Guard obvious mistakes before submitting
  document.getElementById('cpForm').addEventListener('submit', e => {
    if (np.value.length < 8) { e.preventDefault(); alert('Your new password must be at least 8 characters.'); np.focus(); return; }
    if (np.value !== cf.value) { e.preventDefault(); alert('The new passwords don\'t match.'); cf.focus(); }
  });
})();
</script>

<script src="assets/js/pwmeter.js?v=1"></script>
<?php include("includes/footer.php"); ?>
