<?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';
require_admin($conn);

$userId = (int)($_GET['id'] ?? 0);
if (!$userId) redirect('customers.php');

if (is_post()) {
  csrf_verify();

  $new = $_POST['password'] ?? '';
  if (strlen($new) < 8) {
    flash('err','Password too short');
    redirect("?id=$userId");
  }

  $hash = password_hash($new, PASSWORD_BCRYPT);
  $st = $conn->prepare("UPDATE users SET password=? WHERE id=?");
  $st->bind_param("si", $hash, $userId);
  $st->execute();

  flash('msg','Password reset successfully');
  redirect("?id=$userId");
}

include __DIR__ . '/../../views/partials/head.php';
include __DIR__ . '/../../views/partials/admin_sidebar.php';
?>

<div class="container py-4">
  <?php if($m=flash('msg')): ?><div class="alert alert-success"><?= e($m) ?></div><?php endif; ?>

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

    <form method="post">
      <?= csrf_field() ?>
      <input type="password" name="password" class="form-control mb-3" placeholder="New password" required>
      <button class="btn btn-danger w-100">Reset Password</button>
    </form>
  </div>
</div>
