<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/auth.php';

function_admin_login_erfordern();

if (!defined('DatabaseDEBUG') || DatabaseDEBUG !== true) {
    http_response_code(403);
    exit('Access denied');
}

$tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<title>DB Viewer</title>

<style>
:root{
    --bg:#0f1115;--panel:#151922;--border:#2a2f3a;--text:#e6e6e6;--accent:#4da3ff;
}
*{box-sizing:border-box}
body{margin:0;font-family:system-ui,sans-serif;background:var(--bg);color:var(--text);display:flex;height:100vh}

/* Sidebar */
#sidebar{width:260px;background:var(--panel);border-right:1px solid var(--border);padding:12px;overflow:auto}
#sidebar input{width:100%;margin-bottom:10px;padding:6px;background:#1c2130;border:1px solid var(--border);color:var(--text)}
#sidebar a{display:block;padding:6px 8px;color:var(--text);text-decoration:none;border-radius:4px}
#sidebar a:hover{background:var(--border)}

/* Main */
#main{flex:1;display:flex;flex-direction:column}
#content{flex:1;padding:16px;overflow:auto}

/* Table */
table{width:100%;border-collapse:collapse}
th,td{border:1px solid var(--border);padding:6px}
th{background:#1a1f2c}
td[contenteditable]{background:#131722}
tr.insert-row td{background:#0c2a1a}

/* SQL Button */
#sqlBtn{
    position:fixed;left:12px;bottom:12px;
    padding:8px 12px;background:#1c2130;border:1px solid var(--border);
    color:var(--text);cursor:pointer;border-radius:6px
}
#sqlBtn:hover{border-color:var(--accent)}

/* SQL Modal */
#sqlModal{
    position:fixed;inset:0;background:rgba(0,0,0,.6);
    display:none;align-items:center;justify-content:center
}
#sqlBox{
    width:70%;max-width:900px;background:#0c0f16;border:1px solid var(--border);
    padding:12px;border-radius:8px
}
#sqlBox textarea{
    width:100%;height:200px;background:#0f1420;color:var(--text);
    border:1px solid var(--border);padding:10px;font-family:monospace
}
.actions{display:flex;gap:10px;margin-top:10px}
button{background:#1c2130;border:1px solid var(--border);color:var(--text);padding:6px 10px;cursor:pointer}
button:hover{border-color:var(--accent)}
</style>
</head>

<body>

<div id="sidebar">
    <input placeholder="Tabelle suchen…" onkeyup="filterTables(this)">
    <div id="tableList">
        <?php foreach ($tables as $t): ?>
            <a href="#" data-table="<?= htmlspecialchars($t) ?>"
               onclick="loadTable('<?= $t ?>');return false;">
               <?= htmlspecialchars($t) ?>
            </a>
        <?php endforeach; ?>
    </div>
</div>

<div id="main">
    <div id="content"><h3>Tabelle auswählen</h3></div>
</div>

<button id="sqlBtn" onclick="openSQL()">SQL</button>

<div id="sqlModal" onclick="closeSQL(event)">
    <div id="sqlBox">
        <textarea id="sqlInput" placeholder="SQL eingeben…"></textarea>
        <div class="actions">
            <button onclick="runSQL()">Ausführen</button>
            <button onclick="closeSQL()">Schließen</button>
        </div>
        <small style="opacity:.6">STRG+ENTER ausführen · ESC schließen</small>
    </div>
</div>

<script>
let currentTable = null;
let dirtyUpdates = [];

/* Sidebar filter */
function filterTables(i){
    const q=i.value.toLowerCase();
    document.querySelectorAll('#tableList a').forEach(a=>{
        a.style.display=a.dataset.table.toLowerCase().includes(q)?'block':'none';
    });
}

/* Load table */
function loadTable(t){
    currentTable=t;
    dirtyUpdates=[];
    fetch('database_api.php?action=table&name='+t)
        .then(r=>r.text()).then(h=>content.innerHTML=h);
}

/* Track edits */
function markDirty(table,pk,pkVal,field,el){
    dirtyUpdates.push({table,pk,pkVal,field,value:el.innerText});
}

/* Collect insert row */
function collectInsertData(){
    const row=document.querySelector('.insert-row');
    if(!row) return null;

    const data={};
    let hasData=false;

    row.querySelectorAll('[data-field]').forEach(td=>{
        if(td.innerText.trim()!==''){
            data[td.dataset.field]=td.innerText;
            hasData=true;
        }
    });

    return hasData?data:null;
}

/* STRG + S = SAVE ALL */
document.addEventListener('keydown',e=>{
    if((e.ctrlKey||e.metaKey)&&e.key==='s'){
        e.preventDefault();
        saveAll();
    }
    if(e.key==='Escape') closeSQL();
});

function saveAll(){
    if(!currentTable) return;

    const requests=[];

    // updates
    dirtyUpdates.forEach(d=>{
        requests.push(fetch('database_api.php?action=update',{
            method:'POST',
            headers:{'Content-Type':'application/json'},
            body:JSON.stringify(d)
        }));
    });
    dirtyUpdates=[];

    // insert
    const insertData=collectInsertData();
    if(insertData){
        requests.push(fetch('database_api.php?action=insert',{
            method:'POST',
            headers:{'Content-Type':'application/json'},
            body:JSON.stringify({table:currentTable,data:insertData})
        }));
    }

    Promise.all(requests).then(()=>loadTable(currentTable));
}

/* SQL modal */
function openSQL(){sqlModal.style.display='flex';sqlInput.focus();}
function closeSQL(e){if(!e||e.target===sqlModal)sqlModal.style.display='none';}

sqlInput.addEventListener('keydown',e=>{
    if(e.ctrlKey&&e.key==='Enter'){e.preventDefault();runSQL();}
});

function runSQL(){
    fetch('database_api.php?action=sql',{
        method:'POST',
        headers:{'Content-Type':'application/json'},
        body:JSON.stringify({sql:sqlInput.value})
    }).then(r=>r.text()).then(h=>{
        content.innerHTML=h;
        closeSQL();
    });
}
</script>

</body>
</html>
