<?php
// admin-wait-approval.php
session_start();
if (!isset($_GET['pending_id'])) { header('Location: login.html'); exit; }
$pendingId = intval($_GET['pending_id']);
?>
<!doctype html>
<html>
<head><meta charset="utf-8"><title>Waiting for approval</title></head>
<body>
  <h2>Waiting for approval from another admin…</h2>
  <p>Your admin login request has been sent. Another authorized admin must approve this login.</p>
  <p id="status">Status: pending</p>

<script>
const pendingId = <?= json_encode($pendingId) ?>;

function checkStatus(){
  fetch('poll_admin_login_status.php?pending_id=' + pendingId)
    .then(r=>r.json()).then(data=>{
      document.getElementById('status').innerText = 'Status: ' + data.status;
      if (data.status === 'approved') {
        // finalize (send token to finalize endpoint)
        fetch('finalize_admin_login.php', {
          method: 'POST',
          headers: {'Content-Type':'application/json'},
          body: JSON.stringify({ pending_id: pendingId, token: data.token })
        }).then(r=>r.json()).then(res=>{
          if (res.success) {
            window.location = 'admin-dashboard.php';
          } else {
            document.getElementById('status').innerText = 'Finalize failed: ' + res.message;
          }
        });
      } else if (data.status === 'denied') {
        document.getElementById('status').innerText = 'Your request was denied.';
      } else {
        // still pending
        setTimeout(checkStatus, 3000);
      }
    }).catch(err=>{
      setTimeout(checkStatus, 5000);
    });
}

checkStatus();
</script>
</body>
</html>
