<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Content-Type: application/json; charset=UTF-8");

require_once "../../dbcon.php";

function sanitize($data)
{
    global $conn;
    return htmlspecialchars(strip_tags(mysqli_real_escape_string($conn, $data)));
}

$method = $_SERVER["REQUEST_METHOD"];

switch ($method) {

    case "GET":
        // Fetch notifications (filtered by user_id or target_role if provided)
        $user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : null;
        $role = isset($_GET['role']) ? sanitize($_GET['role']) : null;

        $query = "SELECT * FROM notifications";
        $where = [];
        
        if ($user_id) {
            $where[] = "user_id = $user_id";
        }
        if ($role) {
            $where[] = "target_role = '$role'";
        }

        if (!empty($where)) {
            $query .= " WHERE " . implode(" OR ", $where);
        }

        $query .= " ORDER BY id DESC";
        
        $res = mysqli_query($conn, $query);
        $notifications = [];
        while ($row = mysqli_fetch_assoc($res)) {
            $notifications[] = $row;
        }
        echo json_encode(["status" => "success", "data" => $notifications]);
        break;

    case "POST":
        // Allow JSON input or POST fields
        $data = json_decode(file_get_contents("php://input"), true);
        if (!$data) $data = $_POST;

        $title = isset($data['title']) ? sanitize($data['title']) : null;
        $message = isset($data['message']) ? sanitize($data['message']) : null;
        $type = isset($data['type']) ? sanitize($data['type']) : "info";
        $user_id = isset($data['user_id']) ? intval($data['user_id']) : null;
        $target_role = isset($data['target_role']) ? sanitize($data['target_role']) : null;

        if (!$title || !$message) {
            echo json_encode(["status" => "error", "message" => "Title and message are required"]);
            exit;
        }

        $user_val = $user_id ? $user_id : "NULL";
        $role_val = $target_role ? "'$target_role'" : "NULL";

        $q = "INSERT INTO notifications (user_id, title, message, type, target_role) 
              VALUES ($user_val, '$title', '$message', '$type', $role_val)";

        if (mysqli_query($conn, $q)) {
            echo json_encode(["status" => "success", "message" => "Notification added successfully"]);
        } else {
            echo json_encode(["status" => "error", "message" => "Failed to add notification: " . mysqli_error($conn)]);
        }
        break;

    case "DELETE":
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        if ($id <= 0) {
            $data = json_decode(file_get_contents("php://input"), true);
            $id = isset($data['id']) ? intval($data['id']) : 0;
        }

        if ($id <= 0) {
            echo json_encode(["status" => "error", "message" => "Invalid notification ID"]);
            exit;
        }

        if (mysqli_query($conn, "DELETE FROM notifications WHERE id=$id"))
            echo json_encode(["status" => "success", "message" => "Notification deleted successfully"]);
        else
            echo json_encode(["status" => "error", "message" => "Failed to delete notification"]);
        break;

    case "OPTIONS":
        http_response_code(200);
        break;

    default:
        http_response_code(405);
        echo json_encode(["status" => "error", "message" => "Method not allowed"]);
        break;
}

mysqli_close($conn);
?>