<?php
ini_set('memory_limit', '512M');
set_time_limit(0);

if (isset($_GET['download_all'])) {
    $rootPath = realpath('.');
    $zip = new ZipArchive();
    $zipFile = 'archive.zip';
    if ($zip->open($zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
        $filesIterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($rootPath, FilesystemIterator::SKIP_DOTS),
            RecursiveIteratorIterator::LEAVES_ONLY
        );
        foreach ($filesIterator as $name => $file) {
            if (!$file->isDir()) {
                $filePath = $file->getRealPath();
                $relativePath = substr($filePath, strlen($rootPath) + 1);
                if ($relativePath !== $zipFile) {
                    $zip->addFile($filePath, $relativePath);
                }
            }
        }
        $zip->close();
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="' . $zipFile . '"');
        header('Content-Length: ' . filesize($zipFile));
        readfile($zipFile);
        unlink($zipFile);
        exit;
    }
}

// NY iterator för listan i HTML
$fileList = scandir('.');
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Index of /</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>Index of /</h1>
  <p>
    <a class="download-link" href="?download_all=1" aria-label="Download all visible files as one ZIP archive">Download all as ZIP</a>
    <a class="download-link" href="systeminfo.php" aria-label="Show CPU, GPU, RAM and other server details">Systeminfo</a>
  </p>
  <div class="table-wrap">
    <table>
      <thead>
        <tr><th>File Name</th><th>File Size</th><th>Date</th></tr>
      </thead>
      <tbody>
<?php foreach ($fileList as $file): ?>
  <?php 
    if ($file != '.' && $file != '..') {
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if (in_array($ext, ['php','html','css','js'])) continue;
        if ($file === 'archive.zip' || $file === '.htaccess') continue;
  ?>
      <tr>
        <td data-label="File Name"><a href="<?= rawurlencode($file) ?>"><?= htmlspecialchars($file) ?></a></td>
        <td data-label="File Size"><?= is_file($file) ? number_format(filesize($file), 0, '.', ' ') . ' B' : '-' ?></td>
        <td data-label="Date"><?= date("Y-m-d H:i:s", filemtime($file)) ?></td>
      </tr>
  <?php } ?>
<?php endforeach; ?>

      </tbody>
    </table>
  </div>
</body>
</html>
