<?php
session_start();
if(!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true){
    header('Location: admin_login.php');
    exit;
}

require_once 'connectiondb.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $exam_id = $_POST['exam_id'] ?? null;
    $notification_text = $_POST['notification_text'] ?? null;
    $notify_all = isset($_POST['notify_all']) ? 1 : 0;

    if ($notification_text) {
        try {
            if ($notify_all) {
                // Separate code path for notify_all notifications
                $stmt = $pdo->prepare("INSERT INTO exam_notifications (exam_id, notification_text, notify_all) VALUES (0, ?, 1)");
                $stmt->execute([$notification_text]);
            } elseif ($exam_id !== null && $exam_id !== '') {
                // Separate code path for exam-specific notifications
                $stmt = $pdo->prepare("INSERT INTO exam_notifications (exam_id, notification_text, notify_all) VALUES (?, ?, 0)");
                $stmt->execute([$exam_id, $notification_text]);
            } else {
                die("Exam must be selected or notify all must be checked.");
            }
        } catch (PDOException $e) {
            die("Failed to add notification: " . $e->getMessage());
        }
    } else {
        die("Notification text is required.");
    }
}

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