<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/auth.php';
function_admin_login_erfordern();

/* =========================
   SCOPE / SECURITY
   ========================= */
$BASE_DIR = '/var/www/wecker/html';
$BASE_REAL = realpath($BASE_DIR);
if ($BASE_REAL === false) {
    http_response_code(500);
    die('BASE_DIR ungültig');
}

function h($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

function resolvePath($rel){
    global $BASE_DIR, $BASE_REAL;
    $rel = str_replace(["\0","\\"],['','/'],$rel);
    $rel = ltrim($rel,'/');
    if ($rel === '' || $rel === '.') return [$BASE_REAL,true];
    $candidate = $BASE_DIR.'/'.$rel;
    $real = realpath($candidate);
    if ($real === false) return [$candidate,false];
    return [$real, str_starts_with($real,$BASE_REAL)];
}

function isTextFile($p){
    return in_array(strtolower(pathinfo($p,PATHINFO_EXTENSION)),[
        'txt','log','conf','ini','php','sh','js','css',
        'html','htm','json','xml','yml','yaml','md','env','csv'
    ],true);
}

/* =========================
   PATH STATE
   ========================= */
$p = $_GET['p'] ?? '';
[$curPath,$ok] = resolvePath($p);
if (!$ok || !is_dir($curPath)) {
    http_response_code(403);
    die('Zugriff verweigert');
}

$curRel = trim(str_replace($BASE_DIR,'',$curPath),'/');
$parentRel = trim(dirname($curRel),'/');
$viewRel = $_GET['view'] ?? '';
$downloadRel = $_GET['dl'] ?? '';

/* =========================
   DOWNLOAD
   ========================= */
if ($downloadRel !== '') {
    [$dp,$ok] = resolvePath($downloadRel);
    if (!$ok || !is_file($dp)) {
        http_response_code(404);
        exit;
    }
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($dp).'"');
    header('Content-Length: '.filesize($dp));
    readfile($dp);
    exit;
}

/* =========================
   ACTIONS
   ========================= */
$notice = '';
$error  = '';

if ($_SERVER['REQUEST_METHOD']==='POST') {
    $action = $_POST['action'] ?? '';
    try {

        if ($action==='mkdir') {
            $name = trim($_POST['name'] ?? '');
            if ($name==='' || strpbrk($name,'/\\')) throw new RuntimeException('Ungültiger Name');
            mkdir($curPath.'/'.$name,0755) || throw new RuntimeException('mkdir fehlgeschlagen');
            $notice='Ordner erstellt';
        }

        if ($action==='upload') {
            if (!isset($_FILES['file'])) throw new RuntimeException('Kein Upload');
            $f=$_FILES['file'];
            if ($f['error']!==UPLOAD_ERR_OK) throw new RuntimeException('Upload-Fehler');
            move_uploaded_file($f['tmp_name'],$curPath.'/'.basename($f['name']))
                || throw new RuntimeException('Upload fehlgeschlagen');
            $notice='Upload ok';
        }

        if ($action==='delete') {
            [$tp,$ok]=resolvePath($_POST['target']??'');
            if(!$ok) throw new RuntimeException('Ungültiger Pfad');
            if (is_dir($tp)) {
                if (count(array_diff(scandir($tp),['.','..']))>0)
                    throw new RuntimeException('Ordner nicht leer');
                rmdir($tp);
            } else {
                unlink($tp);
            }
            $notice='Gelöscht';
        }

        if ($action==='rename') {
            $new = trim($_POST['new_name']??'');
            if ($new===''||strpbrk($new,'/\\')) throw new RuntimeException('Ungültiger Name');
            [$tp,$ok]=resolvePath($_POST['target']??'');
            if(!$ok) throw new RuntimeException('Ungültiger Pfad');
            rename($tp,dirname($tp).'/'.$new) || throw new RuntimeException('Rename fehlgeschlagen');
            $notice='Umbenannt';
        }

    } catch(Throwable $e){
        $error=$e->getMessage();
    }
    header('Location: ?p='.rawurlencode($curRel));
    exit;
}

/* =========================
   VIEWER
   ========================= */
$viewerTitle='Datei-Vorschau';
$viewerContent='';

if ($viewRel!=='') {
    [$vp,$ok]=resolvePath($viewRel);
    if ($ok && is_file($vp) && isTextFile($vp)) {
        $viewerTitle=basename($vp);
        $viewerContent=file_get_contents($vp) ?: 'Nicht lesbar';
    } else {
        $viewerContent='Keine Vorschau möglich';
    }
}

$entries=scandir($curPath);
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<title>Datei Explorer</title>

<style>
:root{
    --bg:#0f1115;
    --panel:#151922;
    --border:#2a2f3a;
    --text:#e6e6e6;
    --accent:#4da3ff;
    --err:#ff6b6b;
    --ok:#5dff8a;
}

*{box-sizing:border-box}

body{
    margin:0;
    background:var(--bg);
    color:var(--text);
    font-family:system-ui,sans-serif;
    padding:24px;
}

.box{
    background:var(--panel);
    border:1px solid var(--border);
    padding:20px;
    width:100%;
}

/* FLEX LAYOUT */
.layout{
    display:flex;
    gap:16px;
    align-items:stretch;
}

.left{
    flex: 1 1 65%;
}

.right{
    flex: 1 1 35%;
    display:flex;
    flex-direction:column;
}

.grid{
    background:#0f1420;
    border:1px solid var(--border);
}

.row{
    display:flex;
    align-items:center;
    gap:8px;
    padding:8px;
    border-top:1px solid var(--border);
}

.row.header{
    background:#12192a;
    font-weight:600;
}

.cell-name{flex:1}
.cell-size{width:90px}
.cell-type{width:70px}
.cell-actions{
    width:360px;
    display:flex;
    gap:6px;
    justify-content:flex-end;
}

button,.btn{
    padding:5px 10px;
    background:#1c2130;
    border:1px solid var(--border);
    color:var(--text);
    cursor:pointer;
    text-decoration:none;
}

button:hover,.btn:hover{border-color:var(--accent)}

.viewer{
    background:#0f1420;
    border:1px solid var(--border);
    padding:12px;
    display:flex;
    flex-direction:column;
    height:100%;
}

pre{
    flex:1;
    overflow:auto;
    border:1px solid var(--border);
    padding:10px;
    margin:0;
    white-space:pre;
    font-family:monospace;
}

.small{font-size:12px;color:#cfd3dc;font-family:monospace}
.notice{color:var(--ok)}
.error{color:var(--err)}
</style>
</head>

<body>

<div class="box">
<h2 style="color:var(--accent)">Datei Explorer</h2>
<div class="small">Pfad: /<?=h($curRel)?></div>

<div class="layout">

<!-- LEFT -->
<div class="left">

<div style="margin:10px 0; display:flex; gap:10px; align-items:center;">
<form method="post" style="display:flex; gap:6px;">
<input type="hidden" name="action" value="mkdir">
<input type="text" name="name" placeholder="Ordner">
<button>+</button>
</form>

<form method="post" enctype="multipart/form-data" style="display:flex; gap:6px;">
<input type="hidden" name="action" value="upload">
<input type="file" name="file">
<button>Upload</button>
</form>
</div>

<div class="grid">
<div class="row header">
    <div class="cell-name">Name</div>
    <div class="cell-size">Größe</div>
    <div class="cell-type">Typ</div>
    <div class="cell-actions">Aktionen</div>
</div>

<?php foreach($entries as $e):
if($e==='.'||$e==='..') continue;
$abs=$curPath.'/'.$e;
$rel=ltrim(str_replace($BASE_DIR,'',$abs),'/');
$isDir=is_dir($abs);
?>
<div class="row">
    <div class="cell-name">
        <?= $isDir ? '<a href="?p='.h($rel).'">'.h($e).'</a>' : h($e) ?>
    </div>
    <div class="cell-size small"><?= $isDir?'-':filesize($abs) ?></div>
    <div class="cell-type small"><?= $isDir?'DIR':'FILE' ?></div>
    <div class="cell-actions">
        <?php if(!$isDir): ?>
            <a class="btn" href="?dl=<?=h($rel)?>">DL</a>
            <?php if(isTextFile($abs)): ?>
                <a class="btn" href="?p=<?=h($curRel)?>&view=<?=h($rel)?>">View</a>
            <?php endif; ?>
        <?php endif; ?>

        <form method="post">
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="target" value="<?=h($rel)?>">
            <button onclick="return confirm('Löschen?')">Del</button>
        </form>

        <form method="post" style="display:flex; gap:4px;">
            <input type="hidden" name="action" value="rename">
            <input type="hidden" name="target" value="<?=h($rel)?>">
            <input type="text" name="new_name" placeholder="Neu">
            <button>Ren</button>
        </form>
    </div>
</div>
<?php endforeach; ?>
</div>
</div>

<!-- RIGHT -->
<div class="right">
<div class="viewer">
<h3 style="color:var(--accent)"><?=h($viewerTitle)?></h3>
<?= $viewerContent ? '<pre>'.h($viewerContent).'</pre>' : '<div class="small">Datei auswählen</div>' ?>
</div>
</div>

</div>

<?php if($notice):?><div class="notice"><?=h($notice)?></div><?php endif;?>
<?php if($error):?><div class="error"><?=h($error)?></div><?php endif;?>

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