<?php
$db = getDB();
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'] ?? '';
    $youtube_url = $_POST['youtube_url'] ?? '';
    $description = $_POST['description'] ?? '';
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    $id = $_POST['id'] ?? '';

    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $message = 'Invalid security token.';
    } else {
        try {
            if ($id) {
                $stmt = $db->prepare("UPDATE announcements SET title=?, youtube_url=?, description=?, sort_order=? WHERE id=?");
                $stmt->execute([$title, $youtube_url, $description, $sort_order, $id]);
                $message = 'Announcement updated successfully.';
            } else {
                $stmt = $db->prepare("INSERT INTO announcements (title, youtube_url, description, sort_order) VALUES (?, ?, ?, ?)");
                $stmt->execute([$title, $youtube_url, $description, $sort_order]);
                $message = 'Announcement added successfully.';
            }
        } catch (PDOException $e) {
            $message = 'Database error: ' . htmlspecialchars($e->getMessage());
        }
    }
}

$announcements = $db->query("SELECT * FROM announcements ORDER BY sort_order ASC")->fetchAll();
$editAnn = null;
if (isset($_GET['edit'])) {
    $stmt = $db->prepare("SELECT * FROM announcements WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $editAnn = $stmt->fetch();
}

include __DIR__ . '/admin_header.php';
?>

<div class="admin-topbar">
    <h2>Manage Announcements</h2>
</div>

<?php if ($message): ?>
<div class="alert alert-success"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>

<div class="admin-card">
    <h3><?= $editAnn ? 'Edit Announcement' : 'Add New Announcement' ?></h3>
    <form method="post">
        <?= csrfField() ?>
        <?php if ($editAnn): ?>
        <input type="hidden" name="id" value="<?= $editAnn['id'] ?>">
        <?php endif; ?>
        <div class="form-group">
            <label>Title</label>
            <input type="text" name="title" value="<?= htmlspecialchars($editAnn['title'] ?? '') ?>" required>
        </div>
        <div class="form-group">
            <label>YouTube URL</label>
            <input type="url" name="youtube_url" value="<?= htmlspecialchars($editAnn['youtube_url'] ?? '') ?>" required>
        </div>
        <div class="form-group">
            <label>Description</label>
            <textarea name="description" rows="3"><?= htmlspecialchars($editAnn['description'] ?? '') ?></textarea>
        </div>
        <div class="form-group">
            <label>Sort Order</label>
            <input type="number" name="sort_order" value="<?= htmlspecialchars($editAnn['sort_order'] ?? '0') ?>">
        </div>
        <button type="submit" class="btn-sm btn-sm-primary"><?= $editAnn ? 'Update' : 'Add' ?> Announcement</button>
        <?php if ($editAnn): ?>
        <a href="/admin/announcements" class="btn-sm btn-sm-success">Cancel</a>
        <?php endif; ?>
    </form>
</div>

<div class="admin-card">
    <h3>All Announcements</h3>
    <table>
        <thead>
            <tr><th>Title</th><th>YouTube URL</th><th>Order</th><th>Actions</th></tr>
        </thead>
        <tbody>
        <?php foreach ($announcements as $a): ?>
            <tr>
                <td><?= htmlspecialchars($a['title']) ?></td>
                <td><a href="<?= htmlspecialchars($a['youtube_url']) ?>" target="_blank"><?= htmlspecialchars(substr($a['youtube_url'], 0, 40)) ?>...</a></td>
                <td><?= $a['sort_order'] ?></td>
                <td class="actions">
                    <a href="/admin/announcements?edit=<?= $a['id'] ?>" class="btn-sm btn-sm-primary">Edit</a>
                    <form method="post" action="/admin/delete" style="display:inline" onsubmit="return confirm('Are you sure?')"><input type="hidden" name="type" value="announcements"><input type="hidden" name="delete_id" value="<?= $a['id'] ?>"><?= csrfField() ?><button type="submit" class="btn-sm btn-sm-danger">Delete</button></form>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php include __DIR__ . '/admin_footer.php'; ?>
