<?php error_reporting(0); ?>
<!--past-sizes--->
    <style>#sizes {width: 300px;margin: 20px;}</style>
     PastSizes:<select id="sizes" style="border: none;"></select><a href="/other/Computerstuff/Commands/textsavesizes.php?admin" target="_blank" style="color: transparent;">savesizes</a>
    <script>
        async function fetchSizes() {
            try {
                const today = new Date().toISOString().split('T')[0];
                const url = `sizes.json?date=${today}`;
                const response = await fetch(url);
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const data = await response.json();
                const sizesSelect = document.getElementById('sizes');
                sizesSelect.innerHTML = '';
                Object.entries(data).forEach(([filename, size]) => {
                    const option = document.createElement('option');
                    option.value = filename;
                    option.textContent = `${filename}: ${(size / 1024).toFixed(2)} KB`;
                    sizesSelect.appendChild(option);
                });
                function syncSizesDropdown() {
                    const fileopsSelect = document.getElementById('fileops');
                    const fileopsIndex = fileopsSelect.selectedIndex;
                    if (fileopsIndex >= 0 && fileopsIndex < sizesSelect.options.length) {
                        sizesSelect.selectedIndex = fileopsIndex; // Sync sizes dropdown with fileops index
                    }}
                document.getElementById('fileops').addEventListener('change', syncSizesDropdown);
                syncSizesDropdown();
            } catch (error) {
                console.error('Error fetching or processing the JSON file:', error);}}
        fetchSizes();
    </script>
<!--Synchronize--divs-->
<script>
document.addEventListener('DOMContentLoaded', function () {
    const fileopsDivs = document.querySelectorAll('#fileops div');
    const sizesSelect = document.getElementById('sizes');
    fileopsDivs.forEach((div, index) => {
        div.addEventListener('click', function () {
            sizesSelect.selectedIndex = index;
        });});
    sizesSelect.addEventListener('change', function () {
        const selectedIndex = sizesSelect.selectedIndex;
        fileopsDivs.forEach((div, index) => {
            div.style.backgroundColor = index === selectedIndex ? 'lightblue' : '';);});});
</script>





<details>
  <div id="content"></div>
  <script>
    const baseUrl = "https://alceawis.de"; // Base URL
    fetch("https://alceawis.de/code.html")
      .then(response => response.text())
      .then(data => {
        const start = data.indexOf("CMDS") + 4;
        const end = data.indexOf("CodeDistribution") - 0;
        const content = data.substring(start, end);
        // Create a temporary element to parse the content as HTML
        const tempElement = document.createElement("div");
        tempElement.innerHTML = content;
        // Find and convert relative URLs to absolute URLs
        const relativeUrls = tempElement.querySelectorAll("a[href], img[src]");
        relativeUrls.forEach(url => {
          const originalUrl = url.getAttribute("href") || url.getAttribute("src");
          const absoluteUrl = new URL(originalUrl, baseUrl).href;
          url.setAttribute("href", absoluteUrl);
          url.setAttribute("src", absoluteUrl);
        });
        // Append the modified content to the target element
        document.getElementById("content").appendChild(tempElement);
      });
  </script>
</details><br>


<?php
if (!isset($_GET['user']) || $_GET['user'] !== 'admin') {
    $disableButton = true;
} else {
    $disableButton = false;
}
?>
<script>
    window.addEventListener('DOMContentLoaded', function() {
        var submitButtons = document.querySelectorAll('input[type="submit"]');
        if (<?php echo $disableButton ? 'true' : 'false'; ?>) {
            submitButtons.forEach(function(button) {
                button.disabled = true;
            });
        }
    });
</script>
<?php
$currentDir = __DIR__;
function formatSizeUnits($size) {
    if ($size >= 1073741824) {
        return number_format($size / 1073741824, 2) . ' GB';
    } elseif ($size >= 1048576) {
        return number_format($size / 1048576, 2) . ' MB';
    } elseif ($size >= 1024) {
        return number_format($size / 1024, 2) . ' KB';
    } elseif ($size > 1) {
        return $size . ' bytes';
    } elseif ($size == 1) {
        return $size . ' byte';
    } else {
        return '0 bytes';
    }}
$oldFileSize = 0;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $selectedFile = $_POST['selectedFile'];
    $content = $_POST['content'];
    $filename = basename($selectedFile);
    if (!empty($selectedFile) && !empty($content)) {
        if (file_exists($filename)) {
            $oldFileSize = filesize($filename);}
        $fp = fopen($filename, 'w');
        if (flock($fp, LOCK_EX)) {
            $content = mb_convert_encoding($content, 'UTF-8', 'auto');
            fwrite($fp, $content);
            flock($fp, LOCK_UN);
            fclose($fp);
            $newFileSize = filesize($filename);
            if ($newFileSize < $oldFileSize) {
                $color = 'red';
                $sizeComparison = "decreased to";
            } else {
                $color = 'green';
                $sizeComparison = "remained the same at";
            }
            $sizeDifference = formatSizeUnits($newFileSize);
            echo "<p style='color: $color;'>File saved successfully! Size has $sizeComparison $sizeDifference.</p>";
        } else {
            echo "<p style='color: red;'>Could not lock the file for writing!</p>";
}}}
$files = array_diff(scandir($currentDir), array('.', '..')); // Get the list of files excluding "." and ".."
echo "<form method='POST'>";
echo "<select name='selectedFile' id='fileops'>";
foreach ($files as $index => $file) {
    if (pathinfo($file, PATHINFO_EXTENSION) === 'txt') {
        $fileSize = filesize($file);
        echo "<option value='$file' data-index='$index'>$file (" . formatSizeUnits($fileSize) . ")</option>";
    }
}
echo "</select>";
echo "<input type='submit' value='Load File'>";
echo "</form>";
if (isset($_POST['selectedFile'])) {
    $selectedFile = $_POST['selectedFile'];
    $filename = basename($selectedFile);
    if (file_exists($filename)) {
        $content = file_get_contents($filename);
        // Escape content for HTML display
        $escapedContent = htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
        echo "<br>";
        echo "<form method='POST'>";
        echo "<textarea name='content' rows='120' cols='120'>$escapedContent</textarea><br>";
        echo "<input type='hidden' name='selectedFile' value='$selectedFile'>";
        echo "<input type='submit' value='Save'>";
        echo "</form>";
    }
}
?>

