<?php
// Plugin-Übersicht mit Metadaten (Bild/Beschreibung/Plattform) + Fallback für unbekannte .jar
$dir = __DIR__ . '/downloads/plugins';
$baseUrl = '/downloads/plugins/';

function h($s){
  return htmlspecialchars($s ?? '', ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function humanSize($bytes){
  $bytes = (float)$bytes;
  $units = ['B','KB','MB','GB','TB'];
  $i = 0;
  while ($bytes >= 1024 && $i < count($units) - 1) {
    $bytes /= 1024;
    $i++;
  }
  $dec = ($i === 0) ? 0 : 1;
  return number_format($bytes, $dec, ',', '.') . ' ' . $units[$i];
}

function safeInitial($s){
  $s = trim((string)$s);
  if ($s === '') return '?';
  $s = preg_replace('/[^\pL\pN]+/u', ' ', $s);
  $s = trim($s);
  if ($s === '') return '?';
  if (function_exists('mb_substr') && function_exists('mb_strtoupper')) {
    return mb_strtoupper(mb_substr($s, 0, 1, 'UTF-8'), 'UTF-8');
  }
  return strtoupper(substr($s, 0, 1));
}

function platformLabel($p){
  $p = strtolower(trim((string)$p));
  if ($p === 'paper') return ['Paper', 'paper'];
  if ($p === 'velocity') return ['Velocity', 'velocity'];
  if ($p === 'both' || $p === 'paper+velocity' || $p === 'paper + velocity' || $p === 'paper/velocity') return ['Paper + Velocity', 'both'];
  if ($p === '') return ['Unbekannt', 'unknown'];
  return [trim((string)$p), 'custom'];
}

$meta = [];
$metaError = null;
$metaFile = $dir . '/plugins.json';
if (is_file($metaFile)) {
  $raw = @file_get_contents($metaFile);
  if ($raw === false) {
    $metaError = 'plugins.json konnte nicht gelesen werden.';
  } else {
    $decoded = json_decode($raw, true);
    if (!is_array($decoded)) {
      $metaError = 'plugins.json ist kein gültiges JSON.';
    } else {
      $meta = $decoded;
    }
  }
}

$counts = [];
$countsError = null;
$countsFile = $dir . '/download_counts.json';
if (is_file($countsFile)) {
  $rawC = @file_get_contents($countsFile);
  if ($rawC === false) {
    $countsError = 'download_counts.json konnte nicht gelesen werden.';
  } else {
    $decodedC = json_decode($rawC, true);
    if (!is_array($decodedC)) {
      $countsError = 'download_counts.json ist kein gültiges JSON.';
    } else {
      $counts = $decodedC;
    }
  }
}

$jarsByName = [];

if (is_dir($dir)) {
  foreach (glob($dir . '/*.jar') ?: [] as $path) {
    $name = basename($path);
    $jarsByName[$name] = [
      'file' => $name,
      'path' => $path,
      'url'  => $baseUrl . rawurlencode($name),
      'size' => @filesize($path) ?: 0,
      'mtime'=> @filemtime($path) ?: 0,
    ];
  }
}

$cards = [];
$used = [];

if (is_array($meta)) {
  foreach ($meta as $m) {
    if (!is_array($m)) continue;
    $file = (string)($m['file'] ?? '');
    if ($file === '') continue;

    $title = (string)($m['name'] ?? pathinfo($file, PATHINFO_FILENAME));
    $desc  = (string)($m['description'] ?? '');
    $platform = (string)($m['platform'] ?? '');
    $icon = (string)($m['icon'] ?? '');

    if (isset($jarsByName[$file])) {
      $it = $jarsByName[$file];
      $used[$file] = true;
      $cards[] = array_merge($it, [
        'title' => $title,
        'desc' => $desc,
        'platform' => $platform,
        'icon' => $icon,
        'missing' => false,
      ]);
    } else {
      $cards[] = [
        'file' => $file,
        'url'  => '#',
        'size' => 0,
        'mtime'=> 0,
        'title'=> $title,
        'desc' => $desc,
        'platform' => $platform,
        'icon' => $icon,
        'missing' => true,
      ];
    }
  }
}

foreach ($jarsByName as $file => $it) {
  if (isset($used[$file])) continue;
  $cards[] = array_merge($it, [
    'title' => pathinfo($file, PATHINFO_FILENAME),
    'desc' => '',
    'platform' => '',
    'icon' => '',
    'missing' => false,
  ]);
}

usort($cards, function($a, $b){
  return ($b['mtime'] <=> $a['mtime']) ?: strcmp($a['title'], $b['title']);
});
?>
<!doctype html>
<html lang="de">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <title>Rosewood – Plugin Downloads</title>
  <meta name="description" content="Alle Plugins des Rosewood MMORPG Servers zum Download: Paper, Velocity, Custom Development."/>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Cinzel+Decorative:wght@400;700;900&family=Cinzel:wght@400;600;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="assets/css/style.css"/>
  <style>
    /* ── Plugin List – luftiges Zeilen-Design ── */
    .plugin-list {
      display: flex;
      flex-direction: column;
      margin-top: 0.5rem;
    }

    .plugin-row {
      display: flex;
      align-items: center;
      gap: 1.5rem;
      padding: 1.5rem 1rem;
      border-bottom: 1px solid rgba(255,255,255,.06);
      position: relative;
      transition: background 0.25s;
      border-radius: 12px;
      margin: 0 -1rem;
    }
    .plugin-row:last-child { border-bottom: none; }

    .plugin-row::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%) scaleY(0);
      width: 3px;
      height: 50%;
      border-radius: 0 3px 3px 0;
      background: linear-gradient(to bottom, transparent, var(--pink), transparent);
      transition: transform 0.25s;
    }
    .plugin-row:hover::before { transform: translateY(-50%) scaleY(1); }
    .plugin-row:hover { background: rgba(255,179,209,.035); }
    .plugin-row.is-missing { opacity: 0.4; }

    /* Initials-Kreis */
    .plugin-initial {
      flex-shrink: 0;
      width: 46px;
      height: 46px;
      border-radius: 50%;
      background: rgba(255,179,209,.07);
      border: 1px solid rgba(255,179,209,.18);
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      overflow: hidden;
    }
    .plugin-initial span {
      font-family: 'Cinzel Decorative', serif;
      font-size: 1.1rem;
      font-weight: 700;
      color: var(--pink);
      line-height: 1;
    }
    .plugin-initial img {
      position: absolute;
      inset: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    /* Hauptbereich */
    .plugin-body { flex: 1; min-width: 0; }

    .plugin-headline {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 0.6rem 0.9rem;
      margin-bottom: 0.45rem;
    }
    .plugin-name {
      font-family: 'Cinzel', serif;
      font-size: 1rem;
      font-weight: 700;
      letter-spacing: 0.5px;
      color: var(--text);
    }
    .plugin-desc {
      font-size: 0.85rem;
      color: var(--muted);
      line-height: 1.6;
      margin-bottom: 0.5rem;
    }
    .plugin-sub {
      font-size: 0.75rem;
      color: rgba(255,255,255,.25);
      letter-spacing: 0.2px;
    }
    .plugin-file-name { color: rgba(255,179,209,.38); }

    /* Tags */
    .ptag {
      display: inline-block;
      font-size: 0.7rem;
      padding: 2px 9px;
      border-radius: 20px;
      border: 1px solid var(--border);
      color: var(--muted);
      letter-spacing: 0.3px;
      white-space: nowrap;
    }
    .ptag.paper    { border-color: rgba(108,200,108,.35); color: #8de88d; }
    .ptag.velocity { border-color: rgba(100,160,255,.35); color: #94baff; }
    .ptag.both     { border-color: rgba(200,150,255,.35); color: #d4aaff; }

    /* Aktionen */
    .plugin-actions {
      flex-shrink: 0;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      gap: 0.4rem;
    }
    .dl-count {
      font-size: 0.73rem;
      color: rgba(255,255,255,.25);
      white-space: nowrap;
    }

    .notice-warn {
      background: rgba(255,200,100,.06);
      border: 1px solid rgba(255,200,100,.25);
      border-radius: 10px;
      padding: 0.85rem 1.1rem;
      color: rgba(255,200,100,.9);
      font-size: 0.84rem;
      margin-bottom: 1.5rem;
    }

    @media (max-width: 580px) {
      .plugin-row { flex-wrap: wrap; gap: 1rem; margin: 0; padding: 1.25rem 0; }
      .plugin-actions { flex-direction: row; align-items: center; width: 100%; justify-content: space-between; }
    }
  </style>
</head>
<body>
<nav id="mainNav">
  <a class="nav-logo" href="index.html">Rose<em>wood</em></a>
  <button class="nav-toggle" id="navToggle">Menü</button>
  <ul>
    <li><a href="index.html">Start</a></li>
    <li class="nav-dropdown"><a href="quests.html">Gameplay</a>
      <div class="nav-drop-menu">
        <a href="quests.html">Quests &amp; NPCs</a>
        <a href="dungeons.html">Dungeons</a>
        <a href="wavearena.html">WaveArena</a>
        <a href="items.html">Custom Items</a>
        <a href="progression.html">Progression</a>
        <a href="economy.html">Wirtschaft</a>
      </div>
    </li>
    <li class="nav-dropdown"><a href="galerie.html">Galerie</a>
      <div class="nav-drop-menu">
        <a href="galerie.html#landschaft">Landschaft</a>
        <a href="galerie.html#aktion">Aktion</a>
        <a href="galerie.html#attraktionen">Attraktionen</a>
      </div>
    </li>
    <li class="nav-dropdown"><a href="join.html">Community</a>
      <div class="nav-drop-menu">
        <a href="team.html">Team</a>
        <a href="join.html">Join / Server-Infos</a>
        <a href="rules.html">Regeln</a>
        <a href="roadmap.html">Roadmap</a>
        <a href="events.html">Events</a>
        <a href="log.html">Updates</a>
        <a href="links.html">Links</a>
        <a href="impressum.html">Impressum</a>
        <a href="datenschutz.html">Datenschutz</a>
      </div>
    </li>
    <li><a href="vorgeschichte.html">Vorgeschichte</a></li>
    <li><a href="downloads.html" class="active">Downloads</a></li>
    <li><a href="https://shop.therosewood.de" class="btn primary" style="margin-left:.5rem">Shop</a></li>
  </ul>
</nav>

<section class="page-hero">
  <div class="page-hero-content">
    <p class="section-label fade-in">Ressourcen</p>
    <h1 class="fade-in d1">Plugin Downloads</h1>
    <div class="divider center fade-in d2"></div>
    <div class="badge-row fade-in d2">
      <span class="tag">Paper</span>
      <span class="tag">Velocity</span>
      <span class="tag">Open Source</span>
    </div>
    <p class="fade-in d3">Alle Custom-Plugins des Rosewood Servers zum Download.</p>
  </div>
</section>

<div class="content">
  <div class="card rose fade-in">
    <h2>Plugin-Liste</h2>

    <?php if (!is_dir($dir)): ?>
      <p style="color:var(--muted)"><strong>Ordner fehlt:</strong> <code>/downloads/plugins/</code></p>

    <?php elseif (count($cards) === 0): ?>
      <p style="color:var(--muted)"><strong>Noch keine Plugins vorhanden.</strong></p>
      <p style="color:var(--muted);font-size:.85rem">Lade deine <strong>.jar</strong> nach <code>/downloads/plugins/</code> hoch – dann erscheinen sie hier.</p>

    <?php else: ?>
      <?php if ($metaError): ?>
        <div class="notice-warn"><strong>Hinweis:</strong> <?= h($metaError) ?></div>
      <?php endif; ?>
      <?php if ($countsError): ?>
        <div class="notice-warn"><strong>Hinweis:</strong> <?= h($countsError) ?></div>
      <?php endif; ?>

      <div class="plugin-list">
        <?php foreach ($cards as $it): ?>
          <?php
            [$plLabel, $plClass] = platformLabel($it['platform'] ?? '');
            $title   = (string)($it['title'] ?? $it['file']);
            $desc    = trim((string)($it['desc'] ?? ''));
            $initial = safeInitial($title);
            $icon    = trim((string)($it['icon'] ?? ''));
            $missing = (bool)($it['missing'] ?? false);
          ?>
          <div class="plugin-row <?= $missing ? 'is-missing' : '' ?>">

            <div class="plugin-initial">
              <span><?= h($initial) ?></span>
              <?php if ($icon !== ''): ?>
                <img src="<?= h($icon) ?>" alt="<?= h($title) ?>" loading="lazy" onerror="this.remove();" />
              <?php endif; ?>
            </div>

            <div class="plugin-body">
              <div class="plugin-headline">
                <span class="plugin-name"><?= h($title) ?></span>
                <span class="ptag <?= h($plClass) ?>"><?= h($plLabel) ?></span>
              </div>
              <?php if ($desc !== ''): ?>
                <div class="plugin-desc"><?= h($desc) ?></div>
              <?php endif; ?>
              <div class="plugin-sub">
                <span class="plugin-file-name"><?= h($it['file']) ?></span>
                <?php if (!$missing): ?>
                  &nbsp;&bull;&nbsp;<?= h(humanSize((int)$it['size'])) ?>
                  &nbsp;&bull;&nbsp;<?= h(date('d.m.Y', (int)$it['mtime'])) ?>
                <?php else: ?>
                  &nbsp;&bull;&nbsp;Datei fehlt
                <?php endif; ?>
              </div>
            </div>

            <div class="plugin-actions">
              <?php if (!$missing): ?>
                <?php
                  $dlUrl   = '/download.php?type=plugin&file=' . rawurlencode($it['file']);
                  $dlCount = (int)($counts[$it['file']] ?? 0);
                ?>
                <span class="dl-count"><?= h(number_format($dlCount, 0, ',', '.')) ?> DL</span>
                <a class="btn primary" href="<?= h($dlUrl) ?>" download="<?= h($it['file']) ?>">Download</a>
              <?php else: ?>
                <span class="ptag">Fehlt</span>
              <?php endif; ?>
            </div>

          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>

    <div style="margin-top:2rem">
      <a class="btn" href="downloads.html">← Zurück zu Downloads</a>
    </div>
  </div>
</div>

<footer>Rosewood MMORPG &bull; <a href="https://play.therosewood.de">play.therosewood.de</a> &bull; <span id="time"></span> &bull; <a href="impressum.html">Impressum</a></footer>
<script src="assets/js/main.js"></script>
</body>
</html>
