<?php $PAGE_TITLE='Notices'; require __DIR__.'/_layout.php';
// Ensure popup column exists (safe if already added)
try { $pdo->exec("ALTER TABLE notices ADD COLUMN popup TINYINT(1) NOT NULL DEFAULT 0"); } catch (Throwable $e) {}

if($_SERVER['REQUEST_METHOD']==='POST'){csrf_check();
  $id=(int)($_POST['id']??0);
  $popup = isset($_POST['popup'])?1:0;
  $active = isset($_POST['active'])?1:0;
  if($id){
    $pdo->prepare("UPDATE notices SET title=?,body=?,active=?,popup=? WHERE id=?")
        ->execute([$_POST['title'],$_POST['body'],$active,$popup,$id]);
  } else {
    $pdo->prepare("INSERT INTO notices(title,body,active,popup) VALUES(?,?,?,?)")
        ->execute([$_POST['title'],$_POST['body'],$active,$popup]);
  }
  redirect('notices.php');
}
if(isset($_GET['del'])){$pdo->prepare("DELETE FROM notices WHERE id=?")->execute([(int)$_GET['del']]); redirect('notices.php');}
$rows=$pdo->query("SELECT * FROM notices ORDER BY id DESC")->fetchAll();
?>
<h2 style="margin-bottom:14px">📢 নোটিশ</h2>
<div class="card" style="margin-bottom:20px">
<form method="post"><?=csrf_field()?>
<div class="field"><label>Title</label><input class="input" name="title" required></div>
<div class="field"><label>Body</label><textarea class="input" name="body" rows="3" required></textarea></div>
<label style="display:flex;gap:6px;margin-bottom:8px"><input type="checkbox" name="active" checked> Active (ড্যাশবোর্ডে ব্যানার হিসেবে দেখাবে)</label>
<label style="display:flex;gap:6px;margin-bottom:10px"><input type="checkbox" name="popup"> 🔔 Popup (হোমপেজে ফুলস্ক্রিন পপআপ হিসেবে দেখাবে)</label>
<button class="btn">Add Notice</button>
</form></div>
<table><thead><tr><th>#</th><th>Title</th><th>Body</th><th>Active</th><th>Popup</th><th>Date</th><th>Del</th></tr></thead><tbody>
<?php foreach($rows as $r):?>
<tr><td>#<?=$r['id']?></td><td><b><?=e($r['title'])?></b></td><td><?=e($r['body'])?></td>
<td><span class="badge <?=$r['active']?'ok':'fail'?>"><?=$r['active']?'On':'Off'?></span></td>
<td><span class="badge <?=!empty($r['popup'])?'ok':'fail'?>"><?=!empty($r['popup'])?'Popup':'—'?></span></td>
<td><?=e($r['created_at'])?></td>
<td><a class="btn sm danger" href="?del=<?=$r['id']?>" onclick="return confirm('Delete?')">🗑️</a></td></tr>
<?php endforeach;?>
</tbody></table>
<?php require __DIR__.'/_footer.php';
