<?php
require_once __DIR__ . '/../../app/helpers/functions.php';
require_once __DIR__ . '/../../app/helpers/csrf.php';
require_once __DIR__ . '/../../app/middleware/auth.php';

session_boot();
require_login();
$conn = require __DIR__ . '/../../app/config/database.php';
$u = current_user();

if (is_post()) {
  csrf_verify();

  $current = $_POST['current_password'] ?? '';
  $new     = $_POST['new_password'] ?? '';
  $confirm = $_POST['confirm_password'] ?? '';

  if ($new !== $confirm) {
    flash('err','Passwords do not match');
    redirect('change_password.php');
  }

  if (strlen($new) < 8) {
    flash('err','Password must be at least 8 characters');
    redirect('change_password.php');
  }

  // Verify old password
  if (!password_verify($current, $u['password'])) {
    flash('err','Current password is incorrect');
    redirect('change_password.php');
  }

  $hash = password_hash($new, PASSWORD_BCRYPT);

  $st = $conn->prepare("UPDATE users SET password=? WHERE id=?");
  $st->bind_param("si", $hash, $u['id']);
  $st->execute();

  flash('msg','Password changed successfully');
  redirect('change_password.php');
}

$title = 'Change Password';
include __DIR__ . '/../../views/partials/head.php';
include __DIR__ . '/../../views/partials/customer_sidebar.php';
?>

<div class="container py-4" style="margin-left:240px">
  <?php if($m=flash('msg')): ?><div class="alert alert-success"><?= e($m) ?></div><?php endif; ?>
  <?php if($m=flash('err')): ?><div class="alert alert-danger"><?= e($m) ?></div><?php endif; ?>

  <div class="card ab-card p-4" style="max-width:420px">
    <h5 class="fw-bold mb-3">Change Password</h5>

    <form method="post">
      <?= csrf_field() ?>

      <input type="password" name="current_password" class="form-control mb-2" placeholder="Current password" required>
      <input type="password" name="new_password" class="form-control mb-2" placeholder="New password" required>
      <input type="password" name="confirm_password" class="form-control mb-3" placeholder="Confirm new password" required>

      <button class="btn ab-btn text-white w-100">Update Password</button>
    </form>
  </div>
</div>
