<?php
require_once '../includes/config.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
requireAdminLogin();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verify_csrf()) {
    $action = $_POST['action'] ?? '';
    if ($action === 'add') {
        $pdo->prepare("INSERT INTO announcements (title,body,type,is_active,starts_at,ends_at) VALUES (?,?,?,?,?,?)")->execute([trim($_POST['title']),trim($_POST['body']),$_POST['type']??'info',isset($_POST['is_active'])?1:0,$_POST['starts_at']??null,$_POST['ends_at']??null]);
        flash('success','Announcement created.');
    }
    if ($action === 'toggle') {
        $id=(int)$_POST['ann_id'];
        $cur=$pdo->prepare("SELECT is_active FROM announcements WHERE id=? LIMIT 1");$cur->execute([$id]);$c=$cur->fetchColumn();
        $pdo->prepare("UPDATE announcements SET is_active=? WHERE id=?")->execute([$c?0:1,$id]);
        flash('success','Announcement toggled.');
    }
    if ($action === 'delete') {
        $pdo->prepare("DELETE FROM announcements WHERE id=?")->execute([(int)$_POST['ann_id']]);
        flash('success','Announcement deleted.');
    }
    header('Location: /admin/announcements.php'); exit;
}

$anns = $pdo->query("SELECT * FROM announcements ORDER BY id DESC")->fetchAll();
$pageTitle = 'Announcements';
?>
<?php include '../includes/header.php'; ?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div class="page-title mb-0"><i class="fa fa-bullhorn me-2 text-danger"></i>Announcements</div>
  <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addAnnModal"><i class="fa fa-plus me-1"></i>New</button>
</div>

<div class="card">
  <div class="table-responsive">
    <table class="table table-hover mb-0">
      <thead><tr><th>Title</th><th>Body</th><th>Type</th><th>Active</th><th>Period</th><th>Actions</th></tr></thead>
      <tbody>
      <?php if (empty($anns)): ?><tr><td colspan="6" class="text-center py-3 text-muted">No announcements.</td></tr>
      <?php else: foreach ($anns as $a): ?>
      <tr>
        <td class="fw-bold small"><?= sanitize($a['title']) ?></td>
        <td class="small"><?= sanitize(substr($a['body'],0,50)) ?>...</td>
        <td><?= statusBadge($a['type']) ?></td>
        <td><?= $a['is_active'] ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>' ?></td>
        <td class="small"><?= $a['starts_at']?date('M j',$a['starts_at']):'—' ?> – <?= $a['ends_at']?date('M j',$a['ends_at']):'∞' ?></td>
        <td>
          <form method="POST" class="d-flex gap-1">
            <?= csrf_field() ?><input type="hidden" name="ann_id" value="<?= $a['id'] ?>">
            <button name="action" value="toggle" class="btn btn-xs btn-outline-warning"><?= $a['is_active']?'Deactivate':'Activate' ?></button>
            <button name="action" value="delete" class="btn btn-xs btn-outline-danger" data-confirm="Delete this announcement?"><i class="fa fa-trash"></i></button>
          </form>
        </td>
      </tr>
      <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
</div>
<?php include '../includes/footer.php'; ?>
<!-- Add Modal -->
<div class="modal fade" id="addAnnModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
  <div class="modal-header"><h5 class="modal-title">New Announcement</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
  <form method="POST"><div class="modal-body">
    <?= csrf_field() ?><input type="hidden" name="action" value="add">
    <div class="mb-3"><label class="form-label">Title *</label><input type="text" name="title" class="form-control" required></div>
    <div class="mb-3"><label class="form-label">Message *</label><textarea name="body" class="form-control" rows="3" required></textarea></div>
    <div class="row g-3">
      <div class="col-md-6"><label class="form-label">Type</label><select name="type" class="form-select"><option value="info">Info</option><option value="warning">Warning</option><option value="success">Success</option><option value="maintenance">Maintenance</option></select></div>
      <div class="col-md-6"><div class="form-check mt-4"><input class="form-check-input" type="checkbox" name="is_active" id="ann_active" value="1" checked><label class="form-check-label" for="ann_active">Active immediately</label></div></div>
      <div class="col-md-6"><label class="form-label">Start Date</label><input type="datetime-local" name="starts_at" class="form-control"></div>
      <div class="col-md-6"><label class="form-label">End Date</label><input type="datetime-local" name="ends_at" class="form-control"></div>
    </div>
  </div>
  <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button><button class="btn btn-primary fw-bold">Publish</button></div>
  </form>
</div></div></div>
