<?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);
  $imgname=null; if(isset($_FILES['image']) && $_FILES['image']['error']===0){ $ext=pathinfo($_FILES['image']['name'],PATHINFO_EXTENSION); $imgname='galeri_'.time().'_'.rand(1000,9999).'.'.$ext; move_uploaded_file($_FILES['image']['tmp_name'], __DIR__.'/../uploads/'.$imgname); }
  if($id>0){
    if($imgname){ $stmt=$mysqli->prepare("UPDATE galeri SET title=?, image=? WHERE id=?"); $stmt->bind_param('ssi', $_POST['title'],$imgname,$id); }
    else { $stmt=$mysqli->prepare("UPDATE galeri SET title=? WHERE id=?"); $stmt->bind_param('si', $_POST['title'],$id); }
  } else {
    $stmt=$mysqli->prepare("INSERT INTO galeri(title,image) VALUES (?,?)"); $stmt->bind_param('ss', $_POST['title'],$imgname);
  }
  $stmt->execute(); header('Location: galeri.php'); exit;
}
if($act==='del'){ $id=intval($_GET['id']??0); if($id>0){ $o=$mysqli->query("SELECT image FROM galeri WHERE id=$id")->fetch_assoc(); if($o && !empty($o['image'])) @unlink(__DIR__.'/../uploads/'.$o['image']); $mysqli->query("DELETE FROM galeri WHERE id=$id"); } header('Location: galeri.php'); exit; }
$row=null; if($act==='edit'){ $id=intval($_GET['id']??0); $row=$mysqli->query("SELECT * FROM galeri WHERE id=$id")->fetch_assoc(); } ?>
<div class="card" style="padding:18px"><div style="display:flex;justify-content:space-between;align-items:center"><h2>Galeri</h2><a class="btn primary" href="galeri.php?a=form">+ Tambah</a></div>
<?php if($act==='list'): $res=$mysqli->query("SELECT * FROM galeri ORDER BY id DESC"); ?>
<table class="table"><thead><tr><th>ID</th><th>Judul</th><th>Gambar</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['title']); ?></td>
<td><?php if(!empty($r['image'])) echo '<img src="../uploads/'.esc($r['image']).'" style="width:90px;border-radius:6px">'; ?></td>
<td><a class="btn small" href="galeri.php?a=edit&id=<?php echo $r['id']; ?>">Edit</a> <a class="btn small" href="galeri.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" enctype="multipart/form-data" action="galeri.php?a=save"><input type="hidden" name="id" value="<?php echo $row['id']??0; ?>">
<div><label>Judul</label><input class="input" name="title" value="<?php echo esc($row['title']??''); ?>" required></div>
<div><label>Gambar</label><input class="input" type="file" name="image"></div>
<div style="grid-column:1/-1"><button class="btn primary">Simpan</button> <a class="btn" href="galeri.php">Batal</a></div></form>
<?php endif; ?></div><?php include __DIR__.'/../includes/footer.php'; ?>