<?php
// file_manager.php - Simple File Manager with Back Button
session_start();
error_reporting(0);

// ==================== CONFIGURATION ====================
$base_dir = realpath(__DIR__);
$root_anchor = dirname($base_dir);

// ==================== HELPER FUNCTIONS ====================
function sanitize_path($path){
    $path = str_replace('..', '', $path);
    $path = preg_replace('/[^a-zA-Z0-9\.\_\-\/]/', '', $path);
    return trim($path, '/');
}

function safe_realpath_within($path, $allowed_root){
    $rp = realpath($path);
    if($rp === false) return false;
    
    $root = rtrim($allowed_root, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
    if(strpos($rp, $root) === 0 || $rp === rtrim($allowed_root, DIRECTORY_SEPARATOR)) {
        return $rp;
    }
    return false;
}

function get_file_list($dir){
    $files = [];
    if(is_dir($dir)){
        $items = scandir($dir);
        foreach($items as $item){
            if($item === '.' || $item === '..') continue;
            $full_path = $dir . DIRECTORY_SEPARATOR . $item;
            $files[] = [
                'name' => $item,
                'path' => $full_path,
                'size' => is_file($full_path) ? filesize($full_path) : 0,
                'type' => is_dir($full_path) ? 'directory' : 'file',
                'modified' => date('Y-m-d H:i:s', filemtime($full_path))
            ];
        }
    }
    return $files;
}

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';
    }
}

// ==================== REQUESTED DIRECTORY HANDLING ====================
$requested_dir = isset($_GET['dir']) ? sanitize_path($_GET['dir']) : basename($base_dir);
$current_dir_candidate = $root_anchor . ($requested_dir ? DIRECTORY_SEPARATOR . $requested_dir : '');
$current_dir = safe_realpath_within($current_dir_candidate, $root_anchor);

if($current_dir === false){
    $requested_dir = basename($base_dir);
    $current_dir = safe_realpath_within($root_anchor . DIRECTORY_SEPARATOR . $requested_dir, $root_anchor);
    if($current_dir === false){
        $requested_dir = '';
        $current_dir = safe_realpath_within($root_anchor, $root_anchor);
    }
}

// ==================== PARENT DIRECTORY CALCULATION ====================
if($requested_dir !== ''){
    $parent_dir = dirname($requested_dir);
    if($parent_dir === '.' || $parent_dir === '\\') $parent_dir = '';
} else {
    $parent_dir = '';
}

// ==================== BREADCRUMB ====================
$dir_parts = [];
if($requested_dir !== ''){
    $parts = explode('/', $requested_dir);
    $acc = '';
    foreach($parts as $p){
        if($p === '') continue;
        $acc .= ($acc === '' ? '' : '/') . $p;
        $dir_parts[] = ['name' => $p, 'path' => $acc];
    }
}

// ==================== ACTION HANDLING ====================
$action = $_GET['action'] ?? 'list';

switch($action){
    case 'view':
        $file = sanitize_path($_GET['file'] ?? '');
        $file_path = $current_dir . DIRECTORY_SEPARATOR . $file;
        if(safe_realpath_within($file_path, $root_anchor) && is_file($file_path)){
            header('Content-Type: text/plain');
            readfile($file_path);
            exit;
        }
        break;

    case 'edit':
        $file = sanitize_path($_GET['file'] ?? '');
        $file_path = $current_dir . DIRECTORY_SEPARATOR . $file;
        if($_SERVER['REQUEST_METHOD'] === 'POST'){
            $content = $_POST['content'] ?? '';
            if(safe_realpath_within($file_path, $root_anchor) && is_file($file_path)){
                file_put_contents($file_path, $content);
            }
            header('Location: ?action=list&dir=' . urlencode($requested_dir));
            exit;
        }
        if(safe_realpath_within($file_path, $root_anchor) && is_file($file_path)){
            $content = htmlspecialchars(file_get_contents($file_path));
            echo "<!DOCTYPE html><html><head><meta charset='utf-8'><title>Edit: ".htmlspecialchars($file)."</title></head><body>";
            echo "<h2>✏️ Edit: ".htmlspecialchars($file)."</h2>";
            echo "<form method='post'>";
            echo "<textarea name='content' style='width:100%;height:400px;font-family:monospace;'>$content</textarea><br><br>";
            echo "<button type='submit'>💾 Save</button> ";
            echo "<a href='?action=list&dir=".urlencode($requested_dir)."'>🚫 Cancel</a>";
            echo "</form></body></html>";
            exit;
        }
        break;

    case 'delete':
        $file = sanitize_path($_GET['file'] ?? '');
        $file_path = $current_dir . DIRECTORY_SEPARATOR . $file;
        if(safe_realpath_within($file_path, $root_anchor) && file_exists($file_path)){
            if(is_dir($file_path)){
                $it = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator($file_path, RecursiveDirectoryIterator::SKIP_DOTS),
                    RecursiveIteratorIterator::CHILD_FIRST
                );
                foreach($it as $f){
                    $f->isDir() ? rmdir($f->getRealPath()) : unlink($f->getRealPath());
                }
                rmdir($file_path);
            } else {
                unlink($file_path);
            }
        }
        header('Location: ?action=list&dir=' . urlencode($requested_dir));
        exit;
        break;

    case 'upload':
        if(!empty($_FILES['file'])){
            $uploaded = $_FILES['file'];
            if($uploaded['error'] === UPLOAD_ERR_OK){
                $name = basename($uploaded['name']);
                $dest = $current_dir . DIRECTORY_SEPARATOR . $name;
                if(safe_realpath_within(dirname($dest), $root_anchor)){
                    move_uploaded_file($uploaded['tmp_name'], $dest);
                    @chmod($dest, 0644);
                }
            }
        }
        header('Location: ?action=list&dir=' . urlencode($requested_dir));
        exit;
        break;

    case 'download':
        $file = sanitize_path($_GET['file'] ?? '');
        $file_path = $current_dir . DIRECTORY_SEPARATOR . $file;
        if(safe_realpath_within($file_path, $root_anchor) && is_file($file_path)){
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
            header('Content-Length: '.filesize($file_path));
            readfile($file_path);
            exit;
        }
        break;

    case 'create_folder':
        if($_SERVER['REQUEST_METHOD'] === 'POST'){
            $folder = sanitize_path($_POST['folder_name'] ?? '');
            if($folder){
                $fp = $current_dir . DIRECTORY_SEPARATOR . $folder;
                if(safe_realpath_within(dirname($fp), $root_anchor) && !file_exists($fp)){
                    mkdir($fp, 0755, true);
                }
            }
        }
        header('Location: ?action=list&dir=' . urlencode($requested_dir));
        exit;
        break;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>📁 File Manager</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #2c3e50, #34495e);
            color: white;
            padding: 25px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 2.2em;
            margin-bottom: 10px;
            font-weight: 300;
        }
        
        .current-path {
            font-family: 'Courier New', monospace;
            background: rgba(255,255,255,0.1);
            padding: 10px;
            border-radius: 8px;
            margin: 15px 0;
            word-break: break-all;
        }
        
        .navigation {
            background: #ecf0f1;
            padding: 20px;
            border-bottom: 1px solid #bdc3c7;
        }
        
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 12px 20px;
            background: #3498db;
            color: white;
            text-decoration: none;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s ease;
            border: none;
            cursor: pointer;
            font-size: 14px;
        }
        
        .btn:hover {
            background: #2980b9;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        
        .btn-secondary {
            background: #95a5a6;
        }
        
        .btn-secondary:hover {
            background: #7f8c8d;
        }
        
        .btn-danger {
            background: #e74c3c;
        }
        
        .btn-danger:hover {
            background: #c0392b;
        }
        
        .btn-success {
            background: #27ae60;
        }
        
        .btn-success:hover {
            background: #219a52;
        }
        
        .toolbar {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            margin-bottom: 20px;
        }
        
        .breadcrumb {
            background: #f8f9fa;
            padding: 15px 25px;
            border-bottom: 1px solid #dee2e6;
        }
        
        .breadcrumb a {
            color: #3498db;
            text-decoration: none;
        }
        
        .breadcrumb span {
            color: #7f8c8d;
            margin: 0 8px;
        }
        
        .file-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .file-table th {
            background: #34495e;
            color: white;
            padding: 15px;
            text-align: left;
            font-weight: 500;
        }
        
        .file-table td {
            padding: 15px;
            border-bottom: 1px solid #ecf0f1;
        }
        
        .file-table tr:hover {
            background: #f8f9fa;
        }
        
        .file-icon {
            width: 20px;
            text-align: center;
            margin-right: 10px;
        }
        
        .folder-row {
            background: #f0f8ff;
        }
        
        .folder-row:hover {
            background: #e3f2fd !important;
        }
        
        .action-buttons {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }
        
        .empty-folder {
            text-align: center;
            padding: 60px 20px;
            color: #7f8c8d;
        }
        
        .empty-folder i {
            font-size: 3em;
            margin-bottom: 20px;
            display: block;
        }
        
        .upload-form, .folder-form {
            display: flex;
            gap: 10px;
            align-items: center;
        }
        
        input[type="text"], input[type="file"] {
            padding: 10px;
            border: 1px solid #bdc3c7;
            border-radius: 6px;
            font-size: 14px;
        }
        
        input[type="text"] {
            min-width: 200px;
        }
        
        @media (max-width: 768px) {
            .toolbar {
                flex-direction: column;
            }
            
            .upload-form, .folder-form {
                flex-direction: column;
                align-items: stretch;
            }
            
            .action-buttons {
                flex-direction: column;
            }
            
            .btn {
                justify-content: center;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📁 File Manager</h1>
            <div class="current-path">
                📍 <?= htmlspecialchars($current_dir) ?>
            </div>
        </div>
        
        <div class="navigation">
            <div class="toolbar">
                <!-- Back Button -->
                <a class="btn" href="?action=list&dir=<?= urlencode($parent_dir) ?>">
                    ⬅️ Back
                </a>
                
                <!-- Home Button -->
                <a class="btn btn-secondary" href="?action=list&dir=<?= urlencode(basename($base_dir)) ?>">
                    🏠 Project
                </a>
                
                <!-- Root Button -->
                <a class="btn btn-secondary" href="?action=list&dir=">
                    📂 Root
                </a>
                
                <!-- Upload Form -->
                <form method="post" enctype="multipart/form-data" action="?action=upload&dir=<?= urlencode($requested_dir) ?>" class="upload-form">
                    <input type="file" name="file" required>
                    <button class="btn btn-success" type="submit">📤 Upload</button>
                </form>
                
                <!-- Create Folder Form -->
                <form method="post" action="?action=create_folder&dir=<?= urlencode($requested_dir) ?>" class="folder-form">
                    <input type="text" name="folder_name" placeholder="New Folder Name" required>
                    <button class="btn btn-success" type="submit">📁 Create Folder</button>
                </form>
            </div>
        </div>
        
        <div class="breadcrumb">
            <a href="?action=list&dir=">Root</a>
            <?php foreach($dir_parts as $p): ?>
                <span>›</span>
                <a href="?action=list&dir=<?= urlencode($p['path']) ?>"><?= htmlspecialchars($p['name']) ?></a>
            <?php endforeach; ?>
        </div>
        
        <?php
        $files = get_file_list($current_dir);
        if(empty($files)): 
        ?>
            <div class="empty-folder">
                <i>📭</i>
                <h3>This folder is empty</h3>
                <p>Upload files or create new folders to get started</p>
            </div>
        <?php else: ?>
            <table class="file-table">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Type</th>
                        <th>Size</th>
                        <th>Modified</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($files as $f): ?>
                        <tr class="<?= $f['type'] === 'directory' ? 'folder-row' : '' ?>">
                            <td>
                                <span class="file-icon">
                                    <?= $f['type'] === 'directory' ? '📁' : '📄' ?>
                                </span>
                                <?= htmlspecialchars($f['name']) ?>
                            </td>
                            <td><?= $f['type'] ?></td>
                            <td><?= $f['type'] === 'directory' ? '-' : format_size($f['size']) ?></td>
                            <td><?= $f['modified'] ?></td>
                            <td>
                                <div class="action-buttons">
                                    <?php if($f['type'] === 'directory'): 
                                        $next_rel = ($requested_dir !== '' ? $requested_dir . '/' : '') . $f['name'];
                                    ?>
                                        <a class="btn" href="?action=list&dir=<?= urlencode($next_rel) ?>">
                                            📂 Open
                                        </a>
                                    <?php else: ?>
                                        <a class="btn" href="?action=edit&file=<?= urlencode($f['name']) ?>&dir=<?= urlencode($requested_dir) ?>">
                                            ✏️ Edit
                                        </a>
                                        <a class="btn btn-secondary" href="?action=download&file=<?= urlencode($f['name']) ?>&dir=<?= urlencode($requested_dir) ?>">
                                            📥 Download
                                        </a>
                                    <?php endif; ?>
                                    <a class="btn btn-danger" href="?action=delete&file=<?= urlencode($f['name']) ?>&dir=<?= urlencode($requested_dir) ?>" 
                                       onclick="return confirm('Are you sure you want to delete <?= htmlspecialchars($f['name']) ?>?')">
                                        🗑️ Delete
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

    <script>
        // Add some interactive features
        document.addEventListener('DOMContentLoaded', function() {
            // Add confirmation for delete actions
            const deleteLinks = document.querySelectorAll('a[href*="action=delete"]');
            deleteLinks.forEach(link => {
                link.addEventListener('click', function(e) {
                    if (!confirm('Are you sure you want to delete this item?')) {
                        e.preventDefault();
                    }
                });
            });
            
            // Add hover effects
            const rows = document.querySelectorAll('.file-table tr');
            rows.forEach(row => {
                row.addEventListener('mouseenter', function() {
                    this.style.transform = 'translateX(5px)';
                    this.style.transition = 'transform 0.2s ease';
                });
                
                row.addEventListener('mouseleave', function() {
                    this.style.transform = 'translateX(0)';
                });
            });
        });
    </script>
</body>
</html>