<?php
// Here we begin our descent into a magical world of meaningless character sets – because why use actual art?
function getRandomCharacterSet() {
    // Apparently, ASCII art isn't stunning enough without bizarre symbols and numbers, so let's randomize that too.
    $sets = [
        'set1' => '┌┐└┘─│├┤┴┬ ',
        'set2' => '╔╗╚╝═║╠╣╩╦ ',
        'set3' => '╒╕╘╛═│╞╡╧╤ ',
        'set4' => '╓╖╙╜─║╟╢╨╥ ',
        'set5' => '01 ',
        'set6' => '░▒▓█▀▄▌▐   ',
        'set7' => '↑/↓ ',
        'set8' => '▲▼/►◄ ',
        'set9' => '┌┐└┘─│├┤┴┬╔╗╚╝═║╠╣╩╦╒╕╘╛═│╞╡╧╤╓╖╙╜─║╟╢╨╥░▒▓█▀▄▌▐ ',
        'set10' => 'WESEEYOU ',
        'set11' => 'OBEYTHESYSTEM ',
        'set12' => 'HACKTHEPLANET ',
        'set13' => 'CATcat ',
        'set14' => 'CYBER '
    ];
    // Randomly decide which aesthetics to ruin this time.
    $randomSetKey = array_rand($sets);
    return $sets[$randomSetKey];
}

// Create art to showcase the existential void, because everyone needs more ASCII in their life.
function generateRandomAsciiArt($width, $height) {
    $characters = getRandomCharacterSet();
    $totalChars = mb_strlen($characters);
    $art = '';

    for ($i = 0; $i < $height; $i++) {
        for ($j = 0; $j < $width; $j++) {
            $art .= mb_substr($characters, rand(0, $totalChars - 1), 1);
        }
        $art .= "\n";
    }

    return $art;
}

// Surely people still believe color inversion is edgy, right?
function invertColor($r, $g, $b) {
    return [255 - $r, 255 - $g, 255 - $b];
}

// Let’s add some rebellious text to our rebellious art.
function addTextOverlay($image, $text, $fontSize, $posX, $posY, $textColor, $angle = 0) {
    $font = __DIR__ . '/BlockZone.ttf'; // Just hoping this font actually exists here, because who checks these things?
    imagettftext($image, $fontSize, $angle, $posX, $posY, $textColor, $font, $text);
}

// Convert arbitrary characters into an even more arbitrary image.
function asciiArtToImage($fontSize = 16, $lineHeight = 1.0, $overlayX = 0, $overlayY = 0) {
    $fixedWidth = 500;
    $fixedHeight = 500;

    $charactersPerLine = ceil($fixedWidth / $fontSize);
    $lines = ceil($fixedHeight / ($fontSize * $lineHeight));

    $asciiArt = generateRandomAsciiArt($charactersPerLine, $lines);

    $lines = explode("\n", trim($asciiArt));

    $im = imagecreatetruecolor($fixedWidth, $fixedHeight);

    $bgRed = rand(0, 255);
    $bgGreen = rand(0, 255);
    $bgBlue = rand(0, 255);
    $bgColor = imagecolorallocate($im, $bgRed, $bgGreen, $bgBlue);

    list($textRed, $textGreen, $textBlue) = invertColor($bgRed, $bgGreen, $bgBlue);
    $textColor = imagecolorallocate($im, $textRed, $textGreen, $textBlue);

    imagefilledrectangle($im, 0, 0, $fixedWidth, $fixedHeight, $bgColor);

    $font = __DIR__ . '/BlockZone.ttf'; // Again, fingers crossed this is actually here!

    $y = $fontSize;
    foreach ($lines as $line) {
        imagettftext($im, $fontSize, 0, 0, $y, $textColor, $font, $line);
        $y += $fontSize * $lineHeight;
    }

    // Add some profound text to our profound masterpiece.
    addTextOverlay($im, '░▒▓ @void@cyber.ms ▓▒░', 16, $overlayX, $overlayY, $textColor, 90);

    return $im;
}

// Preserve this legacy-defining art in a redundant file format.
function saveImage($im) {
    $filePath = __DIR__ . '/ascii_art.png';
    imagepng($im, $filePath);
    imagedestroy($im);
    return $filePath;
}

// Time to flood Mastodon with more digital enlightenment.
function uploadToMastodon($filePath, $accessToken, $instance) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "$instance/api/v2/media");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $accessToken
    ]);

    // Making sure our precious file gets the respect it deserves.
    $cfile = curl_file_create($filePath, 'image/png', 'ascii_art.png');
    $postData = [
        'file' => $cfile,
        'description' => 'The image has a complex Ascii-Art maze-like pattern, with the text "@void@cyber.ms" written vertically on the right side.'
    ];

    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    $response = curl_exec($ch);
    curl_close($ch);

    if (!$response) {
        return null; // Because why should things go smoothly?
    }

    // Hope the response contains something useful because we never know.
    $responseData = json_decode($response, true);
    return $responseData['id'] ?? null;
}

// Finally, let’s bombard Mastodon with our work of art wrapped in profound status messages.
function postStatusToMastodon($mediaId, $accessToken, $instance, $status) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "$instance/api/v1/statuses");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $accessToken
    ]);

    $postData = [
        'status' => $status,
        'visibility' => 'unlisted',
        'media_ids[]' => $mediaId
    ];

    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_exec($ch);
    curl_close($ch);
}

// Retrieve a random message just because we can.
function getRandomStatus() {
    $fileContent = file(__DIR__ . '/post.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if (!$fileContent) {
        return 'Default status message'; // Always be prepared for disappointment.
    }
    return $fileContent[array_rand($fileContent)];
}

// Check our trivial security measure because who doesn't love gatekeeping?
if (!isset($_GET['key']) || $_GET['key'] !== 'XXXX-XXXX-XXXX') {
    $overlayX = 440;
    $overlayY = 380;

    $image = asciiArtToImage(16, 1.0, $overlayX, $overlayY);
    header('Content-Type: image/png');
    imagepng($image);
    imagedestroy($image);
    exit;
}

// Thrilled to showcase this hidden treasure of keys.
$accessToken = 'YOUR_ACCESS_TOKEN_HERE'; // Insert placeholder for the magical access token.
$instance = 'https://cyber.ms'; // The instance where dreams become reality.

$overlayX = 440;
$overlayY = 380;

$image = asciiArtToImage(16, 1.0, $overlayX, $overlayY);
$filePath = saveImage($image);

$mediaId = uploadToMastodon($filePath, $accessToken, $instance);

if ($mediaId) {
    $randomStatus = getRandomStatus();
    postStatusToMastodon($mediaId, $accessToken, $instance, $randomStatus);
    echo 'Image posted to Mastodon!'; // Triumphantly announce our victory.
} else {
    echo 'Failed to upload image to Mastodon.'; // Accept our fate gracefully.
}
?>