<?php
session_start();

// ---------------- LOGOUT ----------------
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: ?");
    exit;
}

// ---------------- LOGIN ----------------
if (!isset($_SESSION['db'])) {
    if ($_POST) {
        try {
            $dsn = "mysql:host={$_POST['host']};charset=utf8mb4";
            $pdo = new PDO($dsn, $_POST['user'], $_POST['pass']);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            $_SESSION['db'] = [
                'host' => $_POST['host'],
                'user' => $_POST['user'],
                'pass' => $_POST['pass'],
            ];

            header("Location: ?");
            exit;
        } catch (PDOException $e) {
            $error = "Login failed";
        }
    }

    ?>
    <h2>MySQL Login</h2>
    <?php if (!empty($error)) echo "<p style='color:red'>$error</p>"; ?>
    <form method="post">
        Host<br>
        <input name="host" value="localhost"><br><br>
        User<br>
        <input name="user"><br><br>
        Password<br>
        <input type="password" name="pass"><br><br>
        <button>Login</button>
    </form>
    <?php
    exit;
}

// ---------------- CONNECT ----------------
try {
    $cfg = $_SESSION['db'];
    $pdo = new PDO(
        "mysql:host={$cfg['host']};charset=utf8mb4",
        $cfg['user'],
        $cfg['pass']
    );
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    session_destroy();
    die("Connection lost. <a href='?'>Login again</a>");
}

// Selected values
$db     = $_GET['db']    ?? null;
$table  = $_GET['table'] ?? null;
$editId = $_GET['edit']  ?? null;

echo "<div style='float:right'><a href='?logout=1'>Logout</a></div>";

// ---------------- DATABASE LIST ----------------
if (!$db) {
    echo "<h2>Select Database</h2>";
    foreach ($pdo->query("SHOW DATABASES") as $row) {
        echo "<a href='?db={$row['Database']}'>{$row['Database']}</a><br>";
    }
    exit;
}

// Use selected DB
$pdo->exec("USE `$db`");

// ---------------- TABLE LIST ----------------
if (!$table) {
    echo "<h2>Database: $db</h2>";
    echo "<a href='?'>⬅ Databases</a><br><br>";

    foreach ($pdo->query("SHOW TABLES") as $row) {
        $t = array_values($row)[0];
        echo "<a href='?db=$db&table=$t'>$t</a><br>";
    }
    exit;
}

// ---------------- EDIT ROW ----------------
if ($editId) {
    $cols = $pdo->query("DESCRIBE `$table`")->fetchAll(PDO::FETCH_COLUMN);

    if ($_POST) {
        $set = [];
        foreach ($cols as $col) {
            $set[] = "`$col` = :$col";
        }

        $sql = "UPDATE `$table` SET " . implode(", ", $set) . " WHERE `$cols[0]` = :id";
        $stmt = $pdo->prepare($sql);

        foreach ($cols as $col) {
            $stmt->bindValue(":$col", $_POST[$col]);
        }
        $stmt->bindValue(":id", $editId);
        $stmt->execute();

        header("Location: ?db=$db&table=$table");
        exit;
    }

    $row = $pdo->query("SELECT * FROM `$table` WHERE `$cols[0]` = '$editId'")->fetch();

    echo "<h2>Edit Row</h2>";
    echo "<form method='post'>";
    foreach ($row as $k => $v) {
        echo "$k<br>";
        echo "<input name='$k' value='" . htmlspecialchars($v) . "'><br><br>";
    }
    echo "<button>Save</button>";
    echo "</form>";
    exit;
}

// ---------------- VIEW TABLE ----------------
echo "<h2>Table: $table</h2>";
echo "<a href='?db=$db'>⬅ Tables</a><br><br>";

$rows = $pdo->query("SELECT * FROM `$table` LIMIT 50")->fetchAll(PDO::FETCH_ASSOC);

if (!$rows) {
    echo "No data.";
    exit;
}

echo "<table border='1' cellpadding='5'><tr>";
foreach (array_keys($rows[0]) as $col) {
    echo "<th>$col</th>";
}
echo "<th>Edit</th></tr>";

foreach ($rows as $r) {
    echo "<tr>";
    foreach ($r as $v) {
        echo "<td>" . htmlspecialchars($v) . "</td>";
    }
    $id = array_values($r)[0];
    echo "<td><a href='?db=$db&table=$table&edit=$id'>Edit</a></td>";
    echo "</tr>";
}
echo "</table>";
