<?php
declare(strict_types=1);
$DEBUG = isset($_GET['debug']) && $_GET['debug'] === '1';
@ini_set('display_errors', $DEBUG ? '1' : '0');
@ini_set('display_startup_errors', $DEBUG ? '1' : '0');
require_once __DIR__ . '/../includes/auth.php'; // includes ec_session_start()


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

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = null;
if (function_exists('ec_db')) $db = ec_db();
if (!$db instanceof mysqli) {
  $inc = __DIR__ . '/../includes/db.php';
  if (is_file($inc)) { require_once $inc; foreach (['conn','con','mysqli','db','link'] as $v) if (isset($$v) && $$v instanceof mysqli) { $db=$$v; break; } }
}
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=[];
if ($rs=$db->query("SELECT id, COALESCE(type, req_type) AS typ, COALESCE(student_id, ref_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")) {
  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>
