<?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  = 'Centre';
$ACTIVE_MENU = 'centres';

/* ------------- tiny local helpers (no global name clash) ------------- */
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';
}
function esc2($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE,'UTF-8'); }
function csrf_token(){
  if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
  return $_SESSION['csrf'];
}
function csrf_ok(){ return isset($_POST['csrf']) && hash_equals($_SESSION['csrf'] ?? '', (string)$_POST['csrf']); }

/* ------------- find table + columns ------------- */
$candidateTables = ['centres','centers','branches','branch','venues','locations'];
$TBL = ''; foreach ($candidateTables as $t) if (cdb_table_exists($mysqli,$t)) { $TBL=$t; break; }
if ($TBL === '') { http_response_code(500); exit('Centres table not found'); }

$HAVE     = cdb_cols($mysqli,$TBL);
$idCol    = in_array('id',$HAVE,true) ? 'id' : $HAVE[0];
$nameCol  = 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' : '');
$statCol  = in_array('status',$HAVE,true) ? 'status' : (in_array('is_active',$HAVE,true) ? 'is_active' : '');

/* ------------- load row if editing ------------- */
$id = (int)($_GET['id'] ?? 0);
$row = [$nameCol=>'',$codeCol=>'',$statCol=>''];
if ($id>0) {
  $sel = "$idCol AS id,$nameCol AS name" . ($codeCol?",$codeCol AS code":'') . ($statCol?",$statCol AS status":'');
  $st  = $mysqli->prepare("SELECT $sel FROM `$TBL` WHERE `$idCol`=? LIMIT 1");
  $st->bind_param('i',$id); $st->execute(); $row = $st->get_result()->fetch_assoc() ?: $row; $st->close();
}

/* ------------- handle submit ------------- */
$err = '';
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  if (!csrf_ok()) { $err = 'Security check failed.'; }
  else {
    $name = trim((string)($_POST['name'] ?? ''));
    $code = trim((string)($_POST['code'] ?? ''));
    $statusIn = (string)($_POST['status'] ?? '');

    if ($name === '') $err = 'Name is required.';

    if (!$err) {
      // build columns dynamically
      $cols = [$nameCol];  $types = 's';  $vals = [$name];
      if ($codeCol) { $cols[] = $codeCol; $types .= 's'; $vals[] = $code; }
      if ($statCol) {
        if ($statCol === 'is_active') { // store tinyint(1)
          $v = ($statusIn === 'Active' || $statusIn === '1') ? 1 : 0;
        } else {                         // store text enum
          $v = ($statusIn === '' ? 'Active' : $statusIn);
        }
        $cols[] = $statCol; $types .= ($statCol==='is_active'?'i':'s'); $vals[] = $v;
      }

      if ($id>0) {
        $set = implode(', ', array_map(fn($c)=>"`$c`=?", $cols));
        $sql = "UPDATE `$TBL` SET $set WHERE `$idCol`=?";
        $types2 = $types.'i'; $vals2 = array_merge($vals, [$id]);
        $st = $mysqli->prepare($sql); $st->bind_param($types2, ...$vals2); $st->execute(); $st->close();
      } else {
        $colList = implode(',', array_map(fn($c)=>"`$c`", $cols));
        $qMarks  = implode(',', array_fill(0, count($cols), '?'));
        $sql = "INSERT INTO `$TBL` ($colList) VALUES ($qMarks)";
        $st = $mysqli->prepare($sql); $st->bind_param($types, ...$vals); $st->execute(); $id = $st->insert_id; $st->close();
      }
      header('Location: '.('../centres/index.php')); exit;
    }
  }
}

/* ------------- page chrome ------------- */
$__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 p-3">';
?>
<div class="d-flex align-items-center justify-content-between mb-3">
  <h1 class="h5 m-0"><?= $id>0?'Edit Centre':'New Centre' ?></h1>
</div>

<?php if ($err): ?>
  <div class="alert alert-danger py-2"><?= esc2($err) ?></div>
<?php endif; ?>

<div class="card">
  <div class="card-body">
    <form method="post" class="row g-3" autocomplete="off">
      <input type="hidden" name="csrf" value="<?= esc2(csrf_token()) ?>">

      <div class="col-md-6">
        <label class="form-label">Name<span class="text-danger">*</span></label>
        <input class="form-control" name="name" required value="<?= esc2($row['name'] ?? '') ?>">
      </div>

      <?php if ($codeCol): ?>
      <div class="col-md-4">
        <label class="form-label">Code</label>
        <input class="form-control" name="code" value="<?= esc2($row['code'] ?? '') ?>">
      </div>
      <?php endif; ?>

      <?php if ($statCol): ?>
      <div class="col-md-2">
        <label class="form-label">Status</label>
        <select class="form-select" name="status">
          <?php
            $cur = $row['status'] ?? 'Active';
            if ($statCol === 'is_active') $cur = ((string)$cur==='1') ? 'Active' : 'Inactive';
          ?>
          <option <?= $cur==='Active'?'selected':'' ?>>Active</option>
          <option <?= $cur==='Inactive'?'selected':'' ?>>Inactive</option>
        </select>
      </div>
      <?php endif; ?>

      <div class="col-12">
        <button class="btn btn-primary"><?= $id>0?'Save Changes':'Create' ?></button>
        <a class="btn btn-outline-secondary" href="index.php">Cancel</a>
      </div>
    </form>
  </div>
</div>

<?php
$__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>';
