<?php
session_start();

// Security configuration
define('BASE_PATH', realpath('./'));
error_reporting(0);

// Security functions
function sanitize_path($path) {
    $path = str_replace('..', '', $path);
    $path = preg_replace('/[^a-zA-Z0-9\-_\.\/]/', '', $path);
    return BASE_PATH . '/' . ltrim($path, '/');
}

function format_size($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';
    } else {
        return $bytes . ' bytes';
    }
}

function get_file_icon($file) {
    $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    $icons = [
        'pdf' => '📄',
        'txt' => '📝',
        'doc' => '📄', 'docx' => '📄',
        'xls' => '📊', 'xlsx' => '📊',
        'zip' => '📦', 'rar' => '📦', 'tar' => '📦', 'gz' => '📦',
        'jpg' => '🖼️', 'jpeg' => '🖼️', 'png' => '🖼️', 'gif' => '🖼️',
        'php' => '🐘', 'html' => '🌐', 'css' => '🎨', 'js' => '📜',
        'mp3' => '🎵', 'wav' => '🎵',
        'mp4' => '🎬', 'avi' => '🎬'
    ];
    return $icons[$extension] ?? '📄';
}

// Handle POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    
    $action = $_POST['action'] ?? '';
    $response = ['success' => false, 'message' => ''];
    
    try {
        switch ($action) {
            case 'create_folder':
                $path = sanitize_path($_POST['path'] ?? '');
                $name = $_POST['name'] ?? '';
                
                if (!empty($name)) {
                    $full_path = $path . '/' . $name;
                    if (!file_exists($full_path)) {
                        mkdir($full_path, 0755, true);
                        $response['success'] = true;
                        $response['message'] = 'Folder created successfully';
                    } else {
                        $response['message'] = 'Folder already exists';
                    }
                }
                break;
                
            case 'create_file':
                $path = sanitize_path($_POST['path'] ?? '');
                $name = $_POST['name'] ?? '';
                $content = $_POST['content'] ?? '';
                
                if (!empty($name)) {
                    $full_path = $path . '/' . $name;
                    if (file_put_contents($full_path, $content) !== false) {
                        $response['success'] = true;
                        $response['message'] = 'File created successfully';
                    } else {
                        $response['message'] = 'Failed to create file';
                    }
                }
                break;
                
            case 'delete':
                $path = sanitize_path($_POST['path'] ?? '');
                
                if (file_exists($path)) {
                    if (is_dir($path)) {
                        // Delete directory recursively
                        $files = array_diff(scandir($path), ['.', '..']);
                        foreach ($files as $file) {
                            delete_recursive($path . '/' . $file);
                        }
                        rmdir($path);
                    } else {
                        unlink($path);
                    }
                    $response['success'] = true;
                    $response['message'] = 'Deleted successfully';
                }
                break;
                
            case 'rename':
                $path = sanitize_path($_POST['path'] ?? '');
                $new_name = $_POST['new_name'] ?? '';
                
                if (!empty($new_name) && file_exists($path)) {
                    $dir = dirname($path);
                    $new_path = $dir . '/' . $new_name;
                    
                    if (rename($path, $new_path)) {
                        $response['success'] = true;
                        $response['message'] = 'Renamed successfully';
                    } else {
                        $response['message'] = 'Rename failed';
                    }
                }
                break;
                
            case 'edit_file':
                $path = sanitize_path($_POST['path'] ?? '');
                $content = $_POST['content'] ?? '';
                
                if (file_exists($path) && is_file($path)) {
                    if (file_put_contents($path, $content) !== false) {
                        $response['success'] = true;
                        $response['message'] = 'File saved successfully';
                    } else {
                        $response['message'] = 'Failed to save file';
                    }
                }
                break;
                
            case 'upload':
                $path = sanitize_path($_POST['path'] ?? '');
                
                if (isset($_FILES['file'])) {
                    $upload_file = $path . '/' . $_FILES['file']['name'];
                    if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_file)) {
                        $response['success'] = true;
                        $response['message'] = 'File uploaded successfully';
                    } else {
                        $response['message'] = 'Upload failed';
                    }
                }
                break;
                
            case 'extract':
                $path = sanitize_path($_POST['path'] ?? '');
                $archive = sanitize_path($_POST['archive'] ?? '');
                
                if (file_exists($archive)) {
                    $zip = new ZipArchive;
                    if ($zip->open($archive) === TRUE) {
                        $zip->extractTo($path);
                        $zip->close();
                        $response['success'] = true;
                        $response['message'] = 'Archive extracted successfully';
                    } else {
                        $response['message'] = 'Failed to extract archive';
                    }
                }
                break;
        }
    } catch (Exception $e) {
        $response['message'] = 'Error: ' . $e->getMessage();
    }
    
    echo json_encode($response);
    exit;
}

// Recursive delete function
function delete_recursive($path) {
    if (is_dir($path)) {
        $files = array_diff(scandir($path), ['.', '..']);
        foreach ($files as $file) {
            delete_recursive($path . '/' . $file);
        }
        rmdir($path);
    } else {
        unlink($path);
    }
}

// Get current directory
$current_dir = sanitize_path($_GET['dir'] ?? '');
if (!file_exists($current_dir)) {
    $current_dir = BASE_PATH;
}

// Handle file download
if (isset($_GET['download'])) {
    $file = sanitize_path($_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));
        readfile($file);
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP File Manager</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: Arial, sans-serif; background: #f5f5f5; color: #333; }
        .container { max-width: 1200px; margin: 0 auto; padding: 20px; }
        .header { background: #2c3e50; color: white; padding: 20px; border-radius: 8px; margin-bottom: 20px; }
        .toolbar { background: white; padding: 15px; border-radius: 8px; margin-bottom: 20px; display: flex; gap: 10px; flex-wrap: wrap; }
        .btn { background: #3498db; color: white; border: none; padding: 10px 15px; border-radius: 4px; cursor: pointer; text-decoration: none; display: inline-block; }
        .btn:hover { background: #2980b9; }
        .btn-danger { background: #e74c3c; }
        .btn-danger:hover { background: #c0392b; }
        .btn-success { background: #27ae60; }
        .btn-success:hover { background: #219a52; }
        .file-list { background: white; border-radius: 8px; overflow: hidden; }
        .file-item { display: flex; align-items: center; padding: 12px 15px; border-bottom: 1px solid #eee; }
        .file-item:hover { background: #f8f9fa; }
        .file-icon { font-size: 20px; margin-right: 10px; }
        .file-name { flex: 1; }
        .file-actions { display: flex; gap: 5px; }
        .file-size { color: #666; margin-right: 15px; }
        .file-date { color: #666; margin-right: 15px; }
        .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); }
        .modal-content { background: white; margin: 5% auto; padding: 20px; border-radius: 8px; width: 90%; max-width: 500px; }
        .modal-header { display: flex; justify-content: between; align-items: center; margin-bottom: 15px; }
        .close { font-size: 24px; cursor: pointer; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 5px; font-weight: bold; }
        .form-group input, .form-group textarea { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
        .breadcrumb { background: white; padding: 15px; border-radius: 8px; margin-bottom: 20px; }
        .breadcrumb a { color: #3498db; text-decoration: none; }
        .breadcrumb a:hover { text-decoration: underline; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📁 PHP File Manager</h1>
            <p>Current Directory: <?php echo htmlspecialchars(str_replace(BASE_PATH, '', $current_dir)) ?: '/'; ?></p>
        </div>

        <!-- Toolbar -->
        <div class="toolbar">
            <button class="btn" onclick="showModal('createFolderModal')">📁 New Folder</button>
            <button class="btn" onclick="showModal('createFileModal')">📄 New File</button>
            <button class="btn" onclick="showModal('uploadModal')">📤 Upload</button>
            <button class="btn" onclick="refresh()">🔄 Refresh</button>
        </div>

        <!-- Breadcrumb -->
        <div class="breadcrumb">
            <?php
            $breadcrumbs = [];
            $relative_path = str_replace(BASE_PATH, '', $current_dir);
            $parts = array_filter(explode('/', $relative_path));
            $current_path = '';
            
            echo '<a href="?dir=">Root</a>';
            foreach ($parts as $part) {
                $current_path .= '/' . $part;
                echo ' / <a href="?dir=' . urlencode($current_path) . '">' . htmlspecialchars($part) . '</a>';
            }
            ?>
        </div>

        <!-- File List -->
        <div class="file-list">
            <?php
            // Parent directory link
            if ($current_dir !== BASE_PATH) {
                $parent_dir = dirname($current_dir);
                if ($parent_dir === BASE_PATH) $parent_dir = '';
                echo '<div class="file-item">';
                echo '<span class="file-icon">📁</span>';
                echo '<a href="?dir=' . urlencode($parent_dir) . '" class="file-name">.. (Parent Directory)</a>';
                echo '</div>';
            }

            // Get files and directories
            $items = scandir($current_dir);
            $dirs = [];
            $files = [];
            
            foreach ($items as $item) {
                if ($item === '.' || $item === '..') continue;
                
                $full_path = $current_dir . '/' . $item;
                if (is_dir($full_path)) {
                    $dirs[] = $item;
                } else {
                    $files[] = $item;
                }
            }
            
            // Sort directories and files
            sort($dirs);
            sort($files);
            
            // Display directories
            foreach ($dirs as $item) {
                $full_path = $current_dir . '/' . $item;
                $stat = stat($full_path);
                echo '<div class="file-item">';
                echo '<span class="file-icon">📁</span>';
                echo '<a href="?dir=' . urlencode(str_replace(BASE_PATH, '', $full_path)) . '" class="file-name">' . htmlspecialchars($item) . '</a>';
                echo '<span class="file-date">' . date('Y-m-d H:i', $stat['mtime']) . '</span>';
                echo '<div class="file-actions">';
                echo '<button class="btn" onclick="renameItem(\'' . addslashes($full_path) . '\', \'' . addslashes($item) . '\')">Rename</button>';
                echo '<button class="btn btn-danger" onclick="deleteItem(\'' . addslashes($full_path) . '\')">Delete</button>';
                echo '</div>';
                echo '</div>';
            }
            
            // Display files
            foreach ($files as $item) {
                $full_path = $current_dir . '/' . $item;
                $stat = stat($full_path);
                echo '<div class="file-item">';
                echo '<span class="file-icon">' . get_file_icon($item) . '</span>';
                echo '<span class="file-name">' . htmlspecialchars($item) . '</span>';
                echo '<span class="file-size">' . format_size($stat['size']) . '</span>';
                echo '<span class="file-date">' . date('Y-m-d H:i', $stat['mtime']) . '</span>';
                echo '<div class="file-actions">';
                
                if (in_array(strtolower(pathinfo($item, PATHINFO_EXTENSION)), ['txt', 'php', 'html', 'css', 'js', 'json', 'xml'])) {
                    echo '<button class="btn" onclick="editFile(\'' . addslashes($full_path) . '\')">Edit</button>';
                }
                
                echo '<a href="?download=' . urlencode(str_replace(BASE_PATH, '', $full_path)) . '" class="btn">Download</a>';
                
                if (in_array(strtolower(pathinfo($item, PATHINFO_EXTENSION)), ['zip', 'rar', 'tar', 'gz'])) {
                    echo '<button class="btn" onclick="extractArchive(\'' . addslashes($full_path) . '\')">Extract</button>';
                }
                
                echo '<button class="btn" onclick="renameItem(\'' . addslashes($full_path) . '\', \'' . addslashes($item) . '\')">Rename</button>';
                echo '<button class="btn btn-danger" onclick="deleteItem(\'' . addslashes($full_path) . '\')">Delete</button>';
                echo '</div>';
                echo '</div>';
            }
            
            if (empty($dirs) && empty($files)) {
                echo '<div class="file-item">Directory is empty</div>';
            }
            ?>
        </div>
    </div>

    <!-- Modals -->
    <div id="createFolderModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Create New Folder</h3>
                <span class="close" onclick="hideModal('createFolderModal')">&times;</span>
            </div>
            <form id="createFolderForm">
                <div class="form-group">
                    <label>Folder Name:</label>
                    <input type="text" name="name" required>
                </div>
                <input type="hidden" name="path" value="<?php echo htmlspecialchars($current_dir); ?>">
                <button type="submit" class="btn btn-success">Create</button>
            </form>
        </div>
    </div>

    <div id="createFileModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Create New File</h3>
                <span class="close" onclick="hideModal('createFileModal')">&times;</span>
            </div>
            <form id="createFileForm">
                <div class="form-group">
                    <label>File Name:</label>
                    <input type="text" name="name" required>
                </div>
                <div class="form-group">
                    <label>Content:</label>
                    <textarea name="content" rows="10"></textarea>
                </div>
                <input type="hidden" name="path" value="<?php echo htmlspecialchars($current_dir); ?>">
                <button type="submit" class="btn btn-success">Create</button>
            </form>
        </div>
    </div>

    <div id="uploadModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Upload File</h3>
                <span class="close" onclick="hideModal('uploadModal')">&times;</span>
            </div>
            <form id="uploadForm" enctype="multipart/form-data">
                <div class="form-group">
                    <label>Select File:</label>
                    <input type="file" name="file" required>
                </div>
                <input type="hidden" name="path" value="<?php echo htmlspecialchars($current_dir); ?>">
                <button type="submit" class="btn btn-success">Upload</button>
            </form>
        </div>
    </div>

    <div id="editFileModal" class="modal">
        <div class="modal-content" style="max-width: 800px;">
            <div class="modal-header">
                <h3>Edit File</h3>
                <span class="close" onclick="hideModal('editFileModal')">&times;</span>
            </div>
            <form id="editFileForm">
                <div class="form-group">
                    <label>File Content:</label>
                    <textarea id="fileContent" name="content" rows="20" style="font-family: monospace;"></textarea>
                </div>
                <input type="hidden" id="editFilePath" name="path">
                <button type="submit" class="btn btn-success">Save</button>
            </form>
        </div>
    </div>

    <script>
        // Modal functions
        function showModal(modalId) {
            document.getElementById(modalId).style.display = 'block';
        }

        function hideModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            if (event.target.className === 'modal') {
                event.target.style.display = 'none';
            }
        }

        // Form submissions
        document.getElementById('createFolderForm').onsubmit = function(e) {
            e.preventDefault();
            submitForm('createFolderForm', 'create_folder');
        };

        document.getElementById('createFileForm').onsubmit = function(e) {
            e.preventDefault();
            submitForm('createFileForm', 'create_file');
        };

        document.getElementById('uploadForm').onsubmit = function(e) {
            e.preventDefault();
            submitUploadForm();
        };

        document.getElementById('editFileForm').onsubmit = function(e) {
            e.preventDefault();
            submitForm('editFileForm', 'edit_file');
        };

        function submitForm(formId, action) {
            const form = document.getElementById(formId);
            const formData = new FormData(form);
            formData.append('action', action);

            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                if (data.success) {
                    hideModal(formId.replace('Form', 'Modal'));
                    location.reload();
                }
            })
            .catch(error => {
                alert('Error: ' + error);
            });
        }

        function submitUploadForm() {
            const formData = new FormData(document.getElementById('uploadForm'));
            formData.append('action', 'upload');

            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                if (data.success) {
                    hideModal('uploadModal');
                    location.reload();
                }
            })
            .catch(error => {
                alert('Error: ' + error);
            });
        }

        // File operations
        function deleteItem(path) {
            if (confirm('Are you sure you want to delete this item?')) {
                const formData = new FormData();
                formData.append('action', 'delete');
                formData.append('path', path);

                fetch('', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    alert(data.message);
                    if (data.success) {
                        location.reload();
                    }
                });
            }
        }

        function renameItem(path, currentName) {
            const newName = prompt('Enter new name:', currentName);
            if (newName && newName !== currentName) {
                const formData = new FormData();
                formData.append('action', 'rename');
                formData.append('path', path);
                formData.append('new_name', newName);

                fetch('', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    alert(data.message);
                    if (data.success) {
                        location.reload();
                    }
                });
            }
        }

        function editFile(path) {
            fetch('', {
                method: 'POST',
                body: new URLSearchParams({
                    'action': 'get_file',
                    'path': path
                })
            })
            .then(response => response.text())
            .then(content => {
                document.getElementById('fileContent').value = content;
                document.getElementById('editFilePath').value = path;
                showModal('editFileModal');
            })
            .catch(error => {
                alert('Error loading file: ' + error);
            });
        }

        function extractArchive(path) {
            if (confirm('Extract archive here?')) {
                const formData = new FormData();
                formData.append('action', 'extract');
                formData.append('archive', path);
                formData.append('path', '<?php echo htmlspecialchars($current_dir); ?>');

                fetch('', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    alert(data.message);
                    if (data.success) {
                        location.reload();
                    }
                });
            }
        }

        function refresh() {
            location.reload();
        }

        // Add get_file action handler for PHP
        <?php
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'get_file') {
            $path = sanitize_path($_POST['path'] ?? '');
            if (file_exists($path) && is_file($path)) {
                echo 'echo ' . json_encode(file_get_contents($path)) . ';';
            }
            exit;
        }
        ?>
    </script>
</body>
</html>