<?php require_once __DIR__.'/../includes/db.php'; require_once __DIR__.'/../includes/auth.php'; include __DIR__.'/../includes/header.php';
$act=$_GET['a']??'list';
if($act==='save' && $_SERVER['REQUEST_METHOD']==='POST'){ $id=intval($_POST['id']??0);
  $stmt=$mysqli->prepare($id>0? "UPDATE infografis SET label=?,value=?,unit=?,order_index=? WHERE id=?"
                              : "INSERT INTO infografis(label,value,unit,order_index) VALUES (?,?,?,?)");
  if($id>0){ $stmt->bind_param('sisii', $_POST['label'],$_POST['value'],$_POST['unit'],$_POST['order_index'],$id); }
  else { $stmt->bind_param('sisi', $_POST['label'],$_POST['value'],$_POST['unit'],$_POST['order_index']); }
  $stmt->execute(); header('Location: infografis.php'); exit;
}
if($act==='del'){ $id=intval($_GET['id']??0); if($id>0) $mysqli->query("DELETE FROM infografis WHERE id=$id"); header('Location: infografis.php'); exit; }
$row=null; if($act==='edit'){ $id=intval($_GET['id']??0); $row=$mysqli->query("SELECT * FROM infografis WHERE id=$id")->fetch_assoc(); } ?>
<div class="card" style="padding:18px"><div style="display:flex;justify-content:space-between;align-items:center"><h2>Infografis</h2><a class="btn primary" href="infografis.php?a=form">+ Tambah</a></div>
<?php if($act==='list'): $res=$mysqli->query("SELECT * FROM infografis ORDER BY order_index ASC, id DESC"); ?>
<table class="table"><thead><tr><th>ID</th><th>Label</th><th>Nilai</th><th>Satuan</th><th>Urutan</th><th>Aksi</th></tr></thead><tbody>
<?php while($r=$res->fetch_assoc()): ?><tr><td><?php echo $r['id']; ?></td><td><?php echo esc($r['label']); ?></td><td><?php echo esc($r['value']); ?></td><td><?php echo esc($r['unit']); ?></td><td><?php echo esc($r['order_index']); ?></td>
<td><a class="btn small" href="infografis.php?a=edit&id=<?php echo $r['id']; ?>">Edit</a> <a class="btn small" href="infografis.php?a=del&id=<?php echo $r['id']; ?>" onclick="return confirmDelete()">Hapus</a></td></tr><?php endwhile; ?>
</tbody></table>
<?php else: ?>
<form class="grid" method="post" action="infografis.php?a=save"><input type="hidden" name="id" value="<?php echo $row['id']??0; ?>">
<div><label>Label</label><input class="input" name="label" value="<?php echo esc($row['label']??''); ?>" required></div>
<div><label>Nilai</label><input class="input" type="number" name="value" value="<?php echo esc($row['value']??0); ?>" required></div>
<div><label>Satuan</label><input class="input" name="unit" value="<?php echo esc($row['unit']??''); ?>"></div>
<div><label>Urutan</label><input class="input" type="number" name="order_index" value="<?php echo esc($row['order_index']??0); ?>"></div>
<div style="grid-column:1/-1"><button class="btn primary">Simpan</button> <a class="btn" href="infografis.php">Batal</a></div></form>
<?php endif; ?></div><?php include __DIR__.'/../includes/footer.php'; ?>