<?php
include('db_connection.php');

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $message_head = $_POST['message_head'];
    $message_body = $_POST['message_body'];
    $roles = $_POST['roles'] ?? [];

    if (empty($roles)) {
        die("Please select at least one role.");
    }

    /* 1. Insert notification */
    $stmt = $conn->prepare("
        INSERT INTO notifications (message_head, message_body)
        VALUES (?, ?)
    ");
    $stmt->bind_param("ss", $message_head, $message_body);
    $stmt->execute();

    $notification_id = $stmt->insert_id;

    /* 2. Assign roles */
    $role_stmt = $conn->prepare("
        INSERT INTO notification_recipients (notification_id, role, status)
        VALUES (?, ?, 'unread')
    ");

    foreach ($roles as $role) {
        $role_stmt->bind_param("is", $notification_id, $role);
        $role_stmt->execute();
    }

    header("Location: admin_dashboard.php");
    exit();
}
?>