<?php

function fetchAccountId($instance, $username, $platform) {
    $url = "https://$instance/api/v1/accounts/lookup?acct=$username";
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    if ($response === false) {
        die("Error fetching account ID from $instance");
    }

    $data = json_decode($response, true);

    return $data['id'] ?? null;
}

function fetchLatestToots($instance, $accountId, $count = 5) {
    $url = "https://$instance/api/v1/accounts/$accountId/statuses?limit=$count";
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    if ($response === false) {
        die("Error fetching toots from $instance");
    }

    return json_decode($response, true);
}

function fetchBackgroundImageForAkkoma($instance, $username) {
    $url = "https://$instance/api/v1/accounts/$username";
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    if ($response === false) {
        die("Error fetching account data from $instance");
    }

    $data = json_decode($response, true);

    return $data['header'] ?? 'default-background.jpg'; // Use a default if no header image
}

function fetchBackgroundImageForMastodon($instance, $username) {
    $rssUrl = "https://$instance/@$username.rss";
    
    $rss = simplexml_load_file($rssUrl);
    
    if ($rss === false) {
        die("Error fetching or parsing RSS feed from $instance");
    }

    $imageUrl = (string)$rss->channel->image->url;
    
    // Ensure image URL is valid
    return filter_var($imageUrl, FILTER_VALIDATE_URL) ? $imageUrl : 'default-background.jpg';
}

function embedYouTube($url) {
    if (preg_match('/(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?v=([^\&\?\/]+)/', $url, $matches) ||
        preg_match('/(?:https?:\/\/)?youtu\.be\/([^\&\?\/]+)/', $url, $matches)) {
        $youtubeId = $matches[1];
        return "<iframe width='560' height='315' src='https://www.youtube.com/embed/$youtubeId' frameborder='0' allowfullscreen></iframe>";
    }
    return '';
}

function embedPixiv($url) {
    if (preg_match('/(?:https?:\/\/)?(?:www\.)?pixiv\.net\/en\/artworks\/(\d+)/', $url, $matches)) {
        $pixivId = $matches[1];
        return "<div><img src='https://embed.pixiv.net/decorate.php?illust_id=$pixivId&mode=sns-automator' width='50%'></div>";
    }
    return '';
}

function displayToots($toots, $backgroundImage) {
    foreach ($toots as $toot) {
        $username = $toot['account']['username'];
        $displayName = $toot['account']['display_name'];
        $instance = parse_url($toot['account']['url'], PHP_URL_HOST);
        $profileUrl = $toot['account']['url'];
        $createdAt = date("F j, Y, g:i a", strtotime($toot['created_at'])); // Format date
        $profileImage = $toot['account']['avatar']; // Get the profile avatar image URL

        // Style for background with 60% opacity using the specified background image
        echo "<div style='position: relative; padding: 20px; margin-bottom: 20px; background-color: rgba(255, 255, 255, 0.9); border-radius: 10px; overflow: hidden;'>";
        // Create a background div for the background image with opacity 0.6
        echo "<div style='position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-image: url(\"$backgroundImage\"); background-size: cover; background-position: center; opacity: 0.6;'></div>";

        // Display the username as a clickable link to their profile
        echo "<h3 style='position: relative; z-index: 2;'><a href='$profileUrl' target='_blank'>$displayName</a> (@$username@$instance)</h3>";
        // Display the toot content
        echo "<p style='position: relative; z-index: 2;'>{$toot['content']}</p>";
        // Display the created date
        echo "<p style='position: relative; z-index: 2;'><small>Posted on $createdAt</small></p>";

        // Display media attachments (if any)
        if (!empty($toot['media_attachments'])) {
            foreach ($toot['media_attachments'] as $media) {
                switch ($media['type']) {
                    case 'image':
                        echo "<img src='{$media['url']}' alt='image' style='max-width: 45%; height: auto; position: relative; z-index: 2;'><br>";
                        break;
                    case 'video':
                    case 'gifv':
                        echo "<video controls style='max-width: 100%; height: auto; position: relative; z-index: 2;'>
                                <source src='{$media['url']}' type='{$media['mime_type']}'>
                              Your browser does not support the video tag.
                              </video><br>";
                        break;
                    case 'audio':
                        echo "<audio controls style='max-width: 100%; position: relative; z-index: 2;'>
                                <source src='{$media['url']}' type='{$media['mime_type']}'>
                              Your browser does not support the audio element.
                              </audio><br>";
                        break;
                }
            }
        }

        // Check for links in toot content and embed YouTube/Pixiv
        if (preg_match_all('/https?:\/\/[^\s]+/', $toot['content'], $links)) {
            foreach ($links[0] as $link) {
                // Embed YouTube
                $youtubeEmbed = embedYouTube($link);
                if ($youtubeEmbed) {
                    echo "<div style='position: relative; z-index: 2;'>$youtubeEmbed</div>";
                }

                // Embed Pixiv
                $pixivEmbed = embedPixiv($link);
                if ($pixivEmbed) {
                    echo "<div style='position: relative; z-index: 2;'>$pixivEmbed</div>";
                }
            }
        }

        echo "</div>"; // Close toot container
    }
}

// Define the usernames, their respective instances, and platforms
$accounts = [
    ['username' => 'alcea', 'instance' => 'blob.cat', 'platform' => 'akkoma'],
    ['username' => 'alcea', 'instance' => 'animexx.social', 'platform' => 'mastodon'],
    ['username' => 'alcea', 'instance' => 'pawoo.net', 'platform' => 'mastodon']
];

// Arrays to collect image URLs
$backgroundImages = [];

foreach ($accounts as $account) {
    $username = $account['username'];
    $instance = $account['instance'];
    $platform = $account['platform'];

    // Fetch the account ID
    $accountId = fetchAccountId($instance, $username, $platform);

    if ($accountId) {
        // Fetch the latest two toots
        $toots = fetchLatestToots($instance, $accountId, 5);

        // Determine background image based on platform
        if ($platform === 'mastodon') {
            $backgroundImage = fetchBackgroundImageForMastodon($instance, $username);
        } else { // Akkoma
            $backgroundImage = fetchBackgroundImageForAkkoma($instance, $username);
        }

        // Collect background image URL
        $backgroundImages[$username] = $backgroundImage;

        // Display the toots
        displayToots($toots, $backgroundImage);
    } else {
        echo "Failed to fetch account ID for $username@$instance<br>";
    }
}

// Display collected image URLs in a details tag at the page beginning
echo "<details><summary>Background Images</summary><ul>";
foreach ($backgroundImages as $user => $image) {
    echo "<li>$user: <a href='$image' target='_blank'>$image</a></li>";
}
echo "</ul></details>";

?>
