<?php
// /edenrms/pages/approvals_delete_list.php
declare(strict_types=1);
require_once __DIR__ . '/../includes/auth.php';
if (function_exists('ec_session_start')) ec_session_start();

$role = function_exists('ec_role') ? strtolower((string)ec_role()) : '';
$can  = in_array($role, ['admin','super_admin'], true) || (function_exists('ec_can') && ec_can('students.manage'));
if (!$can) { http_response_code(403); echo '<div class="p-3 text-danger">Unauthorized</div>'; exit; }

$db = function_exists('ec_db') ? ec_db() : null;
if (!$db instanceof mysqli) { echo '<div class="p-3 text-danger">DB not configured</div>'; exit; }
$db->set_charset('utf8mb4');

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }

$rows=[];
$rs=$db->query(
  "SELECT id,
          COALESCE(type, req_type) AS typ,
          COALESCE(student_id, ref_id, sid, entity_id) AS sid,
          status, requested_at
   FROM approval_requests
   WHERE LOWER(COALESCE(type,req_type,''))='delete_student'
     AND LOWER(status)='pending'
   ORDER BY requested_at DESC
   LIMIT 200"
);

if ($rs){ while($r=$rs->fetch_assoc()) $rows[]=$r; $rs->close(); }
?>
<div class="table-responsive">
  <table class="table table-sm mb-0">
    <thead><tr><th>ID</th><th>Student ID</th><th>Requested At</th><th class="text-end">Action</th></tr></thead>
    <tbody>
    <?php if(!$rows): ?>
      <tr><td colspan="4" class="text-muted text-center py-3">No pending delete requests.</td></tr>
    <?php else: foreach($rows as $r): ?>
      <tr data-req-id="<?= (int)$r['id'] ?>">
        <td>#<?= (int)$r['id'] ?></td>
        <td><?= (int)$r['sid'] ?></td>
        <td><?= h($r['requested_at']) ?></td>
        <td class="text-end">
          <input type="text" class="form-control form-control-sm d-inline-block js-approval-note" style="width:220px" placeholder="Note (optional)">
          <button class="btn btn-success btn-sm js-approve" data-id="<?= (int)$r['id'] ?>">Approve</button>
          <button class="btn btn-outline-danger btn-sm js-reject" data-id="<?= (int)$r['id'] ?>">Reject</button>
        </td>
      </tr>
    <?php endforeach; endif; ?>
    </tbody>
  </table>
</div>
