<?php
require_once(__DIR__ . "/includes/auth.php");

$first = !empty($_GET['first']) || $__must_reset;
$error = $success = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $cur     = $_POST['current_password'] ?? '';
    $new     = $_POST['new_password'] ?? '';
    $confirm = $_POST['confirm_password'] ?? '';
    try {
        if (!$first) {
            $p = $conn->prepare("SELECT password FROM users WHERE id=?");
            $p->bind_param("i", $__staff_id); $p->execute();
            $hash = $p->get_result()->fetch_assoc()['password'] ?? '';
            if (!$cur) throw new Exception("Enter your current password.");
            if (!password_verify($cur, $hash)) throw new Exception("Current password is incorrect.");
        }
        if (!preg_match('/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$/', $new)) throw new Exception("Password must be at least 8 characters and include an uppercase letter, a lowercase letter, a number, and a special character.");
        if ($new !== $confirm) throw new Exception("Passwords do not match.");

        $nh = password_hash($new, PASSWORD_DEFAULT);
        $u = $conn->prepare("UPDATE users SET password=? WHERE id=?");
        $u->bind_param("si", $nh, $__staff_id); $u->execute();
        // clear forced-reset flag if the column exists
        if ($r = $conn->prepare("UPDATE users SET must_reset_pw=0 WHERE id=?")) { $r->bind_param("i", $__staff_id); $r->execute(); }

        $_SESSION['staff_flash'] = "Password updated successfully.";
        header("Location: index.php"); exit;
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

$page_title = $first ? 'Create New Password' : 'Change Password';
$active_nav = 'settings';
include("includes/header.php");
?>
<style>
.cpw-card{background:#fff;border:1px solid var(--border);border-radius:18px;box-shadow:0 4px 18px rgba(15,23,42,.06);padding:22px 18px}
.cpw-hero{text-align:center;margin-bottom:18px}
.cpw-hero .ic{width:60px;height:60px;border-radius:17px;background:var(--primary-bg);color:var(--primary);display:flex;align-items:center;justify-content:center;margin:0 auto 12px}
.cpw-hero h2{font-size:1.2rem;font-weight:800;letter-spacing:-.02em}
.cpw-hero p{font-size:.84rem;color:var(--text-muted);margin-top:4px;line-height:1.5}
.f-label{display:block;font-size:.84rem;font-weight:700;margin-bottom:8px}
.field{position:relative;margin-bottom:16px}
.field input{width:100%;height:52px;border:1.5px solid var(--border);background:#F7F9FC;border-radius:12px;padding:0 48px 0 14px;font-size:max(16px,.95rem);font-family:var(--font);outline:none}
.field input:focus{border-color:var(--primary);background:#fff;box-shadow:0 0 0 3px rgba(34,90,227,.1)}
.field .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}
.btn-primary{width:100%;height:54px;border:none;border-radius:14px;background:var(--primary);color:#fff;font-weight:700;font-size:1rem;cursor:pointer;box-shadow:0 8px 22px rgba(34,90,227,.3)}
.btn-primary:active{background:var(--primary-dark)}
.sub-back{display:flex;align-items:center;gap:10px;margin-bottom:14px;color:var(--text);font-weight:700}
.sub-back .b{width:34px;height:34px;border-radius:50%;background:var(--primary-bg);color:var(--primary);display:flex;align-items:center;justify-content:center}
</style>

<?php if (!$first): ?>
<a href="settings.php" class="sub-back"><span class="b"><svg width="17" height="17" 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></span>Change Password</a>
<?php endif; ?>

<div class="cpw-card">
  <div class="cpw-hero">
    <div class="ic"><svg width="26" height="26" 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>
    <h2><?php echo $first ? 'Create New Password' : 'Change Password'; ?></h2>
    <p><?php echo $first ? 'Set a new password to secure your account before you continue.' : 'Use a strong password you don\'t reuse elsewhere.'; ?></p>
  </div>

  <?php if ($error): ?><div class="banner err"><?php echo htmlspecialchars($error); ?></div><?php endif; ?>

  <form method="POST" id="cpwForm" autocomplete="off">
    <?php if (!$first): ?>
    <label class="f-label">Current Password</label>
    <div class="field"><input type="password" name="current_password" id="cur" placeholder="Enter current password" required><button type="button" class="eye" data-t="cur" aria-label="Show"></button></div>
    <?php endif; ?>

    <label class="f-label">New Password</label>
    <div class="field"><input type="password" name="new_password" id="np" placeholder="Min. 8 characters" minlength="8" data-pwmeter required><button type="button" class="eye" data-t="np" aria-label="Show"></button></div>

    <label class="f-label">Confirm Password</label>
    <div class="field"><input type="password" name="confirm_password" id="cp" placeholder="Re-enter new password" minlength="8" required><button type="button" class="eye" data-t="cp" aria-label="Show"></button></div>

    <button type="submit" class="btn-primary">Continue</button>
  </form>
</div>

<script>
(function(){
  const open='<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 off='<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('.eye').forEach(b=>{b.innerHTML=open;b.addEventListener('click',()=>{const i=document.getElementById(b.dataset.t);const s=i.type==='password';i.type=s?'text':'password';b.innerHTML=s?off:open;});});
})();
</script>

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