<?php
/**
 * WP File Manager Lite - Standalone File Management Solution
 * 
 * WARNING: This script provides powerful file management capabilities.
 * Ensure you protect it with proper authentication before using in production.
 */

// ==================== CONFIGURATION ====================
$auth_enabled = false; // Set to true to enable basic authentication
$username = 'admin';   // Default username
$password = 'password'; // Default password - CHANGE THIS!

// Allowed file operations (set to false to disable)
$allow_file_upload = true;
$allow_file_deletion = true;
$allow_folder_creation = true;
$allow_file_editing = true;

// File extensions allowed for editing
$editable_extensions = ['txt', 'php', 'html', 'css', 'js', 'json', 'xml', 'md', 'log', 'htaccess'];

// ==================== AUTHENTICATION ====================
session_start();
if ($auth_enabled && !isset($_SESSION['authenticated'])) {
    if (isset($_POST['username']) && isset($_POST['password'])) {
        if ($_POST['username'] === $username && $_POST['password'] === $password) {
            $_SESSION['authenticated'] = true;
        } else {
            $auth_error = "Invalid credentials!";
        }
    }
    
    if (!isset($_SESSION['authenticated'])) {
        // Show login form
        echo '<!DOCTYPE html><html><head><title>Login - File Manager</title>';
        echo '<style>body { font-family: Arial, sans-serif; background: #f1f1f1; display: flex; justify-content: center; align-items: center; height: 100vh; }';
        echo '.login-form { background: white; padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0,0,0,0.1); width: 300px; }';
        echo 'input[type="text"], input[type="password"] { width: 100%; padding: 10px; margin: 8px 0; box-sizing: border-box; }';
        echo 'input[type="submit"] { background: #0073aa; color: white; padding: 10px; border: none; width: 100%; cursor: pointer; }';
        echo '.error { color: red; text-align: center; }</style></head><body>';
        echo '<div class="login-form"><h2 style="text-align: center;">File Manager Login</h2>';
        if (isset($auth_error)) echo '<p class="error">' . $auth_error . '</p>';
        echo '<form method="POST"><input type="text" name="username" placeholder="Username" required>';
        echo '<input type="password" name="password" placeholder="Password" required>';
        echo '<input type="submit" value="Login"></form></div></body></html>';
        exit;
    }
}

// ==================== FUNCTIONS ====================
function getBasePath() {
    return realpath(__DIR__);
}

function formatSize($bytes) {
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        return $bytes . ' bytes';
    } elseif ($bytes == 1) {
        return $bytes . ' byte';
    } else {
        return '0 bytes';
    }
}

function getFileIcon($file) {
    $extension = pathinfo($file, PATHINFO_EXTENSION);
    $icons = [
        'pdf' => '📕',
        'doc' => '📘', 'docx' => '📘',
        'xls' => '📗', 'xlsx' => '📗',
        'ppt' => '📓', 'pptx' => '📓',
        'zip' => '📦', 'rar' => '📦', 'tar' => '📦', 'gz' => '📦',
        'php' => '🐘', 'html' => '🌐', 'css' => '🎨', 'js' => '📜',
        'png' => '🖼', 'jpg' => '🖼', 'jpeg' => '🖼', 'gif' => '🖼', 'svg' => '🖼',
        'mp3' => '🎵', 'wav' => '🎵',
        'mp4' => '🎬', 'mov' => '🎬', 'avi' => '🎬',
        'txt' => '📄', 'log' => '📄',
        'exe' => '⚙️'
    ];
    
    return isset($icons[$extension]) ? $icons[$extension] : '📄';
}

// ==================== PROCESS ACTIONS ====================
$current_dir = isset($_GET['dir']) ? realpath(getBasePath() . '/' . $_GET['dir']) : getBasePath();
// Security: Prevent directory traversal
if (strpos($current_dir, getBasePath()) !== 0) {
    $current_dir = getBasePath();
}

$message = '';
$message_type = '';

// Create folder
if (isset($_POST['new_folder']) && $allow_folder_creation) {
    $new_folder = $current_dir . DIRECTORY_SEPARATOR . $_POST['new_folder_name'];
    if (!file_exists($new_folder)) {
        if (mkdir($new_folder)) {
            $message = "Folder created successfully!";
            $message_type = "success";
        } else {
            $message = "Error creating folder!";
            $message_type = "error";
        }
    } else {
        $message = "Folder already exists!";
        $message_type = "error";
    }
}

// Upload file
if (isset($_FILES['upload_file']) && $allow_file_upload) {
    $target_file = $current_dir . DIRECTORY_SEPARATOR . basename($_FILES['upload_file']['name']);
    if (move_uploaded_file($_FILES['upload_file']['tmp_name'], $target_file)) {
        $message = "File uploaded successfully!";
        $message_type = "success";
    } else {
        $message = "Error uploading file!";
        $message_type = "error";
    }
}

// Delete file/folder
if (isset($_GET['delete']) && $allow_file_deletion) {
    $delete_path = $current_dir . DIRECTORY_SEPARATOR . $_GET['delete'];
    if (strpos(realpath($delete_path), getBasePath()) === 0) { // Security check
        if (is_dir($delete_path)) {
            if (rmdir($delete_path)) {
                $message = "Folder deleted successfully!";
                $message_type = "success";
            } else {
                $message = "Error deleting folder! Make sure it's empty.";
                $message_type = "error";
            }
        } else {
            if (unlink($delete_path)) {
                $message = "File deleted successfully!";
                $message_type = "success";
            } else {
                $message = "Error deleting file!";
                $message_type = "error";
            }
        }
    } else {
        $message = "Invalid path!";
        $message_type = "error";
    }
}

// Edit file
if (isset($_POST['file_content']) && $allow_file_editing) {
    $edit_file = $current_dir . DIRECTORY_SEPARATOR . $_POST['edit_file'];
    if (strpos(realpath($edit_file), getBasePath()) === 0) { // Security check
        if (file_put_contents($edit_file, $_POST['file_content'])) {
            $message = "File saved successfully!";
            $message_type = "success";
        } else {
            $message = "Error saving file!";
            $message_type = "error";
        }
    }
}

// ==================== DISPLAY INTERFACE ====================
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WP File Manager Lite</title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif; line-height: 1.6; color: #333; background-color: #f6f7f7; }
        .container { max-width: 1200px; margin: 0 auto; padding: 20px; }
        header { background: #23282d; color: white; padding: 15px 20px; border-radius: 5px 5px 0 0; display: flex; justify-content: space-between; align-items: center; }
        .breadcrumb { background: white; padding: 10px 20px; border-bottom: 1px solid #e5e5e5; }
        .breadcrumb a { color: #0073aa; text-decoration: none; }
        .breadcrumb a:hover { text-decoration: underline; }
        .toolbar { background: white; padding: 10px 20px; display: flex; gap: 10px; border-bottom: 1px solid #e5e5e5; }
        .btn { background: #0073aa; color: white; border: none; padding: 8px 12px; border-radius: 3px; cursor: pointer; text-decoration: none; display: inline-block; }
        .btn:hover { background: #005a87; }
        .btn-danger { background: #dc3232; }
        .btn-danger:hover { background: #b32d2d; }
        .file-list { background: white; padding: 0; }
        .file-item { display: flex; align-items: center; padding: 10px 20px; border-bottom: 1px solid #e5e5e5; }
        .file-item:hover { background: #f9f9f9; }
        .file-icon { font-size: 24px; margin-right: 15px; }
        .file-name { flex: 1; }
        .file-actions { display: flex; gap: 5px; }
        .file-size { width: 100px; text-align: right; color: #666; }
        .file-modified { width: 180px; text-align: right; color: #666; }
        .message { padding: 10px 20px; margin: 10px 0; border-radius: 3px; }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); }
        .modal-content { background: white; margin: 10% auto; padding: 20px; width: 80%; max-width: 600px; border-radius: 5px; }
        .modal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; }
        .close { font-size: 24px; cursor: pointer; }
        textarea { width: 100%; height: 300px; padding: 10px; font-family: monospace; }
        form { margin: 15px 0; }
        input[type="text"], input[type="file"] { padding: 8px; width: 100%; margin-bottom: 10px; }
        @media (max-width: 768px) {
            .file-size, .file-modified { display: none; }
            .toolbar { flex-wrap: wrap; }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>WP File Manager Lite</h1>
            <div style="color: #a0a5aa;">v1.0</div>
        </header>

        <?php if (!empty($message)): ?>
            <div class="message <?php echo $message_type; ?>"><?php echo $message; ?></div>
        <?php endif; ?>

        <div class="breadcrumb">
            <?php
            $relative_path = str_replace(getBasePath(), '', $current_dir);
            $parts = explode(DIRECTORY_SEPARATOR, trim($relative_path, DIRECTORY_SEPARATOR));
            $current_path = '';
            echo '<a href="?dir=">Root</a>';
            foreach ($parts as $part) {
                if (!empty($part)) {
                    $current_path .= DIRECTORY_SEPARATOR . $part;
                    echo ' / <a href="?dir=' . urlencode($current_path) . '">' . htmlspecialchars($part) . '</a>';
                }
            }
            ?>
        </div>

        <div class="toolbar">
            <button class="btn" onclick="document.getElementById('uploadModal').style.display='block'">Upload File</button>
            <button class="btn" onclick="document.getElementById('folderModal').style.display='block'">Create Folder</button>
            <a href="<?php echo $_SERVER['PHP_SELF'] . '?dir=' . urlencode($relative_path); ?>" class="btn">Refresh</a>
        </div>

        <div class="file-list">
            <?php if ($relative_path !== ''): ?>
                <div class="file-item">
                    <div class="file-icon">📁</div>
                    <div class="file-name">
                        <a href="?dir=<?php echo urlencode(dirname($relative_path)); ?>">.. (Parent Folder)</a>
                    </div>
                    <div class="file-size">-</div>
                    <div class="file-modified">-</div>
                    <div class="file-actions">-</div>
                </div>
            <?php endif; ?>

            <?php
            $items = scandir($current_dir);
            if ($items) {
                foreach ($items as $item) {
                    if ($item === '.' || $item === '..') continue;
                    
                    $full_path = $current_dir . DIRECTORY_SEPARATOR . $item;
                    $is_dir = is_dir($full_path);
                    $size = $is_dir ? '-' : formatSize(filesize($full_path));
                    $modified = date('Y-m-d H:i:s', filemtime($full_path));
                    $icon = $is_dir ? '📁' : getFileIcon($item);
                    $relative_item_path = trim($relative_path . DIRECTORY_SEPARATOR . $item, DIRECTORY_SEPARATOR);
                    
                    echo '<div class="file-item">';
                    echo '<div class="file-icon">' . $icon . '</div>';
                    echo '<div class="file-name">';
                    if ($is_dir) {
                        echo '<a href="?dir=' . urlencode($relative_item_path) . '">' . htmlspecialchars($item) . '</a>';
                    } else {
                        echo htmlspecialchars($item);
                    }
                    echo '</div>';
                    echo '<div class="file-size">' . $size . '</div>';
                    echo '<div class="file-modified">' . $modified . '</div>';
                    echo '<div class="file-actions">';
                    
                    if (!$is_dir && $allow_file_editing && in_array(pathinfo($item, PATHINFO_EXTENSION), $editable_extensions)) {
                        echo '<a href="#" onclick="openEditModal(\'' . urlencode($relative_item_path) . '\', \'' . htmlspecialchars($item) . '\')" class="btn">Edit</a>';
                    }
                    
                    if ($allow_file_deletion) {
                        echo '<a href="?dir=' . urlencode($relative_path) . '&delete=' . urlencode($item) . '" class="btn btn-danger" onclick="return confirm(\'Are you sure you want to delete ' . htmlspecialchars($item) . '?\')">Delete</a>';
                    }
                    
                    echo '</div>';
                    echo '</div>';
                }
            }
            ?>
        </div>
    </div>

    <!-- Upload Modal -->
    <div id="uploadModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Upload File</h2>
                <span class="close" onclick="document.getElementById('uploadModal').style.display='none'">&times;</span>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <input type="file" name="upload_file" required>
                <input type="submit" value="Upload" class="btn">
            </form>
        </div>
    </div>

    <!-- Folder Creation Modal -->
    <div id="folderModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Create New Folder</h2>
                <span class="close" onclick="document.getElementById('folderModal').style.display='none'">&times;</span>
            </div>
            <form method="POST">
                <input type="text" name="new_folder_name" placeholder="Folder Name" required>
                <input type="hidden" name="new_folder" value="1">
                <input type="submit" value="Create" class="btn">
            </form>
        </div>
    </div>

    <!-- File Edit Modal -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="editModalTitle">Edit File</h2>
                <span class="close" onclick="document.getElementById('editModal').style.display='none'">&times;</span>
            </div>
            <form method="POST">
                <textarea id="fileContent" name="file_content"></textarea>
                <input type="hidden" id="editFileName" name="edit_file">
                <input type="submit" value="Save Changes" class="btn">
            </form>
        </div>
    </div>

    <script>
        // Close modals when clicking outside
        window.onclick = function(event) {
            if (event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        }

        function openEditModal(filePath, fileName) {
            document.getElementById('editModalTitle').innerText = 'Editing: ' + fileName;
            document.getElementById('editFileName').value = fileName;
            
            // Fetch file content via AJAX
            var xhr = new XMLHttpRequest();
            xhr.open('GET', '?action=get_content&file=' + encodeURIComponent(filePath), true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    document.getElementById('fileContent').value = xhr.responseText;
                    document.getElementById('editModal').style.display = 'block';
                }
            };
            xhr.send();
        }
        
        // Handle AJAX request for file content
        <?php
        if (isset($_GET['action']) && $_GET['action'] === 'get_content' && isset($_GET['file'])) {
            $file_path = getBasePath() . DIRECTORY_SEPARATOR . $_GET['file'];
            if (strpos(realpath($file_path), getBasePath()) === 0 && is_file($file_path)) {
                header('Content-Type: text/plain');
                readfile($file_path);
                exit;
            }
        }
        ?>
    </script>
</body>
</html>