<?php
function isImage($filename) {
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    return in_array($ext, ['png', 'jpg', 'jpeg', 'svg']);
}

function listGroupedFiles($baseDir) {
    $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($baseDir));
    $filesByDir = [];

    foreach ($rii as $file) {
        if ($file->isDir()) continue;

        $filePath = $file->getPathname();
        $relativePath = str_replace($baseDir . DIRECTORY_SEPARATOR, '', $filePath);
        $dirName = dirname($relativePath);

        if (!isset($filesByDir[$dirName])) {
            $filesByDir[$dirName] = [];
        }

        $filesByDir[$dirName][] = $relativePath;
    }

    foreach ($filesByDir as $dir => $files) {
        echo "<h3>📁 Map: $dir</h3>";
        echo "<div style='display: flex; flex-wrap: wrap; gap: 15px;'>";

        foreach ($files as $relativePath) {
            $fullPath = $baseDir . DIRECTORY_SEPARATOR . $relativePath;
            $encodedPath = urlencode($relativePath);
            $filename = basename($relativePath);

            echo "<div style='border: 1px solid #ccc; padding: 10px; width: 200px; text-align: center;'>";

            if (isImage($relativePath)) {
                echo "<div><img src='$relativePath' style='max-width: 100%; height: auto;' alt='$filename'></div>";
                echo "<div style='margin-top: 5px;'>$filename</div>";
            } else {
                echo "<div>$filename</div>";
                echo "<a href='?download=$encodedPath'>Download</a>";
            }

            echo "</div>";
        }

        echo "</div><hr>";
    }
}

// download functionaliteit
if (isset($_GET['download'])) {
    $file = urldecode($_GET['download']);
    $fullPath = __DIR__ . DIRECTORY_SEPARATOR . $file;

    if (file_exists($fullPath) && is_file($fullPath)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header("Content-Disposition: attachment; filename=\"" . basename($fullPath) . "\"");
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($fullPath));
        readfile($fullPath);
        exit;
    } else {
        echo "Bestand niet gevonden.";
    }
} else {
    echo "<h2>📂 Bestandenstructuur</h2>";
    listGroupedFiles(__DIR__);
}
?>

<!DOCTYPE html>
<html lang="nl">
<head>
    <meta charset="UTF-8">
    <title>Bestandenoverzicht</title>
    <style>
        body {
            background-color: #f2f2f2; /* lichtgrijs */
            font-family: Arial, sans-serif;
            padding: 20px;
        }
        h3 {
            margin-top: 40px;
            color: #333;
        }
    </style>
</head>
<body>
HTML;
