<?php
require_once __DIR__ . '/includes/auth.php';
require_admin();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_check()) {
    $title = trim($_POST['title'] ?? '');
    $slug = trim($_POST['slug'] ?? '') ?: preg_replace('/[^a-z0-9]+/', '-', strtolower($title));
    $slug = trim($slug, '-');
    $description = trim($_POST['description'] ?? '');
    $deadline = trim($_POST['deadline'] ?? '') ?: null;
    $publishedAt = trim($_POST['published_at'] ?? '') ?: date('Y-m-d');
    if ($title !== '') {
        if (!empty($_POST['id'])) {
            db()->prepare('UPDATE procurement_notices SET title=?, slug=?, description=?, deadline=?, published_at=? WHERE id=?')
                ->execute([$title, $slug, $description, $deadline, $publishedAt, (int)$_POST['id']]);
        } else {
            db()->prepare('INSERT INTO procurement_notices (title, slug, description, deadline, published_at, file_path) VALUES (?,?,?,?,?,\'\')')
                ->execute([$title, $slug, $description, $deadline, $publishedAt]);
        }
    }
    header('Location: /admin/procurement.php');
    exit;
}
if (!empty($_GET['delete']) && isset($_GET['csrf']) && hash_equals($_SESSION['csrf'] ?? '', $_GET['csrf'])) {
    db()->prepare('DELETE FROM procurement_notices WHERE id=?')->execute([(int)$_GET['delete']]);
    header('Location: /admin/procurement.php');
    exit;
}

$editing = null;
if (!empty($_GET['edit'])) {
    $stmt = db()->prepare('SELECT * FROM procurement_notices WHERE id=?');
    $stmt->execute([(int)$_GET['edit']]);
    $editing = $stmt->fetch();
}

$notices = db()->query('SELECT * FROM procurement_notices ORDER BY published_at DESC')->fetchAll();
$pageTitle = 'Procurement Notices';
include __DIR__ . '/includes/layout-header.php';
?>
<div class="admin-card mb-6">
  <h3><?= $editing ? 'Edit Notice' : 'Add Notice' ?></h3>
  <form method="post">
    <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
    <?php if ($editing): ?><input type="hidden" name="id" value="<?= (int)$editing['id'] ?>"><?php endif; ?>
    <div class="field-row mb-4">
      <div class="field"><label>Title</label><input type="text" name="title" value="<?= e($editing['title'] ?? '') ?>" required></div>
      <div class="field"><label>Slug</label><input type="text" name="slug" value="<?= e($editing['slug'] ?? '') ?>" placeholder="auto-generated if blank"></div>
    </div>
    <div class="field mb-4"><label>Description</label><textarea name="description" rows="3"><?= e($editing['description'] ?? '') ?></textarea></div>
    <div class="field-row mb-4">
      <div class="field"><label>Published Date</label><input type="date" name="published_at" value="<?= e($editing ? date('Y-m-d', strtotime($editing['published_at'])) : date('Y-m-d')) ?>"></div>
      <div class="field"><label>Deadline</label><input type="date" name="deadline" value="<?= e($editing && $editing['deadline'] ? date('Y-m-d', strtotime($editing['deadline'])) : '') ?>"></div>
    </div>
    <button type="submit" class="btn btn-primary"><?= $editing ? 'Update' : 'Add' ?> Notice</button>
    <?php if ($editing): ?><a href="/admin/procurement.php" class="btn btn-outline">Cancel</a><?php endif; ?>
  </form>
</div>
<div class="admin-card" style="padding:0;overflow-x:auto;">
  <table class="admin-table">
    <thead><tr><th>Title</th><th>Published</th><th>Deadline</th><th></th></tr></thead>
    <tbody>
      <?php foreach ($notices as $n): ?>
        <tr>
          <td><?= e($n['title']) ?></td>
          <td><?= date('M j, Y', strtotime($n['published_at'])) ?></td>
          <td><?= $n['deadline'] ? date('M j, Y', strtotime($n['deadline'])) : '—' ?></td>
          <td class="flex gap-2">
            <a href="/admin/procurement.php?edit=<?= (int)$n['id'] ?>" class="btn btn-outline btn-sm">Edit</a>
            <a href="/admin/procurement.php?delete=<?= (int)$n['id'] ?>&csrf=<?= e(csrf_token()) ?>" class="btn btn-outline btn-sm" onclick="return confirm('Delete this notice?')">Delete</a>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>
<?php include __DIR__ . '/includes/layout-footer.php'; ?>
