<?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';
if (is_file(__DIR__ . '/../../includes/helpers.php')) require_once __DIR__ . '/../../includes/helpers.php';

$PAGE_TITLE  = 'Centres';
$ACTIVE_MENU = 'centres';

/* ---------- tiny local helpers (no name clashes) ---------- */
function cdb_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 cdb_cols(mysqli $db, string $t): array {
  $cols = [];
  if ($rs = $db->query("SHOW COLUMNS FROM `$t`")) {
    while ($r = $rs->fetch_assoc()) $cols[] = $r['Field'];
  }
  return $cols;
}
function cdb_pick_label(array $have, array $candidates): string {
  foreach ($candidates as $c) if (in_array($c, $have, true)) return $c;
  return 'id';
}

/* ---------- find a suitable table ---------- */
$candidateTables = ['centres','centers','branches','branch','venues','locations'];
$TBL = '';
foreach ($candidateTables as $t) { if (cdb_table_exists($mysqli,$t)) { $TBL = $t; break; } }

if ($TBL === '') {
  // pretty message (keeps layout)
  $__top = __DIR__ . '/../../includes/admin_layout_top.php';
  $__bot = __DIR__ . '/../../includes/admin_layout_bottom.php';
  if (is_file($__top)) require $__top; else echo '<div class="container p-3">';
  echo '<div class="alert alert-danger">Couldn’t find a table for <b>Centres</b>. Create one named <code>centres</code> (or similar), or rename your existing table to a centres/centers/branches style.</div>';
  if (is_file($__bot)) require $__bot; else echo '</div>';
  exit;
}

/* ---------- pick columns present in that table ---------- */
$HAVE = cdb_cols($mysqli,$TBL);
$labelCol  = cdb_pick_label($HAVE, ['name','centre_name','center_name','branch_name','venue_name','title','label']);
$codeCol   = in_array('code',$HAVE,true)        ? 'code'   : (in_array('centre_code',$HAVE,true) ? 'centre_code' : '');
$statusCol = in_array('status',$HAVE,true)      ? 'status' : (in_array('is_active',$HAVE,true)    ? 'is_active'   : '');
$idCol     = in_array('id',$HAVE,true)          ? 'id'     : $HAVE[0];

/* ---------- filters ---------- */
$q = trim($_GET['q'] ?? '');
$where = "WHERE 1=1";
$types = ''; $vals = [];
if ($q !== '') { $where .= " AND $labelCol LIKE ?"; $types .= 's'; $vals[] = "%$q%"; }

/* ---------- data ---------- */
$select = "$idCol AS id, $labelCol AS label";
if ($codeCol)   $select .= ", $codeCol   AS code";
if ($statusCol) $select .= ", $statusCol AS status";

$sql = "SELECT $select 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);
$st->close();

/* ---------- open layout (sidebar/topbar) ---------- */
$__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">Centres</h1>
  <div>
    <a href="edit.php" class="btn btn-primary btn-sm">+ New</a>
  </div>
</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…">
  </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:50%">Name</th>
            <?php if ($codeCol):   ?><th>Code</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="<?= 2 + ($codeCol?1:0) + ($statusCol?1:0) ?>" class="text-center text-muted">No records.</td></tr>
        <?php else: foreach ($rows as $r): ?>
          <tr>
            <td class="fw-semibold"><?= esc($r['label']) ?></td>
            <?php if ($codeCol):   ?><td><?= esc($r['code'] ?? '') ?></td><?php endif; ?>
            <?php if ($statusCol): ?>
              <td>
                <?php
                  $st = (string)($r['status'] ?? '');
                  if ($st === 'Active' || $st === '1')       echo '<span class="badge bg-success">Active</span>';
                  elseif ($st === 'Inactive' || $st === '0') echo '<span class="badge bg-secondary">Inactive</span>';
                  else                                       echo '<span class="badge bg-light text-dark">'.esc($st ?: '-').'</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 item?');">
                <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>';
