<?php
$dir = __DIR__;
$self = basename(__FILE__);

function collectFiles(string $dir, string $self): array {
    $files = [];
    foreach (scandir($dir) as $entry) {
        if ($entry === '.' || $entry === '..') {
            continue;
        }
        if ($entry === $self || $entry === 'index.html') {
            continue;
        }

        $path = $dir . DIRECTORY_SEPARATOR . $entry;
        if (is_file($path) && is_readable($path)) {
            $files[] = [
                'name' => $entry,
                'size' => filesize($path),
                'mtime' => filemtime($path),
            ];
        }
    }

    usort($files, static function ($a, $b) {
        return strnatcasecmp($a['name'], $b['name']);
    });

    return $files;
}

if (isset($_GET['download'])) {
    $requested = basename((string)$_GET['download']);
    $path = $dir . DIRECTORY_SEPARATOR . $requested;

    if (!is_file($path) || !is_readable($path)) {
        http_response_code(404);
        echo 'File non trovato.';
        exit;
    }

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . rawurlencode($requested) . '"');
    header('Content-Length: ' . filesize($path));
    header('Cache-Control: no-cache, must-revalidate');
    header('Pragma: public');
    readfile($path);
    exit;
}

if (isset($_GET['list'])) {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode([
        'files' => collectFiles($dir, $self),
        'generated_at' => gmdate('c'),
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$files = collectFiles($dir, $self);

function formatBytes(int $bytes): string {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $size = (float)$bytes;
    $i = 0;
    while ($size >= 1024 && $i < count($units) - 1) {
        $size /= 1024;
        $i++;
    }
    return number_format($size, $i === 0 ? 0 : 1, ',', '.') . ' ' . $units[$i];
}
?>
<!doctype html>
<html lang="it">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="refresh" content="5" />
  <title>Download file</title>
  <style>
    body { font-family: Arial, sans-serif; margin: 24px; background: #f4f6f8; color: #1f2937; }
    .wrap { max-width: 900px; margin: 0 auto; background: #fff; border: 1px solid #e5e7eb; border-radius: 10px; padding: 20px; }
    h1 { margin-top: 0; }
    table { width: 100%; border-collapse: collapse; }
    th, td { text-align: left; border-bottom: 1px solid #e5e7eb; padding: 10px 6px; }
    th { font-size: 14px; color: #6b7280; }
    .download { color: #065f46; font-weight: 700; text-decoration: none; }
    .download:hover { text-decoration: underline; }
    .empty { padding: 14px 8px; color: #6b7280; }
  </style>
</head>
<body>
  <div class="wrap">
    <h1>File disponibili</h1>
    <p>Elenco aggiornato automaticamente ogni 5 secondi.</p>

    <table>
      <thead>
        <tr>
          <th>Nome file</th>
          <th>Dimensione</th>
          <th>Modificato</th>
          <th>Download</th>
        </tr>
      </thead>
      <tbody>
        <?php if (!$files): ?>
          <tr><td class="empty" colspan="4">Nessun file disponibile.</td></tr>
        <?php else: ?>
          <?php foreach ($files as $file): ?>
            <tr>
              <td><?= htmlspecialchars($file['name'], ENT_QUOTES, 'UTF-8') ?></td>
              <td><?= formatBytes((int)$file['size']) ?></td>
              <td><?= date('Y-m-d H:i:s', (int)$file['mtime']) ?></td>
              <td>
                <a class="download" href="?download=<?= rawurlencode($file['name']) ?>">Scarica</a>
                |
                <a class="download" href="<?= rawurlencode($file['name']) ?>">Apri diretto</a>
              </td>
            </tr>
          <?php endforeach; ?>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</body>
</html>
