<?php
declare(strict_types=1);

date_default_timezone_set('Europe/Rome');

$directory   = __DIR__ . '/';
$statsPath   = __DIR__ . '/downloads.json';
$files       = scandir($directory);
$fileCount   = 0;
$totalSize   = 0;

function formatBytes($bytes, $precision = 2){
  $units = ['B','KB','MB','GB','TB','PB'];
  $bytes = max((float)$bytes, 0);
  $pow   = floor(($bytes ? log($bytes) : 0) / log(1024));
  $pow   = (int)min($pow, count($units) - 1);
  $bytes /= (1 << (10 * $pow));
  return round($bytes, $precision).' '.$units[$pow];
}

// Carica stats (compat vecchio formato)
function loadStats(string $path): array {
  if (!file_exists($path)) return ['total_downloads'=>0, 'total_bytes'=>0, 'files'=>[]];
  $raw = file_get_contents($path);
  $j   = $raw !== false ? json_decode($raw, true) : null;
  if (!is_array($j)) return ['total_downloads'=>0, 'total_bytes'=>0, 'files'=>[]];

  // nuovo formato?
  if (isset($j['files'])) {
    $j['total_downloads'] = (int)($j['total_downloads'] ?? 0);
    $j['total_bytes']     = (int)($j['total_bytes'] ?? 0);
    $j['files']           = is_array($j['files']) ? $j['files'] : [];
    return $j;
  }

  // vecchio formato (mappa filename->count)
  $total = 0;
  $files = [];
  foreach ($j as $name => $cnt) {
    $cnt = (int)$cnt;
    $files[$name] = ['count'=>$cnt, 'bytes'=>0, 'last'=>0];
    $total += $cnt;
  }
  return ['total_downloads'=>$total, 'total_bytes'=>0, 'files'=>$files];
}

$stats = loadStats($statsPath);
$perFile = $stats['files'] ?? [];
$totalDownloadsAllTime = (int)($stats['total_downloads'] ?? 0);
$totalBytesServed      = (int)($stats['total_bytes'] ?? 0);

// Estensioni consentite in listing
$allowedExt = ['wad','pk3','zip','pk7'];

?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>IT Node WAD/PK3 File List — Pizza-Doom</title>
  <link rel="icon" href="/assets/image.png" type="image/x-icon" />
  <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
  <link rel="stylesheet" href="/header.css" />
  <link rel="stylesheet" href="/wadsstyle.css?v=20260804-it-list-size-sort-v2" />
</head>
<body>
  <!-- Header condiviso -->
<header class="panel-header" role="banner">
  <div class="logo">
    <a href="/" aria-label="Home">
      <img src="/assets/image.png" alt="Pizza-Doom Logo" class="logo-img" />
    </a>
  </div>

  <!-- Hamburger: NIENTE onclick inline -->
  <button class="hamburger" id="hamburger"
          aria-label="Menu" aria-controls="mobileMenu" aria-expanded="false">☰</button>

  <!-- Menu desktop (CTA a destra nello stesso nav) -->
  <nav class="menu desktop-menu" aria-label="Main">
    <a href="/rules">Rules and Policies</a>
    <a href="/wads">WADs</a>
    <a href="/servers">Servers</a>
    <a href="/banlist">Banlist</a>
    <a href="/feedback">Feedback</a>
    <a href="https://panel.pizza-doom.it/" class="panel-cta" aria-label="Apri Server Panel">Server Panel</a> <!-- perché: spinta a destra -->
  </nav>
</header>

<!-- Menu mobile -->
<nav class="menu mobile-menu" id="mobileMenu" aria-label="Mobile">
  <a href="/rules">Rules</a>
  <a href="/wads">WADs</a>
  <a href="/servers">Servers</a>
  <a href="/banlist">Banlist</a>
  <a href="/feedback">Feedback</a>
  <a href="https://panel.pizza-doom.it/" class="panel-cta-mobile" aria-label="Apri Server Panel">Server Panel</a>
</nav>
<div id="site-announcement-host"></div>
  <main class="page">
    <div class="container">
      <div class="content">
        <h1 class="wad-page-title">
          <span class="wad-title-node">IT NODE</span>
          <span>WAD/PK3 File List</span>
        </h1>

        <!-- PD_PUBLIC_WAD_NODE_MIRRORS_V1 -->
        <section class="wad-node-overview"
                 aria-label="Pizza-Doom WAD mirrors">

          <div class="wad-current-list">
            <span class="wad-node-badge wad-node-it">
              IT
            </span>

            <div>
              <strong>This file list contains IT node files only</strong>

              <p>
                Every row in the table below refers to the repository
                hosted in Milan, Italy. Files available only on the UK
                node are not included in this list.
              </p>
            </div>
          </div>

          <div class="wad-mirror-title">
            Wadseeker / GetWAD mirrors (IT and UK)
          </div>

          <div class="wad-mirror-grid">
            <a class="wad-mirror-card wad-mirror-it"
               href="https://wads.pizza-doom.it/"
               target="_blank"
               rel="noopener">

              <span class="wad-node-badge wad-node-it">
                IT
              </span>

              <span class="wad-mirror-card-body">
                <strong>IT Mirror</strong>
                <code>https://wads.pizza-doom.it/</code>
                <small>Milan, Italy</small>
              </span>
            </a>

            <a class="wad-mirror-card wad-mirror-uk"
               href="https://wads-uk.pizza-doom.it/"
               target="_blank"
               rel="noopener">

              <span class="wad-node-badge wad-node-uk">
                UK
              </span>

              <span class="wad-mirror-card-body">
                <strong>UK Mirror</strong>
                <code>https://wads-uk.pizza-doom.it/</code>
                <small>Erith, United Kingdom</small>
              </span>
            </a>
          </div>

          <p class="wad-mirror-hint">
            Add both addresses to GetWAD or Wadseeker.
            Prefer the mirror matching the server node.
            The UK mirror can also be opened directly to browse
            the files currently available on Erith.
          </p>
        </section>
        <div class="wad-toolbar">
          <input id="wad-search" type="text" placeholder="Search by name or extension (e.g. .wad, .pk3)" />
          <button id="wad-clear" type="button" aria-label="Clear search">✕</button>
        </div>

        <div class="wad-scroll" aria-label="Files available on the IT node">
          <!-- Header sticky -->
          <div class="wad-head">
            <span class="file-name">File Name</span>
            <span class="file-size">File Size</span>
            <span class="file-modified">Last Modified</span>
            <span class="file-downloads">Downloads</span>
          </div>

          <!-- Lista -->
          <ul class="wad-list">
          <?php
            foreach ($files as $file) {
              $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
              if (
                !is_dir($file) && $file[0] !== '.' &&
                !in_array($file, ['index.php','download.php','downloads.json','download_log.txt'], true) &&
                in_array($ext, $allowedExt, true)
              ) {
                $fileCount++;
                $filePath = $directory . $file;
                $fileSize = filesize($filePath) ?: 0;
                $fileDate = date('Y-m-d H:i:s', filemtime($filePath) ?: time());
                $totalSize += $fileSize;

                $count = isset($perFile[$file]['count']) ? (int)$perFile[$file]['count'] : 0;
                $badgeClass = "badge-".$ext;

                echo '<li class="wad-row">
                        <span class="file-name">
                          <a href="download.php?file='.htmlspecialchars($file, ENT_QUOTES).'">
                            <span class="file-badge '.$badgeClass.'">'.strtoupper($ext).'</span>'.htmlspecialchars($file).'
                          </a>
                        </span>
                        <span class="file-size" data-bytes="'.$fileSize.'">'.formatBytes($fileSize).'</span>
                        <span class="file-modified" data-timestamp="'.(filemtime($filePath) ?: time()).'">'.$fileDate.'</span>
                        <span class="file-downloads" data-downloads="'.$count.'">'.$count.'</span>
                      </li>';
              }
            }
          ?>
          </ul>
        </div>
      </div>
    </div>

    <div class="stats-footer">
      <p>IT node files: <?php echo $fileCount; ?></p>
      <p>IT node total size: <?php echo formatBytes($totalSize); ?></p>
      <p>IT mirror downloads: <?php echo number_format($totalDownloadsAllTime); ?></p>
      <p>IT mirror data served: <?php echo formatBytes($totalBytesServed); ?></p>
      <?php
		$tz = new DateTimeZone('Europe/Rome');
		$now = new DateTime('now', $tz);
		$offset = $tz->getOffset($now); // secondi
		$hours = $offset / 3600;
		$sign = $hours >= 0 ? '+' : '-';
		?>
		<p style="opacity:.8">
		  Times are in UTC<?php echo $sign . str_pad((string)abs($hours), 2, '0', STR_PAD_LEFT); ?>:00 (Europe/Rome).
		</p>
    </div>
  </main>

<?php include $_SERVER['DOCUMENT_ROOT'].'/includes/footer.php'; ?>

  <script src="/header.js"></script>
  <script>
  (function(){
    const q = document.getElementById('wad-search');
    const clear = document.getElementById('wad-clear');
    const rows = Array.from(document.querySelectorAll('.wad-row'));
    const headers = Array.from(document.querySelectorAll('.wad-head span'));

    function filter(){
      const v = (q.value || '').trim().toLowerCase();
      rows.forEach(li=>{
        const name = li.querySelector('.file-name').textContent.toLowerCase();
        li.style.display = (!v || name.includes(v)) ? '' : 'none';
      });
    }
    q.addEventListener('input', filter);
    clear.addEventListener('click', ()=>{ q.value=''; filter(); q.focus(); });

    // Ordinamento colonne
    let dir = 1, last = -1;
    headers.forEach((h,idx)=>{
      h.style.cursor='pointer';
      h.addEventListener('click', ()=>{
        if(idx===last) dir*=-1; else { dir=1; last=idx; }
        const ul = h.closest('.wad-scroll').querySelector('.wad-list');
        const items = Array.from(ul.querySelectorAll('.wad-row'));
        const get  = el => el.children[idx].textContent.trim();
        const num  = s  => parseFloat((s||'').replace(/[^\d.]/g,'')) || 0;
        items.sort((a,b)=>{
          let A=get(a), B=get(b), cmp=0;
          if(idx===1) {
            // Usa i byte reali: il testo formattato (KB/MB/GB) non e' ordinabile.
            cmp = Number(a.children[idx].dataset.bytes || 0) -
                  Number(b.children[idx].dataset.bytes || 0);
          } else if(idx===2) {
            cmp = Number(a.children[idx].dataset.timestamp || 0) -
                  Number(b.children[idx].dataset.timestamp || 0);
          } else if(idx===3) {
            cmp = Number(a.children[idx].dataset.downloads || num(A)) -
                  Number(b.children[idx].dataset.downloads || num(B));
          } else {
            cmp = A.localeCompare(B, undefined, {numeric: true, sensitivity: 'base'});
          }
          return dir*cmp;
        });
        items.forEach(li=>ul.appendChild(li));
        headers.forEach(x=>x.classList.remove('sorted','desc'));
        h.classList.add('sorted'); if(dir<0) h.classList.add('desc');
      });
    });
  })();
  </script>
</body>
</html>
