<?php
session_start();
require_once __DIR__ . '/db.php';

// Auth admin
if (!isset($_SESSION['user']) || (($_SESSION['user']['role'] ?? '') !== 'admin')) {
  header("Location: dashboard.php"); exit;
}

// CSRF
if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(16)); }
$CSRF = $_SESSION['csrf_token'];

// Ambil list pending
$stmt = $conn->prepare("
  SELECT r.*, m.full_name
  FROM password_reset_requests r
  LEFT JOIN members m ON m.id = r.member_id
  WHERE r.status='pending'
  ORDER BY r.requested_at DESC
");
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

?><!DOCTYPE html>
<html lang="ms">
<head>
<meta charset="UTF-8">
<title>Password Reset Requests</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
  body{font-family:Arial,sans-serif; padding:20px; background:#f6f7fb}
  h1{margin:0 0 16px}
  table{width:100%; border-collapse:collapse; background:#fff; border-radius:12px; overflow:hidden}
  th,td{padding:12px; border-bottom:1px solid #eee; text-align:left}
  th{background:#fafafa}
  .actions button{padding:6px 10px; border:0; border-radius:8px; cursor:pointer}
  .btn-reset{background:#16a34a; color:#fff}
  .btn-reject{background:#dc2626; color:#fff}
  .note{font-size:12px; color:#666}
</style>
</head>
<body>
  <h1>🔐 Password Reset Requests</h1>

  <table>
    <thead>
      <tr>
        <th>Tarikh Permintaan</th>
        <th>Nama</th>
        <th>Staf</th>
        <th>Emel</th>
        <th>IC(4)</th>
        <th>Telefon</th>
        <th>Tindakan</th>
      </tr>
    </thead>
    <tbody>
      <?php if (!$rows): ?>
        <tr><td colspan="7" class="note" style="text-align:center">Tiada rekod.</td></tr>
      <?php else: foreach($rows as $r): ?>
        <tr>
          <td><?= htmlspecialchars($r['requested_at']) ?></td>
          <td><?= htmlspecialchars($r['full_name'] ?: '-') ?></td>
          <td><?= htmlspecialchars($r['staff_number']) ?></td>
          <td><?= htmlspecialchars($r['email']) ?></td>
          <td><?= htmlspecialchars($r['ic_last4']) ?></td>
          <td><?= htmlspecialchars($r['phone'] ?: '-') ?></td>
          <td class="actions">
            <form method="post" action="admin-password-reset.php" style="display:inline">
              <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($CSRF) ?>">
              <input type="hidden" name="request_id" value="<?= (int)$r['id'] ?>">
              <button class="btn-reset" type="submit">Reset & Tetapkan</button>
            </form>
            <form method="post" action="admin-password-reject.php" style="display:inline">
              <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($CSRF) ?>">
              <input type="hidden" name="request_id" value="<?= (int)$r['id'] ?>">
              <button class="btn-reject" type="submit">Tolak</button>
            </form>
          </td>
        </tr>
      <?php endforeach; endif; ?>
    </tbody>
  </table>

<?php if (!empty($_SESSION['temp_password'])):
  $tmp = $_SESSION['temp_password'];
  $who = $_SESSION['temp_password_for'] ?? '';
  unset($_SESSION['temp_password'], $_SESSION['temp_password_for']); // sekali guna
?>
<script>
  const tmpPass = <?= json_encode($tmp) ?>;
  const who     = <?= json_encode($who) ?>;
  Swal.fire({
    title: 'Kata laluan sementara',
    html: `
      <div style="text-align:left">
        ${who ? `<div style="font-size:13px;margin-bottom:6px;color:#555">Untuk: <b>${who}</b></div>` : ``}
        <div style="font-size:13px;margin-bottom:10px;color:#555">Sila salin dan serahkan melalui saluran rasmi.</div>
        <div style="display:flex;gap:8px;align-items:center;margin:10px 0">
          <input id="tmpPassInput" type="text" value="${tmpPass}" readonly
                 style="flex:1;padding:10px;border:1px solid #ddd;border-radius:8px">
          <button id="copyBtn" class="swal2-confirm swal2-styled">Copy</button>
        </div>
        <label style="font-size:12px"><input type="checkbox" id="maskToggle"> Sembunyikan</label>
      </div>
    `,
    showConfirmButton: true,
    confirmButtonText: 'Tutup',
    allowOutsideClick: false,
    allowEscapeKey: false,
    didOpen: () => {
      const inp = document.getElementById('tmpPassInput');
      const btn = document.getElementById('copyBtn');
      const tog = document.getElementById('maskToggle');
      inp.focus(); inp.select();
      btn.addEventListener('click', async () => {
        try { await navigator.clipboard.writeText(inp.value); btn.textContent='Disalin'; }
        catch(e){ inp.select(); document.execCommand('copy'); btn.textContent='Disalin'; }
      });
      tog.addEventListener('change', e => { inp.type = e.target.checked ? 'password' : 'text'; });
    }
  });
</script>
<?php endif; ?>
</body>
</html>
