<button id="save-list-btn" style="margin-top: 10px;">💾 Save Emoji List</button>

<script>
document.getElementById('save-list-btn').addEventListener('click', function () {
    const instanceInput = document.getElementById('instance');
    const domain = instanceInput ? instanceInput.value.trim() : 'emojis';

    if (!domain) {
        alert("Please enter a valid instance domain first.");
        return;
    }

    // Get all emojis in the grid
    const emojis = document.querySelectorAll('.emoji-item');

    if (!emojis.length) {
        alert("No emojis found to save.");
        return;
    }

    let lines = [];

    emojis.forEach(emojiItem => {
        const shortcodeElem = emojiItem.querySelector('small');
        const imgElem = emojiItem.querySelector('img');

        if (shortcodeElem && imgElem) {
            const shortcode = shortcodeElem.textContent.replace(/:/g, '').trim();
            const url = imgElem.getAttribute('src');
            lines.push(`${shortcode} ${url}`);
        }
    });

    const blob = new Blob([lines.join('\n')], { type: 'text/plain' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = `${domain}.txt`;
    a.style.display = 'none';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
});
</script>



<?php
// Enable error reporting for debugging
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Function to fetch content via cURL
function fetch_via_curl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36');
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

// Function to fetch emojis from the given instance URL
function fetch_emojis($instance) {
    // Try fetching from Emojos API
    $url = "https://emojos.in/$instance";
    $html = fetch_via_curl($url);

    // If the first request fails, try fetching from the Mastodon-compatible endpoint
    if (!$html) {
        $url = "https://$instance/api/v1/custom_emojis";
        $html = fetch_via_curl($url);
        
        // If it's JSON (Mastodon API), parse it
        if ($html && ($data = json_decode($html, true))) {
            $emojis = [];
            foreach ($data as $emoji) {
                $emojis[] = [
                    'url' => $emoji['url'],
                    'shortcode' => $emoji['shortcode']
                ];
            }
            return $emojis;
        }
    }

    // If still no content, return null
    if (!$html) {
        return null;
    }

    // Use DOMDocument to parse the HTML and extract emoji data
    $dom = new DOMDocument();
    @$dom->loadHTML($html);

    $emojis = [];
    $emojiElements = $dom->getElementsByTagName('div');

    foreach ($emojiElements as $element) {
        $imgElement = $element->getElementsByTagName('img');
        $ddElement = $element->getElementsByTagName('dd');

        // Check if we have the necessary elements
        if ($imgElement->length > 0 && $ddElement->length > 0) {
            $url = $imgElement->item(0)->getAttribute('src');
            $shortcode = trim($ddElement->item(0)->nodeValue);

            $emojis[] = ['url' => $url, 'shortcode' => $shortcode];
        }
    }

    return $emojis;
}

// Function to download and cache emoji
function cache_emoji($url, $shortcode) {
    $extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
    if (empty($extension)) {
        $extension = 'png'; // default extension
    }
    
    $filename = preg_replace('/[^a-zA-Z0-9_-]/', '', $shortcode) . '.' . $extension;
    $cache_dir = __DIR__ . '/emoji_cache/';
    
    if (!file_exists($cache_dir)) {
        mkdir($cache_dir, 0755, true);
    }
    
    $cache_path = $cache_dir . $filename;
    
    // If not cached or cache is older than 1 day
    if (!file_exists($cache_path) || (time() - filemtime($cache_path) > 86400)) {
        $image_data = fetch_via_curl($url);
        if ($image_data) {
            file_put_contents($cache_path, $image_data);
        }
    }
    
    if (file_exists($cache_path)) {
        return [
            'path' => $cache_path,
            'filename' => $filename,
            'mime' => mime_content_type($cache_path)
        ];
    }
    
    return false;
}

$filtered = [];
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Handle emoji download
    if (isset($_POST['download_single'])) {
        $url = $_POST['url'];
        $shortcode = $_POST['shortcode'];
        
        $cached = cache_emoji($url, $shortcode);
        if ($cached) {
            header('Content-Type: ' . $cached['mime']);
            header('Content-Disposition: attachment; filename="' . $cached['filename'] . '"');
            readfile($cached['path']);
            exit;
        } else {
            header("HTTP/1.0 404 Not Found");
            echo "Failed to download emoji";
            exit;
        }
    }
    
    // Handle ZIP download
    if (isset($_POST['download_all'])) {
        $instance = $_POST['instance'];
        $keyword = $_POST['keyword'];
        
        // Fetch emojis again to ensure we have fresh data
        $emojis = fetch_emojis($instance);
        if ($emojis !== null) {
            $filtered = [];
            foreach ($emojis as $emoji) {
                if (empty($keyword) || stripos($emoji['shortcode'], $keyword) !== false) {
                    $filtered[] = $emoji;
                }
            }
        }
        
        if (!empty($filtered)) {
            $zip = new ZipArchive();
            $zip_filename = 'emojis_' . time() . '.zip';
            $zip_path = sys_get_temp_dir() . '/' . $zip_filename;
            
            if ($zip->open($zip_path, ZipArchive::CREATE) === TRUE) {
                foreach ($filtered as $emoji) {
                    $cached = cache_emoji($emoji['url'], $emoji['shortcode']);
                    if ($cached) {
                        $zip->addFile($cached['path'], $cached['filename']);
                    }
                }
                $zip->close();
                
                header('Content-Type: application/zip');
                header('Content-Disposition: attachment; filename="' . $zip_filename . '"');
                header('Content-Length: ' . filesize($zip_path));
                readfile($zip_path);
                unlink($zip_path);
                exit;
            }
        }
        
        header("HTTP/1.0 404 Not Found");
        echo "Failed to create ZIP file";
        exit;
    }

    // Handle the form submission for searching
    $instance = isset($_POST['instance']) ? trim($_POST['instance']) : '';
    $keyword = isset($_POST['keyword']) ? trim($_POST['keyword']) : '';

    if (empty($instance)) {
        $error = "Instance URL is required.";
    } else {
        // Fetch emojis from the instance URL
        $emojis = fetch_emojis($instance);
        if ($emojis === null) {
            $error = "Failed to fetch from $instance";
        } else {
            // Filter emojis by keyword
            foreach ($emojis as $emoji) {
                if (empty($keyword) || stripos($emoji['shortcode'], $keyword) !== false) {
                    $filtered[] = $emoji;
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Emoji Fetcher</title>
    <style>
        .download-link {
            cursor: pointer;
            color: blue;
            text-decoration: underline;
        }
        .download-link:hover {
            color: darkblue;
        }
        .emoji-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
            gap: 15px;
            margin: 20px 0;
        }
        .emoji-item {
            text-align: center;
        }
        .download-form {
            display: inline;
        }
    </style>
</head>
<body>

<h2>Emoji Fetcher</h2>

<!-- Display errors if any -->
<?php if ($error): ?>
    <p style="color: red;"><?= htmlspecialchars($error) ?></p>
<?php endif; ?>

<!-- Form to get instance URL and keyword -->
<form method="POST">
    <label for="instance">Instance URL (e.g. blahaj.zone):</label><br>
    <input type="text" name="instance" id="instance" required value="<?= isset($_POST['instance']) ? htmlspecialchars($_POST['instance']) : '' ?>"><br><br>

    <label for="keyword">Keyword:</label><br>
    <input type="text" name="keyword" id="keyword" value="<?= isset($_POST['keyword']) ? htmlspecialchars($_POST['keyword']) : '' ?>"><br><br>

    <button type="submit">Submit</button>
</form>

<?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && $filtered): ?>
    <h3>Matched Emojis (<?= count($filtered) ?>)</h3>
    
    <form method="POST" class="download-form">
        <input type="hidden" name="download_all" value="1">
        <input type="hidden" name="instance" value="<?= htmlspecialchars($_POST['instance']) ?>">
        <input type="hidden" name="keyword" value="<?= htmlspecialchars($_POST['keyword']) ?>">
        <button type="submit" style="margin-bottom: 15px; padding: 8px 15px; background: #4CAF50; color: white; text-decoration: none; border-radius: 4px; border: none; cursor: pointer;">
            Download All as ZIP
        </button>
    </form>
    
    <div class="emoji-grid">
        <?php foreach ($filtered as $emoji): ?>
            <div class="emoji-item">
                <img src="<?= htmlspecialchars($emoji['url']) ?>" alt="<?= htmlspecialchars($emoji['shortcode']) ?>" width="64" height="64"><br>
                <small>:<?= htmlspecialchars($emoji['shortcode']) ?>:</small><br>
                <form method="POST" class="download-form">
                    <input type="hidden" name="download_single" value="1">
                    <input type="hidden" name="url" value="<?= htmlspecialchars($emoji['url']) ?>">
                    <input type="hidden" name="shortcode" value="<?= htmlspecialchars($emoji['shortcode']) ?>">
                    <button type="submit" style="background: none; border: none; color: blue; text-decoration: underline; cursor: pointer;">
                        Download
                    </button>
                </form>
            </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

</body>
</html>
