<?php
@ini_set('display_errors','1'); @error_reporting(E_ALL);

require_once __DIR__ . '/../includes/auth.php';
require_login();

$page_title = 'Competition Type Master';
$TABLE = 'jos_app_competition_type';

/* ---------- helpers (Languages Master pattern) ---------- */
function keep_params(array $changes = []) {
  $qs = is_array($_GET) ? $_GET : [];
  foreach ($changes as $k=>$v) {
    if ($v===null) unset($qs[$k]);
    else $qs[$k] = $v;
  }
  $q = http_build_query($qs);
  $path = $_SERVER['PHP_SELF'];
  return $path . ($q !== '' ? ('?' . $q) : '');
}
function clean($v){ return trim((string)$v); }
function col_exists($con,$table,$col){
  $r=mysqli_query($con,"SHOW COLUMNS FROM `$table` LIKE '".mysqli_real_escape_string($con,$col)."'");
  return ($r && mysqli_num_rows($r)>0);
}
function ensure_schema($con,$table){
  mysqli_query($con,"CREATE TABLE IF NOT EXISTS `$table`(
    `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(190) NOT NULL,
    `status` TINYINT(1) NOT NULL DEFAULT 1,
    `orderby` INT NOT NULL DEFAULT 0,
    PRIMARY KEY (`id`),
    KEY `idx_status`(`status`),
    KEY `idx_orderby`(`orderby`)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
  if(!col_exists($con,$table,'status'))  mysqli_query($con,"ALTER TABLE `$table` ADD `status` TINYINT(1) NOT NULL DEFAULT 1");
  if(!col_exists($con,$table,'orderby')) mysqli_query($con,"ALTER TABLE `$table` ADD `orderby` INT NOT NULL DEFAULT 0");
  else                                    mysqli_query($con,"ALTER TABLE `$table` MODIFY `orderby` INT NOT NULL DEFAULT 0");
}
ensure_schema($con,$TABLE);

/* flash redirect helper */
function back_to_list($msg=''){
  $self = $_SERVER['PHP_SELF'];
  header('Location: '.$self.($msg!==''?'?ok='.urlencode($msg):'')); exit;
}

$ok  = clean($_GET['ok'] ?? '');
$err = '';

/* ---------- POST (Save / Delete) ---------- */
if ($_SERVER['REQUEST_METHOD']==='POST'){
  if (!verify_csrf($_POST['csrf'] ?? null)) {
    $err='Invalid request. Please refresh.';
  } else {
    if (isset($_POST['save'])) {
      $id      = (int)($_POST['id'] ?? 0);
      $name    = clean($_POST['name'] ?? '');
      $status  = (int)($_POST['status'] ?? 1);
      $orderby = (int)($_POST['orderby'] ?? 0);

      if ($name===''){ $err='Name is required.'; }
      else {
        // case-insensitive duplicate check
        $dup_sql = "SELECT id FROM $TABLE WHERE LOWER(name)=LOWER(?)";
        if ($id>0) $dup_sql .= " AND id<>?";
        $st=$con->prepare($dup_sql." LIMIT 1");
        if ($id>0) $st->bind_param('si',$name,$id); else $st->bind_param('s',$name);
        $st->execute(); $dup=$st->get_result()->fetch_assoc(); $st->close();

        if ($dup){ $err='This competition type already exists.'; }
        else {
          if ($orderby<=0){
            $r = mysqli_query($con,"SELECT COALESCE(MAX(orderby),0)+1 nxt FROM $TABLE");
            $orderby = (int)($r ? mysqli_fetch_assoc($r)['nxt'] : 1);
          }
          if ($id>0){
            $st=$con->prepare("UPDATE $TABLE SET name=?, status=?, orderby=? WHERE id=?");
            $st->bind_param('siii',$name,$status,$orderby,$id);
            if ($st->execute()){ $st->close(); back_to_list('Updated successfully.'); }
            $err='Update failed.'; $st->close();
          } else {
            $st=$con->prepare("INSERT INTO $TABLE (name,status,orderby) VALUES (?,?,?)");
            $st->bind_param('sii',$name,$status,$orderby);
            if ($st->execute()){ $st->close(); back_to_list('Added successfully.'); }
            $err='Insert failed.'; $st->close();
          }
        }
      }
    }
    if (isset($_POST['delete'])) {
      $id=(int)($_POST['id'] ?? 0);
      $st=$con->prepare("DELETE FROM $TABLE WHERE id=?");
      $st->bind_param('i',$id);
      if ($st->execute()){ $st->close(); back_to_list('Deleted successfully.'); }
      $err='Delete failed.'; $st->close();
    }
  }
}

/* ---------- mode ---------- */
$mode = (isset($_GET['edit']) || isset($_GET['add'])) ? 'form' : 'list';

/* ---------- edit row ---------- */
$edit=null;
if ($mode==='form' && isset($_GET['edit'])){
  $eid=(int)$_GET['edit'];
  $st=$con->prepare("SELECT id,name,status,orderby FROM $TABLE WHERE id=?");
  $st->bind_param('i',$eid); $st->execute();
  $edit=$st->get_result()->fetch_assoc(); $st->close();
}

/* ---------- filters (match Languages UI) ---------- */
$q      = clean($_GET['q'] ?? '');
$levelS = clean($_GET['level'] ?? '');   // exact order level
$sort   = clean($_GET['sort']  ?? 'order_asc');
$all    = isset($_GET['all']); $lim = $all ? 0 : 50;

$where=" WHERE 1=1 "; $bind=[]; $type='';
if ($q!==''){ $like="%$q%"; $where.=" AND name LIKE ?"; $bind[]=$like; $type.='s'; }
if ($levelS!=='' && is_numeric($levelS)){ $lvl=(int)$levelS; $where.=" AND orderby=?"; $bind[]=$lvl; $type.='i'; }

switch ($sort){
  case 'order_desc': $order="ORDER BY orderby DESC, id DESC"; break;
  case 'name_asc'  : $order="ORDER BY name ASC"; break;
  case 'name_desc' : $order="ORDER BY name DESC"; break;
  case 'id_asc'    : $order="ORDER BY id ASC"; break;
  case 'id_desc'   : $order="ORDER BY id DESC"; break;
  default          : $order="ORDER BY orderby ASC, id DESC";
}

/* ---------- counts / list ---------- */
$st=$con->prepare("SELECT COUNT(*) c FROM $TABLE $where");
if ($bind) $st->bind_param($type, ...$bind);
$st->execute(); $total=(int)$st->get_result()->fetch_assoc()['c']; $st->close();

$sql="SELECT id,name,status,orderby FROM $TABLE $where $order";
if (!$all) $sql.=" LIMIT $lim";
$st=$con->prepare($sql);
if ($bind) $st->bind_param($type, ...$bind);
$st->execute();
$rs=$st->get_result(); $rows=[];
while($r=$rs->fetch_assoc()) $rows[]=$r;
$st->close();

/* ---------- view (UI + styles identical to Languages) ---------- */
ob_start(); ?>
<link rel="stylesheet" href="/adminconsole/assets/ui.css">

<div class="master-wrap">
  <div class="headbar">
    <div class="headbar-left"><h2 style="margin:0"><?php echo htmlspecialchars($page_title); ?></h2></div>
    <div class="headbar-right"><!-- empty on purpose to match Languages --></div>
  </div>

  <?php if($ok):  ?><div class="card" style="border-left:4px solid #10b981"><div><?php echo htmlspecialchars($ok); ?></div></div><?php endif; ?>
  <?php if($err): ?><div class="card" style="border-left:4px solid #ef4444"><div><?php echo htmlspecialchars($err); ?></div></div><?php endif; ?>

  <?php if ($mode==='list'): ?>
    <div class="card">
      <div class="toolbar">
        <form method="get" class="search">
          <input type="text" name="q" class="inp" placeholder="Search language..." value="<?php echo htmlspecialchars($q); ?>" style="width:320px">
          <input type="number" name="level" class="inp small" placeholder="Order level" value="<?php echo htmlspecialchars($levelS); ?>">
          <select name="sort" class="inp small" title="Sort by">
            <?php
              $opts = [
                'order_asc'  => 'Order Level ↑',
                'order_desc' => 'Order Level ↓',
                'name_asc'   => 'Name A–Z',
                'name_desc'  => 'Name Z–A',
                'id_desc'    => 'Newest first',
                'id_asc'     => 'Oldest first',
              ];
              foreach($opts as $k=>$v){
                $sel = ($sort===$k)?'selected':'';
                echo "<option value=\"$k\" $sel>$v</option>";
              }
            ?>
          </select>
          <button class="btn gray" type="submit">Search</button>
          <a class="btn gray" href="<?php echo keep_params(['q'=>null,'level'=>null,'sort'=>null,'all'=>null]); ?>">Reset</a>
        </form>

        <div style="display:flex;gap:8px">
          <a class="btn green" href="<?php echo keep_params(['add'=>1,'edit'=>null]); ?>">Add New</a>
          <a class="btn gray"  href="<?php echo keep_params(['all'=>1]); ?>">View All (<?php echo $total; ?>)</a>
        </div>
      </div>

      <div style="margin:6px 0 12px;color:#9ca3af">
        Showing <strong><?php echo !$all ? count($rows) : $total; ?></strong> of <strong><?php echo $total; ?></strong>
        (sorted: <?php echo htmlspecialchars($opts[$sort] ?? 'Order Level ↑'); ?>)
      </div>

      <div class="table-wrap">
        <table>
          <thead><tr>
            <th>SR No</th><th>Name</th><th>Order Level</th><th>Status</th><th>Actions</th>
          </tr></thead>
          <tbody>
            <?php if(!$rows): ?><tr><td colspan="5" style="color:#9ca3af">No records</td></tr><?php endif; ?>
            <?php $sr=0; foreach($rows as $r): $sr++; ?>
              <tr>
                <td><?php echo $sr; ?></td>
                <td><?php echo htmlspecialchars($r['name']); ?></td>
                <td><?php echo (int)$r['orderby']; ?></td>
                <td><span class="badge <?php echo $r['status']?'on':'off'; ?>"><?php echo $r['status']?'Active':'Inactive'; ?></span></td>
                <td>
                  <a class="btn gray" href="<?php echo keep_params(['edit'=>(int)$r['id'],'add'=>null]); ?>">Edit</a>
                  <form method="post" style="display:inline" onsubmit="return confirm('Delete this record?');">
                    <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
                    <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>">
                    <button class="btn red" name="delete" type="submit">Delete</button>
                  </form>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>

  <?php else: /* form */ ?>
    <div class="card" style="max-width:720px">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px">
        <h3 style="margin:0"><?php echo $edit ? 'Edit Competition Type' : 'Add Competition Type'; ?></h3>
        <a class="btn gray" href="<?php echo keep_params(['edit'=>null,'add'=>null]); ?>">Back to List</a>
      </div>

      <form method="post" style="display:grid;grid-template-columns:1fr 1fr;gap:12px" autocomplete="off">
        <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
        <?php if($edit): ?><input type="hidden" name="id" value="<?php echo (int)$edit['id']; ?>"><?php endif; ?>

        <div style="grid-column:1/-1">
          <label>Name*</label>
          <input name="name" class="inp" required value="<?php echo htmlspecialchars($edit['name'] ?? ''); ?>">
        </div>

        <div>
          <label>Order Level</label>
          <input name="orderby" type="number" class="inp" value="<?php echo htmlspecialchars((string)($edit['orderby'] ?? '')); ?>" placeholder="Auto if blank/0">
        </div>

        <div>
          <label>Status</label>
          <?php $st = isset($edit['status']) ? (int)$edit['status'] : 1; ?>
          <select name="status" class="inp">
            <option value="1" <?php echo $st===1?'selected':''; ?>>Active</option>
            <option value="0" <?php echo $st===0?'selected':''; ?>>Inactive</option>
          </select>
        </div>

        <div style="grid-column:1/-1">
          <button class="btn green" name="save" type="submit">Save</button> 
        </div>
      </form>
    </div>
  <?php endif; ?>
</div>
<?php echo ob_get_clean();
