<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
$pageTitle = 'Manage Ads';
include 'header.php';

$conn = getConnection();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = sanitize($_POST['title']);
    $content = sanitize($_POST['content']);
    $reward = floatval($_POST['reward']);
    $conn->query("INSERT INTO ads (title, content, reward) VALUES ('$title', '$content', $reward)");
    setFlash('success', 'Ad created!');
    redirect('ads.php');
}

$ads = $conn->query("SELECT * FROM ads ORDER BY created_at DESC");
?>
<div class="container">
    <div class="card">
        <h3>📺 Manage Ads</h3>
        <form method="POST" style="background:#f9f9f9;padding:20px;border-radius:8px;margin:20px 0">
            <div class="form-group"><label>Ad Title</label><input type="text" name="title" class="form-control" required></div>
            <div class="form-group"><label>Content</label><textarea name="content" class="form-control" rows="3" required></textarea></div>
            <div class="form-group"><label>Reward (KSH)</label><input type="number" step="0.01" name="reward" class="form-control" required></div>
            <button type="submit" class="btn btn-success">Create Ad</button>
        </form>
        <table class="table">
            <tr><th>Title</th><th>Reward</th><th>Status</th><th>Actions</th></tr>
            <?php while ($ad = $ads->fetch_assoc()): ?>
            <tr>
                <td><?php echo htmlspecialchars($ad['title']); ?></td>
                <td>Ksh <?php echo number_format($ad['reward'], 2); ?></td>
                <td><?php echo $ad['status']; ?></td>
                <td><a href="?delete=<?php echo $ad['id']; ?>" class="btn btn-danger" style="padding:5px 10px">Delete</a></td>
            </tr>
            <?php endwhile; ?>
        </table>
    </div>
</div>
<?php include 'footer.php'; ?>
