<?php
// Admin → Students (list) for studentss table
// Path: /elms/admin/students/index.php

declare(strict_types=1);
if (session_status() === PHP_SESSION_NONE) session_start();

/* ---------- auth ---------- */
$role = strtolower((string)($_SESSION['user']['role'] ?? $_SESSION['role'] ?? ''));
if (is_file(__DIR__ . '/../../includes/auth.php')) {
  require_once __DIR__ . '/../../includes/auth.php';
  if (function_exists('require_role')) require_role(['super_admin','branch_admin','admin']);
}
if (!in_array($role, ['super_admin','branch_admin','admin'], true)) {
  http_response_code(403); echo 'Forbidden'; exit;
}

/* ---------- utils ---------- */
function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }

/* ---------- DB bootstrap ---------- */
$ROOT = rtrim($_SERVER['DOCUMENT_ROOT'] ?? dirname(__DIR__,2), '/');
$tried=[]; $try=function(string $p)use(&$tried){ $tried[]=$p; if(is_file($p)){ require_once $p; return true; } return false; };
$try($ROOT.'/elms/includes/db.php') || $try(__DIR__.'/../../includes/db.php') || $try(__DIR__.'/../includes/db.php');
if (!isset($mysqli) || !($mysqli instanceof mysqli)) { if (isset($conn) && $conn instanceof mysqli) $mysqli=$conn; }
if (!isset($mysqli) || !($mysqli instanceof mysqli)) { http_response_code(500); echo "<h3>DB not initialized</h3><pre>".esc(implode("\n",$tried))."</pre>"; exit; }
@$mysqli->set_charset('utf8mb4');

/* ---------- helpers ---------- */
function columns(mysqli $db, string $t): array {
  $cols=[]; $t=$db->real_escape_string($t);
  if($rs=$db->query("SHOW COLUMNS FROM `$t`")){ while($r=$rs->fetch_assoc()) $cols[]=$r['Field']; }
  return $cols;
}

/* ---------- fixed table: studentss ---------- */
$STU_TBL = 'studentss';
$COLS = columns($mysqli,$STU_TBL);
$has = fn(string $c)=> in_array($c,$COLS,true);

/* ---------- column mappings (EMAIL + PASSWORD aware) ---------- */
$col_id          = $has('id') ? 'id' : null;
$col_center_no   = $has('center_reg_no') ? 'center_reg_no' : null;
$col_ref_no      = $has('reference_no') ? 'reference_no' : null;
$col_title       = $has('title') ? 'title' : null;
$col_fullname    = $has('full_name') ? 'full_name' : ($has('name') ? 'name' : null);

/* Email: academic_email → email → email_address */
$col_email_pref  = $has('academic_email') ? 'academic_email'
                 : ($has('email') ? 'email'
                 : ($has('email_address') ? 'email_address' : null));

/* NIC: nic_passport → nic */
$col_nic         = $has('nic_passport') ? 'nic_passport' : ($has('nic') ? 'nic' : null);

/* Password display (safe): academic_plain_password → password_plain → password → academic_password_hash */
$col_pwd = null;
foreach (['academic_plain_password','password_plain','password','academic_password_hash'] as $c) {
  if ($has($c)) { $col_pwd = $c; break; }
}

/* ---------- inputs ---------- */
$q       = trim((string)($_GET['q'] ?? ''));
$page    = max(1,(int)($_GET['page'] ?? 1));
$perPage = 25;
$offset  = ($page-1)*$perPage;

/* ---------- SELECT list ---------- */
$select = [];
$select[] = $col_id        ? "s.`$col_id` AS id"                     : "NULL AS id";
$select[] = $col_center_no ? "s.`$col_center_no` AS center_reg_no"   : "'' AS center_reg_no";
$select[] = $col_ref_no    ? "s.`$col_ref_no` AS reference_no"       : "'' AS reference_no";
$select[] = $col_title     ? "s.`$col_title` AS title"               : "'' AS title";
$select[] = $col_fullname  ? "s.`$col_fullname` AS full_name"        : "'' AS full_name";
$select[] = $col_email_pref? "s.`$col_email_pref` AS email_address"  : "'' AS email_address";
$select[] = $col_nic       ? "s.`$col_nic` AS nic_passport"          : "'' AS nic_passport";
$select[] = $col_pwd       ? "s.`$col_pwd` AS pwd"                   : "'' AS pwd";

/* ---------- WHERE (search across key fields) ---------- */
$where=["1=1"]; $types=''; $vals=[];
if ($q!==''){
  $parts=[];
  foreach ([$col_center_no,$col_ref_no,$col_fullname,$col_email_pref,$col_nic,$col_title] as $c){
    if ($c){ $parts[]="s.`$c` LIKE CONCAT('%',?,'%')"; $types.='s'; $vals[]=$q; }
  }
  if ($parts) $where[]='('.implode(' OR ',$parts).')';
}

/* ---------- COUNT ---------- */
$total=0; $sqlCount="SELECT COUNT(*) AS c FROM `$STU_TBL` s WHERE ".implode(' AND ',$where);
if ($stc=$mysqli->prepare($sqlCount)){
  if ($types!=='') $stc->bind_param($types, ...$vals);
  $stc->execute();
  if ($res=$stc->get_result()) $total = (int)($res->fetch_assoc()['c'] ?? 0);
  $stc->close();
}
$pages=max(1,(int)ceil($total/$perPage));

/* ---------- DATA ---------- */
$sql="SELECT ".implode(',',$select)." FROM `$STU_TBL` s WHERE ".implode(' AND ',$where)." ORDER BY id DESC LIMIT ?,?";
$stm=$mysqli->prepare($sql);
if ($types===''){ $stm->bind_param('ii',$offset,$perPage); }
else{ $typesAll=$types.'ii'; $bind=array_merge($vals,[$offset,$perPage]); $stm->bind_param($typesAll, ...$bind); }
$stm->execute();
$rows = ($r=$stm->get_result()) ? $r->fetch_all(MYSQLI_ASSOC) : [];
$stm->close();

/* ---------- layout ---------- */
$cTop=[__DIR__.'/../../includes/admin_layout_top.php', __DIR__.'/../../includes/layout_admin_top.php'];
$cBot=[__DIR__.'/../../includes/admin_layout_bottom.php', __DIR__.'/../../includes/layout_admin_bottom.php'];
$LAY_TOP=null; foreach($cTop as $f){ if(is_file($f)){ $LAY_TOP=$f; break; } }
$LAY_BOT=null; foreach($cBot as $f){ if(is_file($f)){ $LAY_BOT=$f; break; } }
$PAGE_TITLE='Students'; $ACTIVE_MENU='students';

if($LAY_TOP){ require $LAY_TOP; } else { ?>
<!doctype html>
<meta charset="utf-8"><title>Students</title>
<style>
body{font:14px/1.5 system-ui,Segoe UI,Arial;margin:20px}
.row{display:flex;gap:8px;flex-wrap:wrap;margin:0 0 12px}
.form-control{padding:8px 10px;border:1px solid #e5e7eb;border-radius:8px;min-width:260px}
.btn{padding:8px 12px;border-radius:8px;border:1px solid #d1d5db;background:#111827;color:#fff;text-decoration:none}
.btn-outline{background:#fff;color:#111;border-color:#d1d5db}
.card{border:1px solid #e5e7eb;border-radius:12px}
.card-body{padding:12px}
table{border-collapse:collapse;width:100%}
th,td{border:1px solid #e5e7eb;padding:8px}
th{background:#f3f4f6;text-align:left}
.text-muted{color:#6b7280}.text-center{text-align:center}
.d-flex{display:flex;justify-content:space-between;align-items:center}
.pagination{list-style:none;display:flex;gap:6px;padding:0;margin:0}
.page-link{display:block;padding:6px 10px;border:1px solid #e5e7eb;border-radius:8px;text-decoration:none;color:#111}
.page-item.disabled .page-link{opacity:.5;pointer-events:none}
</style>
<div class="container">
<?php } ?>

<h1 style="margin:0 0 12px">Students</h1>

<form class="row" method="get">
  <input class="form-control" name="q" value="<?= esc($q) ?>" placeholder="Search (center reg, reference no, name, email, NIC, title)…">
  <button class="btn">Search</button>
  <a class="btn btn-outline" href="./">Reset</a>
</form>

<div class="card">
  <div class="card-body">
    <div class="table-responsive">
      <table class="table">
        <thead>
          <tr>
            <th style="width:80px">ID</th>
            <th>Center Reg No</th>
            <th>Reference No</th>
            <th>Title</th>
            <th>Full Name</th>
            <th>Email Address</th>
            <th>NIC/Passport</th>
            <th>Password</th>
          </tr>
        </thead>
        <tbody>
        <?php if (!$rows): ?>
          <tr><td colspan="8" class="text-muted text-center">No students found.</td></tr>
        <?php else: foreach($rows as $r): ?>
          <tr>
            <td><?= esc((string)($r['id'] ?? '')) ?></td>
            <td><?= esc((string)($r['center_reg_no'] ?? '')) ?></td>
            <td><?= esc((string)($r['reference_no'] ?? '')) ?></td>
            <td><?= esc((string)($r['title'] ?? '')) ?></td>
            <td><?= esc((string)($r['full_name'] ?? '')) ?></td>
            <td>
              <?php
                $em=(string)($r['email_address'] ?? '');
                echo $em!=='' ? '<a href="mailto:'.esc($em).'">'.esc($em).'</a>' : '—';
              ?>
            </td>
            <td><?= esc((string)($r['nic_passport'] ?? '')) ?></td>
            <td>
              <?php
                $ph = (string)($r['pwd'] ?? '');
                if ($ph === '' || $ph === null) {
                  echo '—';
                } elseif (preg_match('/^\\$2y\\$/', $ph) || preg_match('/^{argon2/i', $ph)) {
                  // Stored as hash (bcrypt/argon2) → never reveal
                  echo '•••• (hash)';
                } else {
                  // Looks like a plain/temporary password → mask
                  $short = strlen($ph) > 10 ? substr($ph, 0, 7).'…' : $ph;
                  echo '<span title="Stored value (masked)">'.esc($short).'</span>';
                }
              ?>
            </td>
          </tr>
        <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>

    <div class="d-flex" style="margin-top:10px">
      <div class="text-muted"><?= (int)$total ?> record<?= $total===1?'':'s' ?> · page <?= (int)$page ?> / <?= (int)$pages ?></div>
      <?php if ($pages>1):
        $qs=$_GET; unset($qs['page']); $mk=function($p)use($qs){ return '?'.http_build_query($qs+['page'=>$p]); };
      ?>
        <ul class="pagination">
          <li class="page-item <?= $page<=1?'disabled':'' ?>"><a class="page-link" href="<?= $mk(max(1,$page-1)) ?>">Prev</a></li>
          <li class="page-item disabled"><span class="page-link"><?= (int)$page ?></span></li>
          <li class="page-item <?= $page>=$pages?'disabled':'' ?>"><a class="page-link" href="<?= $mk(min($pages,$page+1)) ?>">Next</a></li>
        </ul>
      <?php endif; ?>
    </div>
  </div>
</div>

<?php if($LAY_BOT){ require $LAY_BOT; } else { echo "</div>"; }
