<?php
header("Content-Type: text/html; charset=utf-8");

$base = __DIR__;
$allowedExt = ['jpg','jpeg','png','gif','webp'];

// hämta dir från query
$dir = isset($_GET['dir']) ? $_GET['dir'] : '';
$path = realpath($base . '/' . $dir);

// säkerhet: se till att man inte kan kliva utanför
if (!$path || strpos($path, $base) !== 0) {
    die("Felaktig katalog");
}

// lista mappar och bilder i vald katalog
$folders = [];
$images = [];
foreach (scandir($path) as $f) {
    if ($f === '.' || $f === '..') continue;
    $full = $path . '/' . $f;
    if (is_dir($full)) {
        $folders[] = $dir ? "$dir/$f" : $f;
    } else {
        $ext = strtolower(pathinfo($f, PATHINFO_EXTENSION));
        if (in_array($ext, $allowedExt)) {
            $images[] = $dir ? "$dir/$f" : $f;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="sv">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Galleri</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div class="header">
    <?php if ($dir): ?>
      <a href="index.php" class="back-btn">Tillbaka</a>
    <?php endif; ?>
  </div>

  <?php if ($folders): ?>
    <div class="folders">
<?php foreach ($folders as $f): 
  $name = basename($f);
  $name = str_replace(['_', '-', '.'], ' ', $name);
  $name = ucfirst($name);
?>
  <a class="folder" href="index.php?dir=<?= urlencode($f) ?>">
    <?= htmlspecialchars($name) ?>
  </a>
<?php endforeach; ?>

    </div>
  <?php endif; ?>

  <?php if ($images): ?>
    <div class="gallery">
      <?php foreach ($images as $img): ?>
        <img src="<?= htmlspecialchars($img) ?>" alt="">
      <?php endforeach; ?>
    </div>
  <?php endif; ?>

<div id="lightbox" class="hidden">
  <span id="close">&times;</span>
  <img id="lightbox-img" src="" alt="">
  <div id="nav-left">&#10094;</div>
  <div id="nav-right">&#10095;</div>
</div>



  <script src="script.js"></script>
</body>
</html>

