<?php
require_once "auth.php";                 // role guard + staff lock + audit()
require_once "../includes/db.php";

$msg = "";
if ($_SERVER['REQUEST_METHOD']==='POST') {
  $current = trim($_POST['current'] ?? '');
  $new1    = trim($_POST['new1'] ?? '');
  $new2    = trim($_POST['new2'] ?? '');

  if ($current === '' || $new1 === '' || $new2 === '') {
    $msg = "<div class='alert alert-danger'>All fields are required.</div>";
  } elseif ($new1 !== $new2) {
    $msg = "<div class='alert alert-danger'>New passwords do not match.</div>";
  } elseif (strlen($new1) < 8) {
    $msg = "<div class='alert alert-danger'>New password must be at least 8 characters.</div>";
  } else {
    $id = (int)($_SESSION['admin_id'] ?? 0);
    $st = $conn->prepare("SELECT password FROM admins WHERE id=? LIMIT 1");
    $st->bind_param("i",$id); $st->execute();
    $hash = ($st->get_result()->fetch_assoc())['password'] ?? '';
    if (!$hash || !password_verify($current, $hash)) {
      $msg = "<div class='alert alert-danger'>Current password is incorrect.</div>";
    } else {
      $newHash = password_hash($new1, PASSWORD_DEFAULT);
      $up = $conn->prepare("UPDATE admins SET password=?, updated_at=NOW() WHERE id=?");
      $up->bind_param("si", $newHash, $id);
      if ($up->execute()) {
        $msg = "<div class='alert alert-success'>Password updated successfully.</div>";
        audit($conn, 'password_change', 'admins', $id, ['who'=>$_SESSION['admin'],'result'=>'success']);
      } else {
        $msg = "<div class='alert alert-danger'>Update failed. Please try again.</div>";
      }
    }
  }
}
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Change Password • Eden Campus</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="../assets/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-4" style="max-width:560px">
  <h4 class="mb-3">Change Password</h4>
  <?= $msg ?>
  <form method="post" class="card p-3">
    <div class="mb-3">
      <label class="form-label">Current Password</label>
      <input type="password" name="current" class="form-control" required>
    </div>
    <div class="mb-3">
      <label class="form-label">New Password</label>
      <input type="password" name="new1" class="form-control" required minlength="8">
      <div class="form-text">Min 8 characters.</div>
    </div>
    <div class="mb-3">
      <label class="form-label">Confirm New Password</label>
      <input type="password" name="new2" class="form-control" required minlength="8">
    </div>
    <div class="d-flex gap-2">
      <button class="btn btn-primary">Update</button>
      <a href="dashboard.php" class="btn btn-outline-secondary">Back</a>
    </div>
  </form>
</div>
</body>
</html>
