<?php
// /elms/includes/whitelist.php
// Utilities for assessment re-submit whitelist (ELMS).

if (!function_exists('elms_pick_table')) {
  function elms_pick_table(mysqli $db, array $cands): ?string {
    foreach ($cands as $t) {
      $t = $db->real_escape_string($t);
      $rs = $db->query("SHOW TABLES LIKE '{$t}'");
      if ($rs && $rs->num_rows > 0) { $rs->free(); return $t; }
      if ($rs) $rs->free();
    }
    return null;
  }
}

if (!function_exists('elms_is_whitelisted')) {
  function elms_is_whitelisted(mysqli $db, int $assessment_id, int $student_id): bool {
    $tbl = elms_pick_table($db, ['lms_resubmit_whitelist','assessment_resubmit_whitelist','resubmit_whitelist']);
    if (!$tbl) return false;
    $assessment_id = (int)$assessment_id;
    $student_id    = (int)$student_id;
    $sql = "SELECT 1 FROM `{$tbl}` WHERE assessment_id={$assessment_id} AND student_id={$student_id} LIMIT 1";
    if ($rs = $db->query($sql)) { $ok = $rs->num_rows > 0; $rs->free(); return $ok; }
    return false;
  }
}

if (!function_exists('elms_consume_whitelist')) {
  // one-time pass → remove after successful submit
  function elms_consume_whitelist(mysqli $db, int $assessment_id, int $student_id): void {
    $tbl = elms_pick_table($db, ['lms_resubmit_whitelist','assessment_resubmit_whitelist','resubmit_whitelist']);
    if (!$tbl) return;
    $assessment_id = (int)$assessment_id;
    $student_id    = (int)$student_id;
    $db->query("DELETE FROM `{$tbl}` WHERE assessment_id={$assessment_id} AND student_id={$student_id} LIMIT 1");
  }
}

if (!function_exists('elms_whitelist_override')) {
  // Helper to apply whitelist on top of your normal rules:
  // returns [bool $allow_submit, bool $whitelist_used]
  function elms_whitelist_override(mysqli $db, int $assessment_id, int $student_id, bool $normal_rules_pass): array {
    if ($normal_rules_pass) return [true, false];
    if (elms_is_whitelisted($db, $assessment_id, $student_id)) return [true, true];
    return [false, false];
  }
}
