<?php
$page_title = "নোটিশ পাঠান";
require_once 'includes/auth_check.php';
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'];
    $notice_message = $_POST['message'];

    if (!empty($title) && !empty($notice_message)) {
        // Fetch all user IDs
        $users_result = $conn->query("SELECT id FROM users WHERE role = 'user'");
        $conn->begin_transaction();
        try {
            $stmt = $conn->prepare("INSERT INTO notifications (user_id, title, message) VALUES (?, ?, ?)");
            while ($user = $users_result->fetch_assoc()) {
                $user_id = $user['id'];
                $stmt->bind_param("iss", $user_id, $title, $notice_message);
                $stmt->execute();
            }
            $conn->commit();
            $message = '<div class="alert alert-success">সকল ব্যবহারকারীর কাছে নোটিশ সফলভাবে পাঠানো হয়েছে।</div>';
        } catch (Exception $e) {
            $conn->rollback();
            $message = '<div class="alert alert-danger">নোটিশ পাঠাতে সমস্যা হয়েছে।</div>';
        }
        $stmt->close();
    } else {
        $message = '<div class="alert alert-warning">শিরোনাম এবং বার্তা উভয়ই পূরণ করুন।</div>';
    }
}

include 'includes/header.php';
?>
<div class="container-fluid">
    <h2 class="mb-4">সকল ব্যবহারকারীকে নোটিশ পাঠান</h2>
    <?php echo $message; ?>
    <div class="card"><div class="card-body">
        <form method="POST">
            <div class="mb-3"><label class="form-label">শিরোনাম</label><input type="text" name="title" class="form-control" required></div>
            <div class="mb-3"><label class="form-label">বার্তা</label><textarea name="message" class="form-control" rows="5" required></textarea></div>
            <button type="submit" class="btn btn-primary">নোটিশ পাঠান</button>
        </form>
    </div></div>
</div>
<?php include 'includes/footer.php'; $conn->close(); ?>