<?php
// /elms/admin/lecturers/edit.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/db.php';
require_once __DIR__ . '/../../includes/helpers.php';
if (is_file(__DIR__ . '/../../includes/scope.php')) require_once __DIR__ . '/../../includes/scope.php';

function table_exists(mysqli $db, string $t): bool {
  $st = $db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? LIMIT 1");
  $st->bind_param('s',$t); $st->execute();
  $ok = (bool)$st->get_result()->fetch_row(); $st->close(); return $ok;
}
function column_exists(mysqli $db, string $t, string $c): bool {
  $st = $db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1");
  $st->bind_param('ss',$t,$c); $st->execute();
  $ok = (bool)$st->get_result()->fetch_row(); $st->close(); return $ok;
}
function esc2($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8'); }

// detect lecturers table
$LECT_TBL = table_exists($mysqli,'lecturers') ? 'lecturers' : '';
if (!$LECT_TBL) {
  http_response_code(500);
  exit('Lecturers table not found. Create a table like "lecturers".');
}

// optional centre list
$centres = [];
$CENTRE_TBL = '';
foreach (['centres','centers','branches'] as $cand) {
  if (table_exists($mysqli,$cand)) { $CENTRE_TBL = $cand; break; }
}
if ($CENTRE_TBL) {
  $label = 'name';
  foreach (['name','centre_name','center_name','title','label'] as $lc) {
    if (column_exists($mysqli,$CENTRE_TBL,$lc)) { $label = $lc; break; }
  }
  $sqlC = "SELECT id, COALESCE($label,'#') AS label FROM `$CENTRE_TBL` ORDER BY label";
  if ($rs = $mysqli->query($sqlC)) { while($r=$rs->fetch_assoc()) $centres[(int)$r['id']]=$r['label']; }
}

// defaults
$id     = (int)($_GET['id'] ?? 0);
$mode   = $id>0 ? 'edit' : 'new';
$title  = $mode==='edit' ? 'Edit Lecturer' : 'New Lecturer';

$full_name = '';
$email     = '';
$phone     = '';
$status    = 'Active';
$centre_id = 0;
$designation = 'Lecturer';

// if editing, load row
if ($id>0) {
  $sel = "SELECT id,
                 COALESCE(full_name, name, '') AS full_name,
                 COALESCE(email,'') AS email,
                 COALESCE(phone,'') AS phone,
                 COALESCE(status,'Active') AS status,
                 COALESCE(centre_id, 0) AS centre_id,
                 COALESCE(designation, title, 'Lecturer') AS designation
          FROM `$LECT_TBL` WHERE id=? LIMIT 1";
  $st = $mysqli->prepare($sel); $st->bind_param('i',$id); $st->execute();
  if ($row = $st->get_result()->fetch_assoc()) {
    $full_name = (string)$row['full_name'];
    $email     = (string)$row['email'];
    $phone     = (string)$row['phone'];
    $status    = (string)$row['status'];
    $centre_id = (int)$row['centre_id'];
    $designation = (string)$row['designation'];
  }
  $st->close();
}

// handle post
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  $full_name  = trim((string)($_POST['full_name'] ?? ''));
  $email      = trim((string)($_POST['email'] ?? ''));
  $phone      = trim((string)($_POST['phone'] ?? ''));
  $status     = trim((string)($_POST['status'] ?? 'Active'));
  $centre_id  = (int)($_POST['centre_id'] ?? 0);
  $designation= trim((string)($_POST['designation'] ?? 'Lecturer'));

  if ($full_name === '') $full_name = '—';

  if ($id>0) {
    $sql = "UPDATE `$LECT_TBL`
            SET full_name=?, email=?, phone=?, status=?, centre_id=?, designation=?
            WHERE id=?";
    $st  = $mysqli->prepare($sql);
    $st->bind_param('ssssi si', $full_name, $email, $phone, $status, $centre_id, $designation, $id);
    // note: fix type string: 'ssssisi' (4s + i + s + i)
  } else {
    $sql = "INSERT INTO `$LECT_TBL` (full_name,email,phone,status,centre_id,designation)
            VALUES (?,?,?,?,?,?)";
    $st  = $mysqli->prepare($sql);
    $st->bind_param('ssssis', $full_name, $email, $phone, $status, $centre_id, $designation);
  }
  // correct bind types:
  if ($id>0) { $st->bind_param('ssssisi', $full_name, $email, $phone, $status, $centre_id, $designation, $id); }
  else       { $st->bind_param('ssssis',  $full_name, $email, $phone, $status, $centre_id, $designation); }

  $st->execute(); $st->close();

  // ABSOLUTE redirect to list (prevents /admin/lecturers/.../admin/lecturers/)
  header('Location: ' . app_url('/admin/lecturers/index.php'));
  exit;
}

// layout open
$__layoutOpened = false;
foreach (['admin_layout_top.php','layout_top.php'] as $f) {
  $p = __DIR__ . '/../../includes/' . $f;
  if (is_file($p)) { require $p; $__layoutOpened = true; break; }
}
if (!$__layoutOpened) {
  echo "<!doctype html><html><head><meta charset='utf-8'>";
  echo "<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css'>";
  echo "<title>$title</title></head><body class='container py-3'>";
}
?>
<div class="d-flex align-items-center justify-content-between mb-3">
  <h1 class="h5 m-0"><?= esc2($title) ?></h1>
  <div>
    <!-- FIXED: absolute URL back to list -->
    <a href="<?= esc(app_url('/admin/lecturers/index.php')) ?>" class="btn btn-outline-secondary btn-sm">Back to list</a>
  </div>
</div>

<form method="post" class="card">
  <div class="card-body">
    <div class="row g-3">
      <div class="col-md-6">
        <label class="form-label">Full name <span class="text-danger">*</span></label>
        <input class="form-control" name="full_name" required value="<?= esc2($full_name) ?>">
      </div>
      <div class="col-md-6">
        <label class="form-label">Title / Designation</label>
        <select class="form-select" name="designation">
          <?php
            $opts = ['Lecturer','Senior Lecturer','Assistant Lecturer','Head of Department','Coordinator','Visiting Lecturer','Instructor','Tutor'];
            foreach ($opts as $o) { $sel = ($o===$designation)?' selected':''; echo "<option$sel>".esc2($o)."</option>"; }
          ?>
        </select>
      </div>
      <?php if ($CENTRE_TBL): ?>
        <div class="col-md-6">
          <label class="form-label">Centre</label>
          <select class="form-select" name="centre_id">
            <option value="0">— Not assigned —</option>
            <?php foreach($centres as $cid=>$lab): ?>
              <option value="<?= (int)$cid ?>" <?= $cid===$centre_id?'selected':'' ?>><?= esc2($lab) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      <?php endif; ?>
      <div class="col-md-6">
        <label class="form-label">Status</label>
        <select class="form-select" name="status">
          <?php foreach (['Active','Inactive'] as $st): ?>
            <option <?= $st===$status?'selected':'' ?>><?= esc2($st) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-6">
        <label class="form-label">Email</label>
        <input class="form-control" name="email" type="email" value="<?= esc2($email) ?>">
      </div>
      <div class="col-md-6">
        <label class="form-label">Phone</label>
        <input class="form-control" name="phone" value="<?= esc2($phone) ?>">
      </div>
    </div>
  </div>
  <div class="card-footer d-flex gap-2">
    <button class="btn btn-primary"><?= $id>0?'Save changes':'Create' ?></button>
    <!-- FIXED: absolute URL cancel -->
    <a class="btn btn-outline-secondary" href="<?= esc(app_url('/admin/lecturers/index.php')) ?>">Cancel</a>
  </div>
</form>

<?php
// layout close
$__layoutClosed = false;
foreach (['admin_layout_bottom.php','layout_bottom.php'] as $f) {
  $p = __DIR__ . '/../../includes/' . $f;
  if (is_file($p)) { require $p; $__layoutClosed = true; break; }
}
if (!$__layoutClosed) echo "</body></html>";
