<?php
// =======================
// DESCARGAR ARCHIVO
// =======================
if (isset($_GET['download'])) {
    $file = $_GET['download'];

    if (file_exists($file) && is_file($file)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($file) . '"');
        header('Content-Length: ' . filesize($file));
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        flush();
        readfile($file);
        exit;
    }
}

// Definir la raíz de los archivos
$rootDir = __DIR__;
$currentDir = isset($_GET['dir']) ? $_GET['dir'] : $rootDir;

// Función para listar archivos y carpetas
function listDirectory($dir) {
    $files = [];
    $dirs = [];
    $items = scandir($dir);
    foreach ($items as $item) {
        if ($item == '.' || $item == '..') continue;
        $path = $dir . DIRECTORY_SEPARATOR . $item;
        if (is_dir($path)) {
            $dirs[] = $item;
        } else {
            $files[] = $item;
        }
    }
    return ['dirs' => $dirs, 'files' => $files];
}

// Abrir archivo y obtener su contenido
if (isset($_GET['file']) && file_exists($_GET['file'])) {
    $fileContent = file_get_contents($_GET['file']);
    $fileSize = filesize($_GET['file']);
}

// Guardar cambios en el archivo
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['content']) && isset($_POST['file'])) {
    file_put_contents($_POST['file'], $_POST['content']);
    $message = 'Archivo guardado correctamente.';
}

// Mover archivo
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['move']) && isset($_POST['source']) && isset($_POST['destination'])) {
    if (rename($_POST['source'], $_POST['destination'])) {
        $message = 'Archivo movido correctamente.';
    } else {
        $message = 'Error al mover el archivo.';
    }
}

// Renombrar archivo o carpeta
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['rename']) && isset($_POST['source']) && isset($_POST['newName'])) {
    $destination = dirname($_POST['source']) . DIRECTORY_SEPARATOR . $_POST['newName'];
    if (rename($_POST['source'], $destination)) {
        $message = 'Archivo o carpeta renombrado correctamente.';
    } else {
        $message = 'Error al renombrar el archivo o carpeta.';
    }
}

// Crear un nuevo archivo
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create']) && isset($_POST['newFileName'])) {
    $newFilePath = $currentDir . DIRECTORY_SEPARATOR . $_POST['newFileName'];
    if (!file_exists($newFilePath)) {
        touch($newFilePath);
        $message = 'Archivo creado correctamente.';
    } else {
        $message = 'El archivo ya existe.';
    }
}

// Listar el directorio actual
$directoryContent = listDirectory($currentDir);
?>

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Gestor de Archivos</title>
<style>
body { font-family: Arial; margin:20px; }
table { width:100%; border-collapse:collapse; }
table, th, td { border:1px solid #ddd; }
th, td { padding:8px; }
.button { background:#007BFF; color:#fff; padding:10px 20px; border:none; cursor:pointer; }
.button:hover { background:#0056b3; }
.file-link { color:#007BFF; text-decoration:none; }
</style>
</head>
<body>

<h1>Gestor de Archivos</h1>

<?php if (isset($message)) echo "<p>$message</p>"; ?>

<h2>Navegar:</h2>
<form method="GET">
<input type="text" name="dir" value="<?php echo $currentDir; ?>" style="width:80%">
<button class="button">Ir</button>
</form>

<h2>Crear archivo:</h2>
<form method="POST">
<input type="text" name="newFileName" required>
<button class="button" name="create">Crear</button>
</form>

<h2>Carpetas:</h2>
<table>
<?php foreach ($directoryContent['dirs'] as $dir): ?>
<tr>
<td>
<a class="file-link" href="?dir=<?php echo urlencode($currentDir . DIRECTORY_SEPARATOR . $dir); ?>">
<?php echo $dir; ?>
</a>
</td>
<td>
<!-- Formulario para renombrar carpeta -->
<form method="POST" style="display:inline-block;">
<input type="text" name="newName" placeholder="Nuevo nombre" required>
<input type="hidden" name="source" value="<?php echo $currentDir . DIRECTORY_SEPARATOR . $dir; ?>">
<button class="button" name="rename">Renombrar</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</table>

<h2>Archivos:</h2>
<table>
<tr><th>Archivo</th><th>Tamaño</th><th>Acciones</th></tr>

<?php foreach ($directoryContent['files'] as $file): ?>
<tr>
<td><?php echo $file; ?></td>
<td><?php echo filesize($currentDir . DIRECTORY_SEPARATOR . $file); ?> bytes</td>
<td>
<a class="file-link" href="?file=<?php echo urlencode($currentDir . DIRECTORY_SEPARATOR . $file); ?>&dir=<?php echo urlencode($currentDir); ?>">Editar</a>
 |
<a class="file-link" href="?download=<?php echo urlencode($currentDir . DIRECTORY_SEPARATOR . $file); ?>">Descargar</a>
 |
<!-- Formulario para renombrar archivo -->
<form method="POST" style="display:inline-block;">
<input type="text" name="newName" placeholder="Nuevo nombre" required>
<input type="hidden" name="source" value="<?php echo $currentDir . DIRECTORY_SEPARATOR . $file; ?>">
<button class="button" name="rename">Renombrar</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</table>

<?php if (isset($fileContent)): ?>
<h2>Editar archivo</h2>
<form method="POST">
<textarea name="content" style="width:100%;height:300px"><?php echo htmlspecialchars($fileContent); ?></textarea>
<input type="hidden" name="file" value="<?php echo htmlspecialchars($_GET['file']); ?>">
<button class="button">Guardar</button>
</form>
<p>Tamaño: <?php echo $fileSize; ?> bytes</p>
<?php endif; ?>

</body>
</html>
