<?php
// ============================================================
//  change_password.php  —  Author: Change Password
// ============================================================
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
ini_set("display_errors", 0);
require_once __DIR__ . '/config/db.php';
startSession();

$user    = getCurrentUser();
$user_id = $user['user_id'];

// ── Shared layout identity ────────────────────────────────────
$pageTitle  = 'Change Password';
$activePage = 'change_password';

// ── Handle AJAX password change ───────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_change_password'])) {
    header('Content-Type: application/json');
    try {
        $current = $_POST['current_password'] ?? '';
        $new     = $_POST['new_password']     ?? '';
        $confirm = $_POST['confirm_password'] ?? '';

        if (!$current || !$new || !$confirm) {
            echo json_encode(['success' => false, 'message' => 'All fields are required.']);
            exit;
        }
        if (strlen($new) < 8) {
            echo json_encode(['success' => false, 'message' => 'New password must be at least 8 characters.']);
            exit;
        }
        if ($new !== $confirm) {
            echo json_encode(['success' => false, 'message' => 'New passwords do not match.']);
            exit;
        }

        // Load stored password hash
        $stmt = db()->prepare("SELECT password FROM users WHERE user_id=?");
        $stmt->execute([$user_id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$row) {
            echo json_encode(['success' => false, 'message' => 'User not found.']);
            exit;
        }

        // Verify current password
        if (!password_verify($current, $row['password'])) {
            echo json_encode(['success' => false, 'message' => 'Current password is incorrect.']);
            exit;
        }

        // Update with new hash
        $hash = password_hash($new, PASSWORD_BCRYPT);
        db()->prepare("UPDATE users SET password=? WHERE user_id=?")
            ->execute([$hash, $user_id]);

        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

require_once __DIR__ . '/_layout.php';
?>

<style>
/* ── change_password page styles ─────────────────────────── */
.au-main { padding: 24px 28px 60px; }

.cp-container {
  max-width: 580px;
  margin: 0 auto;
}

/* Card */
.cp-card {
  background: var(--white);
  border: 1px solid var(--border);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0,0,0,.06);
}

.cp-card-header {
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 20px 24px;
  border-bottom: 1px solid var(--border);
}
.cp-icon {
  width: 42px; height: 42px;
  border-radius: 10px;
  background: #FFF3E0;
  display: flex; align-items: center; justify-content: center;
  font-size: 20px; flex-shrink: 0;
}
.cp-card-title { font-size: 16px; font-weight: 700; color: var(--text); }
.cp-card-sub   { font-size: 12.5px; color: var(--muted); margin-top: 2px; }

.cp-card-body { padding: 24px; }

/* Form fields */
.cp-group { margin-bottom: 18px; }
.cp-label {
  display: flex; align-items: center; gap: 5px;
  font-size: 13px; font-weight: 600; color: var(--text);
  margin-bottom: 6px;
}
.cp-label .req { color: #DC2626; font-size: 11px; }
.cp-input-wrap { position: relative; }
.cp-input {
  width: 100%; padding: 10px 40px 10px 14px;
  border: 1.5px solid var(--border);
  border-radius: 8px;
  font-family: var(--font); font-size: 13.5px;
  color: var(--text); background: var(--white);
  outline: none; transition: border-color .15s;
}
.cp-input:focus {
  border-color: var(--blue);
  box-shadow: 0 0 0 3px rgba(27,63,110,.1);
}
.cp-input.err { border-color: #DC2626 !important; }

/* Toggle password visibility */
.cp-eye {
  position: absolute; right: 12px; top: 50%;
  transform: translateY(-50%);
  background: none; border: none; cursor: pointer;
  color: var(--muted); font-size: 15px; padding: 2px;
  transition: color .15s; line-height: 1;
}
.cp-eye:hover { color: var(--text); }

/* Strength bar */
.strength-bar-wrap {
  height: 4px; background: #E5E7EB;
  border-radius: 99px; margin-top: 8px; overflow: hidden;
  display: none;
}
.strength-bar-wrap.show { display: block; }
.strength-bar {
  height: 100%; border-radius: 99px;
  transition: width .3s, background .3s;
}
.strength-hint { font-size: 11.5px; color: var(--muted); margin-top: 4px; display: none; }
.strength-hint.show { display: block; }

/* Error message */
.cp-err {
  display: none; align-items: center; gap: 5px;
  font-size: 12px; color: #DC2626; margin-top: 5px; font-weight: 500;
}
.cp-err.show { display: flex; }

/* Update button */
.btn-update-password {
  width: 100%; padding: 13px;
  background: var(--blue);
  color: #fff; border: none;
  border-radius: 8px;
  font-family: var(--font); font-size: 14px; font-weight: 700;
  cursor: pointer; transition: background .15s;
  display: flex; align-items: center; justify-content: center; gap: 8px;
  margin-top: 4px;
}
.btn-update-password:hover    { background: #132B50; }
.btn-update-password:disabled { opacity: .6; cursor: not-allowed; }

/* Success notice */
.cp-success {
  display: none; align-items: center; gap: 10px;
  background: #F0FDF4; border: 1px solid #86EFAC;
  border-radius: 8px; padding: 14px 18px;
  font-size: 13.5px; color: #166534; font-weight: 600;
  margin-top: 16px;
}
.cp-success.show { display: flex; }

/* Divider hint */
.cp-requirements {
  background: #F8FAFC; border: 1px solid var(--border);
  border-radius: 8px; padding: 12px 16px;
  font-size: 12.5px; color: var(--muted);
  line-height: 1.8; margin-bottom: 20px;
}
.cp-requirements ul { list-style: none; padding: 0; }
.cp-requirements li::before { content: '• '; color: var(--blue); font-weight: 700; }

/* Toast */
.toast-wrap { position: fixed; bottom: 24px; right: 24px; display: flex; flex-direction: column; gap: 8px; z-index: 9999; }
.toast { padding: 11px 16px; border-radius: 8px; font-size: 13px; font-weight: 500; color: #fff; box-shadow: 0 4px 14px rgba(0,0,0,.18); display: flex; align-items: center; gap: 8px; animation: tup .25s ease; }
.ts { background: #1D8A5E; } .te { background: #DC2626; }
@keyframes tup { from{opacity:0;transform:translateY(8px)} to{opacity:1;transform:translateY(0)} }
.spinner { display: inline-block; width: 15px; height: 15px; border: 2px solid rgba(255,255,255,.3); border-top-color: #fff; border-radius: 50%; animation: spin .6s linear infinite; }
@keyframes spin { to{transform:rotate(360deg)} }
</style>

<div class="cp-container">
  <div class="cp-card">

    <!-- Card header -->
    <div class="cp-card-header">
      <div class="cp-icon">🔑</div>
      <div>
        <div class="cp-card-title">Change Password</div>
        <div class="cp-card-sub">Minimum 8 characters required</div>
      </div>
    </div>

    <!-- Card body -->
    <div class="cp-card-body">

      <!-- Requirements hint -->
      <div class="cp-requirements">
        <ul>
          <li>At least 8 characters long</li>
          <li>New password must differ from current password</li>
          <li>Both new password fields must match</li>
        </ul>
      </div>

      <!-- Current Password -->
      <div class="cp-group">
        <label class="cp-label" for="currentPassword">
          Current Password <span class="req">*</span>
        </label>
        <div class="cp-input-wrap">
          <input type="password" class="cp-input" id="currentPassword"
                 placeholder="Enter current password"
                 oninput="clearErr('currentErr')">
          <button type="button" class="cp-eye" onclick="togglePwd('currentPassword',this)" title="Show/hide">👁</button>
        </div>
        <div class="cp-err" id="currentErr"></div>
      </div>

      <!-- New Password -->
      <div class="cp-group">
        <label class="cp-label" for="newPassword">
          New Password <span class="req">*</span>
        </label>
        <div class="cp-input-wrap">
          <input type="password" class="cp-input" id="newPassword"
                 placeholder="At least 8 characters"
                 oninput="onNewPwdInput(this); clearErr('newErr')">
          <button type="button" class="cp-eye" onclick="togglePwd('newPassword',this)" title="Show/hide">👁</button>
        </div>
        <div class="strength-bar-wrap" id="strengthWrap">
          <div class="strength-bar" id="strengthBar"></div>
        </div>
        <div class="strength-hint" id="strengthHint"></div>
        <div class="cp-err" id="newErr"></div>
      </div>

      <!-- Confirm New Password -->
      <div class="cp-group">
        <label class="cp-label" for="confirmPassword">
          Confirm New Password <span class="req">*</span>
        </label>
        <div class="cp-input-wrap">
          <input type="password" class="cp-input" id="confirmPassword"
                 placeholder="Repeat new password"
                 oninput="clearErr('confirmErr')">
          <button type="button" class="cp-eye" onclick="togglePwd('confirmPassword',this)" title="Show/hide">👁</button>
        </div>
        <div class="cp-err" id="confirmErr"></div>
      </div>

      <!-- Submit button -->
      <button type="button" class="btn-update-password" id="updateBtn" onclick="doChangePassword()">
        🔒 Update Password
      </button>

      <!-- Success notice -->
      <div class="cp-success" id="cpSuccess">
        <span>✅</span> Password updated successfully!
      </div>

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

<div class="toast-wrap" id="toastWrap"></div>

<script>
/* ── Toggle password visibility ─────────────────────────── */
function togglePwd(inputId, btn) {
    const inp = document.getElementById(inputId);
    const isText = inp.type === 'text';
    inp.type = isText ? 'password' : 'text';
    btn.textContent = isText ? '👁' : '🙈';
}

/* ── Password strength ───────────────────────────────────── */
function onNewPwdInput(inp) {
    const val = inp.value;
    const wrap = document.getElementById('strengthWrap');
    const bar  = document.getElementById('strengthBar');
    const hint = document.getElementById('strengthHint');

    if (!val) {
        wrap.classList.remove('show');
        hint.classList.remove('show');
        return;
    }

    wrap.classList.add('show');
    hint.classList.add('show');

    let score = 0;
    if (val.length >= 8)  score++;
    if (val.length >= 12) score++;
    if (/[A-Z]/.test(val)) score++;
    if (/[0-9]/.test(val)) score++;
    if (/[^A-Za-z0-9]/.test(val)) score++;

    const levels = [
        { pct: '20%', bg: '#EF4444', label: 'Very weak' },
        { pct: '40%', bg: '#F97316', label: 'Weak' },
        { pct: '60%', bg: '#EAB308', label: 'Fair' },
        { pct: '80%', bg: '#22C55E', label: 'Strong' },
        { pct: '100%',bg: '#16A34A', label: 'Very strong' },
    ];
    const lvl = levels[Math.min(score, 4)];
    bar.style.width      = lvl.pct;
    bar.style.background = lvl.bg;
    hint.textContent     = lvl.label;
    hint.style.color     = lvl.bg;
}

/* ── Clear individual error ──────────────────────────────── */
function clearErr(id) {
    const el = document.getElementById(id);
    if (el) { el.textContent = ''; el.classList.remove('show'); }
    document.getElementById('cpSuccess').classList.remove('show');
}

/* ── Show error on a field ───────────────────────────────── */
function showErr(inputId, errId, msg) {
    document.getElementById(inputId).classList.add('err');
    const err = document.getElementById(errId);
    err.textContent = msg;
    err.classList.add('show');
}

function clearInputErr(inputId) {
    document.getElementById(inputId).classList.remove('err');
}

/* ── Main change password handler ────────────────────────── */
function doChangePassword() {
    // Clear all errors first
    ['currentPassword','newPassword','confirmPassword'].forEach(id => {
        document.getElementById(id).classList.remove('err');
    });
    ['currentErr','newErr','confirmErr'].forEach(id => {
        const el = document.getElementById(id);
        el.textContent = ''; el.classList.remove('show');
    });
    document.getElementById('cpSuccess').classList.remove('show');

    const current = document.getElementById('currentPassword').value;
    const newPwd  = document.getElementById('newPassword').value;
    const confirm = document.getElementById('confirmPassword').value;

    // Client-side validation
    let valid = true;
    if (!current) {
        showErr('currentPassword', 'currentErr', 'Please enter your current password');
        valid = false;
    }
    if (!newPwd) {
        showErr('newPassword', 'newErr', 'Please enter a new password');
        valid = false;
    } else if (newPwd.length < 8) {
        showErr('newPassword', 'newErr', 'Password must be at least 8 characters');
        valid = false;
    }
    if (!confirm) {
        showErr('confirmPassword', 'confirmErr', 'Please confirm your new password');
        valid = false;
    } else if (newPwd && newPwd !== confirm) {
        showErr('confirmPassword', 'confirmErr', 'Passwords do not match');
        valid = false;
    }
    if (!valid) return;

    const btn = document.getElementById('updateBtn');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner"></span> Updating...';

    const fd = new FormData();
    fd.append('ajax_change_password', '1');
    fd.append('current_password', current);
    fd.append('new_password',     newPwd);
    fd.append('confirm_password', confirm);

    fetch('change_password.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(data => {
        btn.disabled = false;
        btn.innerHTML = '🔒 Update Password';

        if (data.success) {
            // Clear all fields
            document.getElementById('currentPassword').value = '';
            document.getElementById('newPassword').value     = '';
            document.getElementById('confirmPassword').value = '';
            // Reset strength bar
            document.getElementById('strengthWrap').classList.remove('show');
            document.getElementById('strengthHint').classList.remove('show');
            // Show success
            document.getElementById('cpSuccess').classList.add('show');
            showToast('✅ Password updated successfully!', 's');
        } else {
            // Show error on relevant field
            const msg = data.message || 'Failed to update password';
            if (msg.toLowerCase().includes('current') || msg.toLowerCase().includes('incorrect')) {
                showErr('currentPassword', 'currentErr', msg);
            } else if (msg.toLowerCase().includes('match')) {
                showErr('confirmPassword', 'confirmErr', msg);
            } else {
                showErr('newPassword', 'newErr', msg);
            }
            showToast('❌ ' + msg, 'e');
        }
    })
    .catch(() => {
        btn.disabled = false;
        btn.innerHTML = '🔒 Update Password';
        showToast('❌ Network error — please try again', 'e');
    });
}

/* ── Toast ───────────────────────────────────────────────── */
function showToast(msg, t = 'i') {
    const w = document.getElementById('toastWrap');
    const d = document.createElement('div');
    d.className = 'toast t' + t;
    d.textContent = msg;
    w.appendChild(d);
    setTimeout(() => d.remove(), 3500);
}

/* ── Enter key support ───────────────────────────────────── */
document.addEventListener('keydown', e => {
    if (e.key === 'Enter' && ['currentPassword','newPassword','confirmPassword'].includes(e.target.id)) {
        doChangePassword();
    }
});
</script>

<?php layoutEnd(); ?>