<?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');
}

$action = $_GET['action'] ?? '';

if ($action === 'table') {
    $table = preg_replace('/[^a-zA-Z0-9_]/','',$_GET['name']);
    $cols = $pdo->query("DESCRIBE `$table`")->fetchAll();
    $pk = null; foreach ($cols as $c) if ($c['Key']==='PRI') $pk=$c['Field'];

    $rows = $pdo->query("SELECT * FROM `$table` LIMIT 500")->fetchAll();

    echo "<h3>$table</h3><table><tr>";
    foreach ($cols as $c) echo "<th>{$c['Field']}</th>";
    echo "</tr>";

    foreach ($rows as $r){
        echo "<tr>";
        foreach ($cols as $c){
            $f=$c['Field']; $v=htmlspecialchars((string)$r[$f]);
            if ($f===$pk) echo "<td>$v</td>";
            else echo "<td contenteditable oninput=\"markDirty('$table','$pk','{$r[$pk]}','$f',this)\">$v</td>";
        }
        echo "</tr>";
    }

    echo "<tr class='insert-row'>";
    foreach ($cols as $c){
        echo $c['Extra']==='auto_increment' ? "<td></td>" : "<td contenteditable data-field='{$c['Field']}'></td>";
    }
    echo "</tr></table>";
    exit;
}

if ($action === 'update') {
    $d=json_decode(file_get_contents('php://input'),true);
    $pdo->prepare("UPDATE `{$d['table']}` SET `{$d['field']}`=:v WHERE `{$d['pk']}`=:pk")
        ->execute([':v'=>$d['value'],':pk'=>$d['pkVal']]);
    exit;
}

if ($action === 'insert') {
    $d=json_decode(file_get_contents('php://input'),true);
    $fields=array_keys($d['data']);
    $sql="INSERT INTO `{$d['table']}` (`".implode('`,`',$fields)."`) VALUES (:".implode(',:',$fields).")";
    $pdo->prepare($sql)->execute($d['data']);
    exit;
}

if ($action === 'sql') {
    $d=json_decode(file_get_contents('php://input'),true);
    $sql=trim($d['sql']);
    try{
        if (stripos($sql,'select')===0){
            $rows=$pdo->query($sql)->fetchAll();
            if(!$rows){ echo "<p>Keine Ergebnisse</p>"; exit; }
            echo "<table><tr>";
            foreach(array_keys($rows[0]) as $c) echo "<th>$c</th>";
            echo "</tr>";
            foreach($rows as $r){ echo "<tr>"; foreach($r as $v) echo "<td>".htmlspecialchars((string)$v)."</td>"; echo "</tr>"; }
            echo "</table>";
        } else {
            $cnt=$pdo->exec($sql);
            echo "<p>$cnt Zeilen betroffen</p>";
        }
    } catch(Throwable $e){
        echo "<pre style='color:#ff6b6b'>".$e->getMessage()."</pre>";
    }
    exit;
}
