<?php
session_start();

// --- CONFIGURACIÓN DE ACCESO ---
$PASSWORD = '33comRxX'; // ¡CAMBIA ESTO!

// --- AQUÍ DEFINES TUS CARPETAS PERMITIDAS ---
// Puedes usar rutas absolutas ('/var/www/html') o relativas (__DIR__ . '/carpeta')
$ALLOWED_DIRS = [
    //'Inicio (Script)' => __DIR__, 
	'Aplicaciones' => '/var/www/html/MS/APPS/',
	'Archivos' => '/var/www/html/MS/librerias/Archivos/',
	'Librerias' => '/var/www/html/MS/librerias/',
	'Paginas' => '/var/www/html/MS/librerias/Archivos/',
	'Descargas' => '/var/www/html/MS/Descargas/'
    // 'Proyecto Web'    => 'C:/xampp/htdocs/mi_sitio',
    // 'Logs del Server' => '/var/log/apache2',
    // 'Backup'          => '../backups' 
];

// Extensiones editables
$editable_ext = ['php', 'html', 'css', 'js', 'json', 'xml', 'txt', 'md', 'sql', 'env', 'htaccess'];

// --- AUTENTICACIÓN ---
if (isset($_POST['login'])) {
    if ($_POST['password'] === $PASSWORD) {
        $_SESSION['fm_logged'] = true;
    } else {
        $error = "Contraseña incorrecta";
    }
}
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: " . strtok($_SERVER["REQUEST_URI"], '?'));
    exit;
}
if (!isset($_SESSION['fm_logged'])) {
    echo '<!DOCTYPE html><html><head><title>Login</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"><style>body{background:#f8f9fa;display:flex;align-items:center;justify-content:center;height:100vh;}</style></head><body><div class="card p-4 shadow" style="width:350px;"><h4 class="text-center mb-3">Acceso Seguro</h4>'.(isset($error)?"<div class='alert alert-danger'>$error</div>":"").'<form method="post"><input type="password" name="password" class="form-control mb-3" placeholder="Contraseña" required><button type="submit" name="login" class="btn btn-primary w-100">Entrar</button></form></div></body></html>';
    exit;
}

// --- LÓGICA DE SELECCIÓN DE CARPETA RAÍZ ---
$drive_key = isset($_GET['drive']) ? $_GET['drive'] : null;
$ROOT_DIR = null;
$in_drive_selection = true;

if ($drive_key && isset($ALLOWED_DIRS[$drive_key])) {
    $real_root = realpath($ALLOWED_DIRS[$drive_key]);
    if ($real_root) {
        $ROOT_DIR = $real_root;
        $in_drive_selection = false;
    }
}

// Si estamos dentro de una carpeta permitida, ejecutamos la lógica del gestor
$msg = "";
$files_list = [];
$editor_mode = false;
$file_content = "";
$current_path = "";

if (!$in_drive_selection) {
    // --- GESTIÓN DE RUTAS RELATIVAS ---
    $base_url = strtok($_SERVER["REQUEST_URI"], '?');
    $current_path = isset($_GET['path']) ? $_GET['path'] : '';
    if (strpos($current_path, '..') !== false) $current_path = ''; 
    $abs_path = realpath($ROOT_DIR . '/' . $current_path);
    
    // Seguridad: Validar que seguimos dentro del ROOT seleccionado
    if ($abs_path === false || strpos($abs_path, $ROOT_DIR) !== 0) {
        $abs_path = $ROOT_DIR;
        $current_path = '';
    }

    // --- PROCESAR ACCIONES ---
    
    // 1. Guardar Archivo (Editor)
    if (isset($_POST['save_file_content'])) {
        $file_to_save = $ROOT_DIR . '/' . $_POST['file_path'];
        if (strpos(realpath($file_to_save), $ROOT_DIR) === 0) {
            file_put_contents($file_to_save, $_POST['file_content']);
            $msg = "Archivo guardado correctamente.";
        }
    }

    // 2. Descarga
    if (isset($_GET['download'])) {
        $file = $ROOT_DIR . '/' . $_GET['download'];
        if (file_exists($file) && is_file($file) && strpos(realpath($file), $ROOT_DIR) === 0) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="'.basename($file).'"');
            header('Content-Length: ' . filesize($file));
            readfile($file);
            exit;
        }
    }

    // 3. Renombrar
    if (isset($_POST['rename_item'])) {
        $old = $abs_path . '/' . $_POST['old_name'];
        $new = $abs_path . '/' . $_POST['new_name'];
        if (file_exists($old) && !file_exists($new)) { rename($old, $new); $msg = "Renombrado."; }
        else $msg = "Error al renombrar.";
    }

    // 4. Subir / Crear / Borrar / Copiar
    if (isset($_FILES['file_upload'])) {
        move_uploaded_file($_FILES['file_upload']['tmp_name'], $abs_path . '/' . basename($_FILES['file_upload']['name']));
        $msg = "Archivo subido.";
    }
    if (isset($_POST['new_folder'])) {
        $n = $abs_path . '/' . $_POST['folder_name'];
        if (!file_exists($n)) { mkdir($n); $msg = "Carpeta creada."; }
    }
    if (isset($_GET['delete'])) {
        $d = $ROOT_DIR . '/' . $_GET['delete'];
        if ($d != __FILE__ && strpos(realpath($d), $ROOT_DIR) === 0) {
            if(is_dir($d)) deleteDir($d); else unlink($d);
            $msg = "Eliminado.";
        }
    }
    if (isset($_GET['copy'])) {
        $_SESSION['cp_path'] = $ROOT_DIR . '/' . $_GET['copy'];
        $_SESSION['cp_name'] = basename($_GET['copy']);
        $msg = "Copiado al portapapeles.";
    }
    if (isset($_GET['paste']) && isset($_SESSION['cp_path'])) {
        $src = $_SESSION['cp_path']; $dst = $abs_path . '/' . $_SESSION['cp_name'];
        if(file_exists($src)) {
            if(is_dir($src)) recurse_copy($src, $dst); else copy($src, $dst);
            $msg = "Pegado.";
        }
    }

    // --- MODO EDITOR ---
    if (isset($_GET['edit'])) {
        $f_edit_abs = $ROOT_DIR . '/' . $_GET['edit'];
        $ext = pathinfo($f_edit_abs, PATHINFO_EXTENSION);
        if (file_exists($f_edit_abs) && in_array($ext, $editable_ext) && strpos(realpath($f_edit_abs), $ROOT_DIR) === 0) {
            $editor_mode = true;
            $file_content = file_get_contents($f_edit_abs);
            $file_editing_path = $_GET['edit'];
        }
    }
}

// Funciones Aux
function deleteDir($dir) { $files = array_diff(scandir($dir), ['.','..']); foreach ($files as $file) (is_dir("$dir/$file")) ? deleteDir("$dir/$file") : unlink("$dir/$file"); return rmdir($dir); }
function recurse_copy($src,$dst) { $dir = opendir($src); @mkdir($dst); while(false !== ( $file = readdir($dir)) ) { if (( $file != '.' ) && ( $file != '..' )) { if ( is_dir($src . '/' . $file) ) recurse_copy($src . '/' . $file,$dst . '/' . $file); else copy($src . '/' . $file,$dst . '/' . $file); } } closedir($dir); }
function formatSize($bytes) { if ($bytes >= 1048576) return number_format($bytes / 1048576, 2) . ' MB'; return number_format($bytes / 1024, 2) . ' KB'; }

?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestor V3</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        .icon-col { width: 40px; text-align: center; }
        .table-hover tbody tr:hover { background-color: #f1f1f1; }
        a { text-decoration: none; color: #333; }
        #editor { height: 600px; width: 100%; border: 1px solid #ccc; }
        .drive-card:hover { transform: translateY(-5px); box-shadow: 0 10px 20px rgba(0,0,0,0.1); transition: 0.3s; cursor: pointer; }
    </style>
</head>
<body class="p-4 bg-light">
<div class="container-fluid" style="max-width: 1200px;">
    
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3><i class="fa-solid fa-server text-primary"></i> Gestor de Archivos</h3>
        <div>
            <?php if(!$in_drive_selection && isset($_SESSION['cp_path'])): ?>
                <a href="?drive=<?= urlencode($drive_key) ?>&path=<?= urlencode($current_path) ?>&paste=true" class="btn btn-warning btn-sm me-2"><i class="fa-solid fa-paste"></i> Pegar</a>
            <?php endif; ?>
            <a href="?logout=true" class="btn btn-danger btn-sm">Salir</a>
        </div>
    </div>

    <?php if ($msg): ?><div class="alert alert-success alert-dismissible fade show py-2"><?= $msg ?><button type="button" class="btn-close p-2" data-bs-dismiss="alert"></button></div><?php endif; ?>

    <?php if ($in_drive_selection): ?>
        <div class="row">
            <div class="col-12 mb-3"><h5 class="text-secondary">Selecciona una ubicación:</h5></div>
            <?php foreach($ALLOWED_DIRS as $name => $path): 
                $exists = file_exists($path);
            ?>
            <div class="col-md-4 mb-3">
                <div class="card drive-card h-100 border-0 shadow-sm">
                    <div class="card-body text-center">
                        <i class="fa-solid <?= $exists ? 'fa-hard-drive text-primary' : 'fa-triangle-exclamation text-danger' ?> fa-3x mb-3"></i>
                        <h5 class="card-title"><?= $name ?></h5>
                        <p class="card-text text-muted small"><?= $path ?></p>
                        <?php if($exists): ?>
                            <a href="?drive=<?= urlencode($name) ?>" class="btn btn-outline-primary w-100 stretched-link">Abrir</a>
                        <?php else: ?>
                            <span class="text-danger small">Ruta no encontrada</span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

    <?php elseif ($editor_mode): ?>
        <div class="card shadow">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span>Editando: <strong><?= htmlspecialchars($file_editing_path) ?></strong></span>
                <a href="?drive=<?= urlencode($drive_key) ?>&path=<?= urlencode(dirname($file_editing_path) == '.' ? '' : dirname($file_editing_path)) ?>" class="btn btn-secondary btn-sm">Cancelar</a>
            </div>
            <div class="card-body p-0">
                <div id="editor"><?= htmlspecialchars($file_content) ?></div>
                <form method="post" id="editorForm" class="p-3 border-top">
                    <textarea name="file_content" id="hidden_content" style="display:none;"></textarea>
                    <input type="hidden" name="file_path" value="<?= htmlspecialchars($file_editing_path) ?>">
                    <button type="button" onclick="saveEditor()" name="save_file_content" class="btn btn-success"><i class="fa-solid fa-save"></i> Guardar</button>
                </form>
            </div>
        </div>

    <?php else: ?>
        <div class="row mb-3 g-2">
            <div class="col-md-8">
                <div class="bg-white p-2 border rounded d-flex align-items-center">
                    <a href="?" class="me-2 text-secondary fw-bold" title="Cambiar Unidad"><i class="fa-solid fa-server"></i> Inicio</a>
                    <span class="mx-2 text-muted">|</span>
                    <a href="?drive=<?= urlencode($drive_key) ?>&path=" class="me-2 text-primary fw-bold"><?= $drive_key ?></a> / 
                    <?php
                        $crumbs = array_filter(explode('/', $current_path));
                        $build = '';
                        foreach($crumbs as $crumb){
                            $build .= $crumb;
                            echo '<a href="?drive='.urlencode($drive_key).'&path='.urlencode($build).'" class="ms-1">'.$crumb.'</a> / ';
                            $build .= '/';
                        }
                    ?>
                </div>
            </div>
            <div class="col-md-4 text-end">
                <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#uploadModal"><i class="fa-solid fa-upload"></i> Subir</button>
                <button class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#folderModal"><i class="fa-solid fa-folder-plus"></i> Carpeta</button>
            </div>
        </div>

        <div class="card shadow-sm">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light"><tr><th class="icon-col"></th><th>Nombre</th><th>Tamaño</th><th class="text-end">Acciones</th></tr></thead>
                    <tbody>
                        <?php
                        $files = scandir($abs_path);
                        usort($files, function($a, $b) use ($abs_path) {
                            $da = is_dir($abs_path.'/'.$a); $db = is_dir($abs_path.'/'.$b);
                            if ($da && !$db) return -1; if (!$da && $db) return 1; return strcasecmp($a, $b);
                        });
                        foreach($files as $f):
                            if($f == '.') continue;
                            if($f == '..' && $current_path == '') continue; // No mostramos '..' en la raíz de la unidad
                            
                            $p_rel = ($current_path ? $current_path . '/' : '') . $f;
                            $p_abs = $abs_path . '/' . $f;
                            $is_dir = is_dir($p_abs);
                            $ext = pathinfo($f, PATHINFO_EXTENSION);
                            $can_edit = !$is_dir && in_array(strtolower($ext), $editable_ext);
                            
                            // Link '..' especial: si estamos en subcarpeta vuelve atrás, si estamos en raíz no se muestra
                            $link = ($f == '..') ? dirname($current_path) : $p_rel;
                            if($link == '.') $link = '';
                        ?>
                        <tr>
                            <td class="icon-col">
                                <?php if($f == '..'): ?><i class="fa-solid fa-level-up-alt"></i>
                                <?php elseif($is_dir): ?><i class="fa-solid fa-folder text-warning"></i>
                                <?php else: ?><i class="fa-regular fa-file text-secondary"></i><?php endif; ?>
                            </td>
                            <td>
                                <?php if($is_dir): ?>
                                    <a href="?drive=<?= urlencode($drive_key) ?>&path=<?= urlencode($link) ?>" class="fw-bold text-dark"><?= $f ?></a>
                                <?php else: echo $f; endif; ?>
                            </td>
                            <td><?= $is_dir ? '-' : formatSize(filesize($p_abs)) ?></td>
                            <td class="text-end">
                                <?php if($f != '..'): ?>
                                    <div class="btn-group">
                                        <?php if($can_edit): ?>
                                            <a href="?drive=<?=urlencode($drive_key)?>&edit=<?=urlencode($p_rel)?>" class="btn btn-sm btn-outline-primary"><i class="fa-solid fa-code"></i></a>
                                        <?php endif; ?>
                                        <?php if(!$is_dir): ?>
                                            <a href="?drive=<?=urlencode($drive_key)?>&download=<?=urlencode($p_rel)?>" class="btn btn-sm btn-outline-success"><i class="fa-solid fa-download"></i></a>
                                        <?php endif; ?>
                                        <button class="btn btn-sm btn-outline-secondary" onclick="renameItem('<?= $f ?>')"><i class="fa-solid fa-pen"></i></button>
                                        <a href="?drive=<?=urlencode($drive_key)?>&path=<?=urlencode($current_path)?>&copy=<?=urlencode($p_rel)?>" class="btn btn-sm btn-outline-secondary"><i class="fa-regular fa-copy"></i></a>
                                        <a href="?drive=<?=urlencode($drive_key)?>&path=<?=urlencode($current_path)?>&delete=<?=urlencode($p_rel)?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('¿Borrar?')"><i class="fa-solid fa-trash"></i></a>
                                    </div>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php endif; ?>
</div>

<div class="modal fade" id="uploadModal" tabindex="-1"><div class="modal-dialog"><form method="post" enctype="multipart/form-data" class="modal-content"><div class="modal-header"><h5 class="modal-title">Subir</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><input type="file" name="file_upload" class="form-control" required></div><div class="modal-footer"><button type="submit" class="btn btn-primary">Subir</button></div></form></div></div>
<div class="modal fade" id="folderModal" tabindex="-1"><div class="modal-dialog"><form method="post" class="modal-content"><div class="modal-header"><h5 class="modal-title">Nueva Carpeta</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><input type="text" name="folder_name" class="form-control" placeholder="Nombre" required><input type="hidden" name="new_folder" value="1"></div><div class="modal-footer"><button type="submit" class="btn btn-success">Crear</button></div></form></div></div>
<div class="modal fade" id="renameModal" tabindex="-1"><div class="modal-dialog"><form method="post" class="modal-content"><div class="modal-header"><h5 class="modal-title">Renombrar</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><label>Actual:</label><input type="text" id="old_name_display" class="form-control mb-2" disabled><label>Nuevo:</label><input type="text" name="new_name" id="new_name_input" class="form-control" required><input type="hidden" name="old_name" id="old_name_val"><input type="hidden" name="rename_item" value="1"></div><div class="modal-footer"><button type="submit" class="btn btn-primary">Guardar</button></div></form></div></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js"></script>
<script>
function renameItem(f){ document.getElementById('old_name_display').value=f; document.getElementById('old_name_val').value=f; document.getElementById('new_name_input').value=f; new bootstrap.Modal(document.getElementById('renameModal')).show(); }
<?php if ($editor_mode): ?>
    var editor = ace.edit("editor"); editor.setTheme("ace/theme/monokai"); editor.session.setMode("ace/mode/php");
    function saveEditor() { document.getElementById('hidden_content').value = editor.getValue(); document.getElementById('editorForm').submit(); }
<?php endif; ?>
</script>
</body>
</html>