<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once __DIR__ . '/../../includes/auth.php';
require_role(['super_admin','branch_admin']);

require_once __DIR__ . '/../../includes/helpers.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/scope.php';

$PAGE_TITLE  = 'Lecturers';
$ACTIVE_MENU = 'lecturers';

/* ---------- pick source table ---------- */
$TBL = null;
foreach (['lecturers','teachers','staff','users'] as $t) {
  if (table_exists_local($t)) { $TBL = $t; break; }
}
if (!$TBL) die('<div style="padding:20px;font:14px system-ui">No lecturers/teachers/staff/users table found.</div>');

/* role filter (only for users-like tables) */
$roleCol = null;
foreach (['role','user_role','type','user_type'] as $c) {
  if (column_exists_local($TBL,$c)) { $roleCol = $c; break; }
}
$roleWhere = '';
if ($TBL === 'users' && $roleCol) { $roleWhere = " AND $roleCol='lecturer'"; }

/* label (name) resolution */
$labelExpr = null;
if (column_exists_local($TBL,'name'))        $labelExpr = 'name';
elseif (column_exists_local($TBL,'full_name')) $labelExpr = 'full_name';
elseif (column_exists_local($TBL,'first_name') && column_exists_local($TBL,'last_name')) $labelExpr = "CONCAT(first_name,' ',last_name)";
else $labelExpr = 'id';

$hasEmail = column_exists_local($TBL,'email');
$hasPhone = column_exists_local($TBL,'phone') || column_exists_local($TBL,'phone_no');
$phoneCol = column_exists_local($TBL,'phone') ? 'phone' : (column_exists_local($TBL,'phone_no') ? 'phone_no' : null);

$codeCol = null;
foreach (['code','staff_id','employee_id'] as $c) if (column_exists_local($TBL,$c)) { $codeCol=$c; break; }

$statusCol = null;
foreach (['status','active','is_active'] as $c) if (column_exists_local($TBL,$c)) { $statusCol=$c; break; }

/* search */
$q = trim($_GET['q'] ?? '');
$where = "WHERE 1=1$roleWhere";
$types=''; $vals=[];
if ($q !== '') {
  $where .= " AND ($labelExpr LIKE ?" . ($hasEmail ? " OR email LIKE ?" : "") . ")";
  $types .= 's'; $vals[]="%$q%";
  if ($hasEmail) { $types.='s'; $vals[]="%$q%"; }
}

/* query */
$cols = "id, $labelExpr AS label";
if ($codeCol)  $cols .= ", $codeCol AS code";
if ($hasEmail) $cols .= ", email";
if ($phoneCol) $cols .= ", $phoneCol AS phone";
if ($statusCol)$cols .= ", $statusCol AS status_raw";

$sql = "SELECT $cols FROM $TBL $where ORDER BY label";
$st  = $mysqli->prepare($sql);
if ($types) $st->bind_param($types, ...$vals);
$st->execute();
$rows = $st->get_result()->fetch_all(MYSQLI_ASSOC);

/* layout open */
$__layoutOpened=false;
foreach(['admin_layout_top.php','layout_top.php','admin_header.php','header_admin.php'] as $f){
  $p=__DIR__.'/../../includes/'.$f; if(is_file($p)){require_once $p; $__layoutOpened=true; break;}
}
if(!$__layoutOpened) echo '<div class="container-fluid p-3">';
?>
<div class="d-flex align-items-center justify-content-between mb-3">
  <h1 class="h5 m-0">Lecturers</h1>
  <a href="edit.php" class="btn btn-primary btn-sm">+ New Lecturer</a>
</div>

<form class="row g-2 mb-3" method="get">
  <div class="col-auto">
    <input type="text" name="q" value="<?= esc($q) ?>" class="form-control form-control-sm" placeholder="Search name or email">
  </div>
  <div class="col-auto">
    <button class="btn btn-outline-secondary btn-sm">Search</button>
    <a class="btn btn-link btn-sm" href="index.php">Reset</a>
  </div>
</form>

<div class="card">
  <div class="card-body">
    <div class="table-responsive">
      <table class="table table-hover align-middle">
        <thead class="small">
          <tr>
            <th style="width:32%">Name</th>
            <?php if ($codeCol):  ?><th>Code</th><?php endif; ?>
            <?php if ($hasEmail): ?><th>Email</th><?php endif; ?>
            <?php if ($phoneCol): ?><th>Phone</th><?php endif; ?>
            <?php if ($statusCol):?><th>Status</th><?php endif; ?>
            <th style="width:140px"></th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$rows): ?>
            <tr><td colspan="6" class="text-center text-muted">No lecturers found.</td></tr>
          <?php else: foreach ($rows as $r):
            $statusText = '';
            if ($statusCol) {
              $val = $r['status_raw'];
              if ($statusCol==='status')        $statusText = (string)$val;
              elseif ($statusCol==='active' || $statusCol==='is_active') $statusText = ((int)$val===1?'Active':'Inactive');
            } ?>
            <tr>
              <td class="fw-semibold"><?= esc($r['label']) ?></td>
              <?php if ($codeCol):  ?><td><?= esc($r['code'] ?? '') ?></td><?php endif; ?>
              <?php if ($hasEmail): ?><td><?= esc($r['email'] ?? '') ?></td><?php endif; ?>
              <?php if ($phoneCol): ?><td><?= esc($r['phone'] ?? '') ?></td><?php endif; ?>
              <?php if ($statusCol):?>
                <td>
                  <span class="badge <?= ($statusText==='Active')?'bg-success':(($statusText==='Inactive')?'bg-secondary':'bg-light text-dark') ?>">
                    <?= esc($statusText ?: '-') ?>
                  </span>
                </td>
              <?php endif; ?>
              <td class="text-end">
                <a href="edit.php?id=<?= (int)$r['id'] ?>" class="btn btn-sm btn-outline-primary">Edit</a>
                <form method="post" action="delete.php" class="d-inline" onsubmit="return confirm('Delete this lecturer?');">
                  <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                  <button class="btn btn-sm btn-outline-danger">Delete</button>
                </form>
              </td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php
/* close layout */
$__layoutClosed=false;
foreach(['admin_layout_bottom.php','layout_bottom.php','admin_footer.php','footer_admin.php'] as $f){
  $p=__DIR__.'/../../includes/'.$f; if(is_file($p)){require_once $p; $__layoutClosed=true; break;}
}
if(!$__layoutClosed) echo '</div>';
