<?php
$uploadDir = 'uploads/';
$currentDir = isset($_GET['dir']) ? $_GET['dir'] : '';  // Aktueller Ordner
$fullPath = $uploadDir . $currentDir;  // Vollständiger Pfad

// Sicherstellen, dass das Verzeichnis existiert
if (!is_dir($fullPath)) {
    mkdir($fullPath, 0777, true);
}

// Datei-Upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['files'])) {
    $uploadedFiles = [];
    foreach ($_FILES['files']['name'] as $key => $name) {
        $targetFilePath = $fullPath . '/' . basename($name);
        if (move_uploaded_file($_FILES['files']['tmp_name'][$key], $targetFilePath)) {
            $uploadedFiles[] = $name;
        }
    }
    echo json_encode(["status" => "success", "message" => "Dateien erfolgreich hochgeladen!", "files" => $uploadedFiles]);
    exit;
}

// Datei verschieben
if (isset($_POST['move_file']) && isset($_POST['new_folder'])) {
    $fileToMove = $uploadDir . $_POST['move_file'];
    $newFolder = $uploadDir . $_POST['new_folder'] . '/';

    if (!is_dir($newFolder)) {
        mkdir($newFolder, 0777, true);
    }

    if (rename($fileToMove, $newFolder . basename($_POST['move_file']))) {
        echo json_encode(["status" => "success", "message" => "Datei verschoben nach {$_POST['new_folder']}"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Fehler beim Verschieben!"]);
    }
    exit;
}

// Datei löschen
if (isset($_POST['delete_file'])) {
    $fileToDelete = $uploadDir . $_POST['delete_file'];
    if (file_exists($fileToDelete)) {
        unlink($fileToDelete);
        echo json_encode(["status" => "success", "message" => "Datei erfolgreich gelöscht!"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Datei nicht gefunden!"]);
    }
    exit;
}

// Ordner-Inhalt abrufen
function scanDirectory($dir) {
    $items = [];
    foreach (scandir($dir) as $item) {
        if ($item === '.' || $item === '..') continue;
        $path = $dir . '/' . $item;
        $relativePath = str_replace('uploads/', '', $path);

        if (is_dir($path)) {
            $items[] = ["name" => $relativePath, "type" => "folder"];
        } else {
            $items[] = ["name" => $relativePath, "type" => "file"];
        }
    }
    return $items;
}

$filesAndFolders = scanDirectory($fullPath);
?>

<!DOCTYPE html>
<html lang="de">
<head>
    <link rel="icon" type="image/png" href="cloud.ico">
    <meta name="robots" content="noindex, nofollow">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Datei-Management</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            background: linear-gradient(135deg, #ffeb3b, #ff9800);
        }
        .container {
            max-width: 600px;
            margin: auto;
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 6px 15px rgba(0,0,0,0.15);
        }
        .file-list {
            text-align: left;
        }
        .file-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            border-bottom: 1px solid #ddd;
        }
        .folder {
            font-weight: bold;
            color: #007aff;
            cursor: pointer;
        }
        .button {
            background: #007aff;
            color: white;
            padding: 8px;
            border: none;
            cursor: pointer;
            border-radius: 5px;
        }
    </style>
    <script>
        function uploadFiles(files) {
            let formData = new FormData();
            for (let i = 0; i < files.length; i++) {
                formData.append("files[]", files[i]);
            }

            fetch(window.location.href, {
                method: "POST",
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                if (data.status === "success") location.reload();
            })
            .catch(error => console.error("Fehler:", error));
        }

        function moveFile(fileName) {
            let newFolder = prompt("In welches Verzeichnis verschieben?");
            if (!newFolder) return;

            let formData = new FormData();
            formData.append("move_file", fileName);
            formData.append("new_folder", newFolder);

            fetch("upload.php", {
                method: "POST",
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                if (data.status === "success") location.reload();
            })
            .catch(error => console.error("Fehler:", error));
        }

        function deleteFile(fileName) {
            if (!confirm("Soll die Datei wirklich gelöscht werden?")) return;

            let formData = new FormData();
            formData.append("delete_file", fileName);

            fetch("upload.php", {
                method: "POST",
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                if (data.status === "success") location.reload();
            })
            .catch(error => console.error("Fehler:", error));
        }

        function navigateTo(folder) {
            window.location.href = "?dir=" + encodeURIComponent(folder);
        }
    </script>
</head>
<body>

    <div class="container">
        <h2>📂 Datei-Upload & Management</h2>

        <h3>Aktueller Ordner: <?= $currentDir ?: 'Hauptverzeichnis' ?></h3>
        <?php if ($currentDir): ?>
            <button class="button" onclick="window.location.href='upload.php'">⬅️ Zurück</button>
        <?php endif; ?>

        <div class="upload-box">
            📤 Ziehe Dateien hierher oder
            <input type="file" id="fileInput" multiple style="display: none;" onchange="uploadFiles(this.files)">
            <button class="button" onclick="document.getElementById('fileInput').click();">Dateien auswählen</button>
        </div>

        <h3>📁 Dateien & Ordner</h3>
        <div class="file-list">
            <?php foreach ($filesAndFolders as $item): ?>
                <div class="file-item">
                    <?php if ($item["type"] === "folder"): ?>
                        <span class="folder" onclick="navigateTo('<?= $item["name"] ?>')">📁 <?= basename($item["name"]) ?></span>
                    <?php else: ?>
                        <span>📄 <?= basename($item["name"]) ?></span>
                        <button class="button" onclick="moveFile('<?= $item["name"] ?>')">📁 Verschieben</button>
                        <button class="button" onclick="deleteFile('<?= $item["name"] ?>')">❌ Löschen</button>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </div>

</body>
</html>
