<?php
require_once __DIR__.'/../includes/db.php';
require_once __DIR__.'/../includes/auth.php';
require_once __DIR__.'/../includes/helpers.php';
require_login();
$page_title = "Change Password";

$ok = $err = '';

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

  if (strlen($new1) < 6 || $new1 !== $new2) {
    $err = 'New password must be 6+ characters and both match.';
  } else {
    $st = $pdo->prepare("SELECT password_hash FROM users WHERE id = :id");
    $st->execute([':id'=>$_SESSION['uid']]);
    $row = $st->fetch();

    if (!$row || !password_verify($current, $row['password_hash'])) {
      $err = 'Current password is incorrect.';
    } else {
      $newHash = password_hash($new1, PASSWORD_DEFAULT);
      $upd = $pdo->prepare("UPDATE users SET password_hash = :p WHERE id = :id");
      $upd->execute([':p'=>$newHash, ':id'=>$_SESSION['uid']]);
      $ok = 'Password changed.';
    }
  }
}

include __DIR__.'/../includes/header.php';
?>

<div class="row g-4">
  <div class="col-md-3"><?php include __DIR__.'/../includes/sidebar.php'; ?></div>
  <div class="col-md-9">
    <div class="card shadow-sm">
      <div class="card-body">
        <h5 class="card-title mb-3">Change Password</h5>

        <?php if($ok): ?><div class="alert alert-success"><?= sanitize($ok) ?></div><?php endif; ?>
        <?php if($err): ?><div class="alert alert-danger"><?= sanitize($err) ?></div><?php endif; ?>

        <form method="post" class="row g-3" autocomplete="off">
          <div class="col-12">
            <label class="form-label">Current password</label>
            <input name="current" type="password" class="form-control" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">New password (min 6)</label>
            <input name="new1" type="password" class="form-control" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Confirm new password</label>
            <input name="new2" type="password" class="form-control" required>
          </div>
          <div class="col-12">
            <button class="btn btn-dark">Update password</button>
            <a href="settings.php" class="btn btn-outline-secondary ms-2">Back to settings</a>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<?php include __DIR__.'/../includes/footer.php'; ?>
