<?php
// Get the query parameters from the URL
$apiKey = $_GET['apikey'];
$userId = $_GET['userid'];
$instanceUrl = $_GET['instanceurl'];

// Define the API endpoint URL
$apiUrl = $instanceUrl . '/api/v1/notifications';

// Create the request options
$options = array(
    'http' => array(
        'header'  => "Authorization: Bearer $apiKey",
        'method'  => 'GET',
        'ignore_errors' => true
    )
);

// Create the context
$context = stream_context_create($options);

// Send the request
$response = file_get_contents($apiUrl, false, $context);

// Check for errors
if ($response === false) {
    echo 'Request failed.';
    exit;
}

// Get the HTTP status code
$httpCode = http_response_code();

// Process the response
if ($httpCode === 200) {
    $notifications = json_decode($response, true);

    // Display the notifications
    echo '<div id="notifications">';
    foreach ($notifications as $notification) {
        $notificationElement = createNotificationElement($notification);
        echo $notificationElement;
    }
    echo '</div>';
} else {
    echo '<div id="error">Request failed. Status: ' . $httpCode . '</div>';
    exit;
}

// Helper function to create a notification element
function createNotificationElement($notification)
{
    $notificationElement = '<div class="notification" style="border: 1px solid #ccc;padding: 10px;margin-bottom: 10px;';
    
    if ($notification['type'] === 'mention') {
        $notificationElement .= 'background-color: lightblue;">';
    } else if ($notification['type'] === 'favourite') {
        $notificationElement .= 'background-color: pink;">';
    } else {
        $notificationElement .= '">';
    }

    $accountElement = '<div class="account">' . ($notification['account']['display_name'] ?? $notification['account']['username']) . '</div>';
    $statusElement = '<div class="status">' . $notification['status']['content'] . '</div>';

    $dateElement = '<div class="date"><a href="' . $notification['status']['url'] . '" target="_blank">' . date('Y-m-d H:i:s', strtotime($notification['created_at'])) . '</a></div>';

    $notificationElement .= $accountElement . $statusElement . $dateElement . '</div>';

    return $notificationElement;
}