<?php
// admin_broadcast.php (Contoh Sederhana)
session_start();
include 'config.php';

// Pastikan yang akses adalah Admin (Sesuaikan dengan logic login admin Anda)
// if(!isset($_SESSION['admin_logged_in'])) { header("Location: admin_login.php"); exit(); }

// HANDLE TAMBAH / EDIT / HAPUS
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] == 'add') {
            $title = $conn->real_escape_string($_POST['title']);
            $msg = $conn->real_escape_string($_POST['message']);
            $conn->query("INSERT INTO admin_messages (title, message) VALUES ('$title', '$msg')");
        } 
        elseif ($_POST['action'] == 'edit') {
            $id = intval($_POST['id']);
            $title = $conn->real_escape_string($_POST['title']);
            $msg = $conn->real_escape_string($_POST['message']);
            $conn->query("UPDATE admin_messages SET title='$title', message='$msg' WHERE id=$id");
        } 
        elseif ($_POST['action'] == 'delete') {
            $id = intval($_POST['id']);
            $conn->query("DELETE FROM admin_messages WHERE id=$id");
            $conn->query("DELETE FROM message_reads WHERE message_id=$id"); // Hapus data read terkait
        }
    }
    header("Location: admin_broadcast.php"); exit();
}

$msgs = $conn->query("SELECT * FROM admin_messages ORDER BY created_at DESC");
?>

<!DOCTYPE html>
<html>
<head><title>Admin Broadcast</title></head>
<body>
    <h1>Kelola Pesan Broadcast</h1>
    
    <form method="POST" style="border:1px solid #ccc; padding:10px; margin-bottom:20px;">
        <h3>Kirim Pesan Baru</h3>
        <input type="hidden" name="action" value="add">
        <input type="text" name="title" placeholder="Judul Pesan" required style="width:100%; margin-bottom:10px;"><br>
        <textarea name="message" placeholder="Isi Pesan..." required style="width:100%; height:100px;"></textarea><br>
        <button type="submit">Kirim Broadcast</button>
    </form>

    <table border="1" cellpadding="10" cellspacing="0" width="100%">
        <tr>
            <th>Tanggal</th>
            <th>Judul</th>
            <th>Isi</th>
            <th>Aksi</th>
        </tr>
        <?php while($row = $msgs->fetch_assoc()): ?>
        <tr>
            <td><?php echo $row['created_at']; ?></td>
            <td><?php echo $row['title']; ?></td>
            <td><?php echo nl2br($row['message']); ?></td>
            <td>
                <form method="POST" onsubmit="return confirm('Hapus pesan ini?');">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                    <button type="submit" style="color:red;">Hapus</button>
                </form>
            </td>
        </tr>
        <?php endwhile; ?>
    </table>
</body>
</html>