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

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

$msg = '';
$users = $conn->query("SELECT id, full_name, account_number FROM users ORDER BY id DESC");

if (is_post()) {

  $userId = (int)$_POST['user_id'];

  $tempPin = random_int(1000, 9999);
  $hash = password_hash((string)$tempPin, PASSWORD_DEFAULT);

  $st = $conn->prepare("
    UPDATE users
    SET pin_hash=?, pin_temp=1
    WHERE id=?
  ");
  $st->bind_param("si", $hash, $userId);
  $st->execute();

  $msg = "Temporary PIN for user ID {$userId}: {$tempPin}";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Reset PIN | Admin</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body class="bg-light">

<div class="container py-4">

  <h4 class="fw-bold mb-3">Admin – Reset Customer PIN</h4>

  <?php if ($msg): ?>
    <div class="alert alert-success fw-bold"><?= e($msg) ?></div>
  <?php endif; ?>

  <div class="card p-4" style="max-width:520px">
    <form method="post">
      <label>Select Customer</label>
      <select name="user_id" class="form-select mb-3" required>
        <?php while ($u = $users->fetch_assoc()): ?>
          <option value="<?= $u['id'] ?>">
            <?= e($u['full_name']) ?> — <?= e($u['account_number']) ?>
          </option>
        <?php endwhile; ?>
      </select>

      <button class="btn btn-danger w-100 fw-bold">
        Generate Temporary PIN
      </button>
    </form>
  </div>

</div>

</body>
</html>
