<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);

/****************************************************
 * CONFIGURACIÓN DE CONEXIÓN (mysqli ONLY)
 ****************************************************/
$host = "localhost";
$user = "root";
$pass = "33comRxXMysql";

$conn = new mysqli($host, $user, $pass);
if ($conn->connect_error) die("Error: " . $conn->connect_error);
$conn->set_charset("utf8mb4");

/****************************************************
 * FUNCIONES ÚTILES
 ****************************************************/
function getDatabases($conn) {
    $arr = [];
    $q = $conn->query("SHOW DATABASES");
    if (!$q) return $arr;
    while ($r = $q->fetch_assoc()) $arr[] = $r["Database"];
    return $arr;
}

function getTables($conn, $db) {
    $arr = [];
    if (!$conn->select_db($db)) return $arr;
    $q = $conn->query("SHOW TABLES");
    if (!$q) return $arr;
    while ($r = $q->fetch_array()) $arr[] = $r[0];
    return $arr;
}

function getColumns($conn, $db, $table) {
    if (!$conn->select_db($db)) return [];
    $arr = [];
    $safe = $conn->real_escape_string($table);
    $q = $conn->query("SHOW FULL COLUMNS FROM `{$safe}`");
    if (!$q) return $arr;
    while ($r = $q->fetch_assoc()) $arr[] = $r;
    return $arr;
}

/**
 * Construye el SQL seguro para DEFAULT:
 */
function buildDefaultSQL($conn, $raw) {
    if ($raw === null || $raw === "") return ""; // omit
    $upper = strtoupper($raw);
    $keywords = ['NULL', 'CURRENT_TIMESTAMP', 'CURRENT_DATE', 'CURRENT_TIME', 'NOW()'];
    if (in_array($upper, $keywords, true)) {
        return "DEFAULT $raw";
    }
    if (is_numeric($raw)) {
        return "DEFAULT $raw";
    }
    $esc = $conn->real_escape_string($raw);
    return "DEFAULT '{$esc}'";
}

/**
 * Validación simple de identificadores (tabla/columna):
 * Permite letras, números y guion bajo.
 */
function safeIdentifier($name) {
    return (is_string($name) && preg_match('/^[A-Za-z0-9_]+$/', $name)) ? $name : false;
}

/****************************************************
 * PROCESAR CRUD (POST)
 ****************************************************/
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // recoger db y tabla (si vienen)
    $db = $_POST["db"] ?? "";
    $table = $_POST["table"] ?? "";

    // If client passed a db, try to select it (not fatal)
    if ($db && !$conn->select_db($db)) {
        $error = "No se pudo seleccionar la base de datos " . htmlspecialchars($db);
    }

    /*************** CREAR TABLA *****************/
    if (isset($_POST['create_table'])) {
        $dbName   = trim($_POST['db_name'] ?? '');
        $newTable = trim($_POST['table_name'] ?? '');

        if (!$dbName || !$newTable) {
            $error = "Faltan datos para crear la tabla.";
        } elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $newTable)) {
            $error = "Nombre de tabla inválido.";
        } else {
            $safeDB = $conn->real_escape_string($dbName);
            $safeTable = $conn->real_escape_string($newTable);
            $sql = "CREATE TABLE `{$safeDB}`.`{$safeTable}` (
                `id` INT NOT NULL AUTO_INCREMENT,
                PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
            if (!$conn->query($sql)) {
                $error = $conn->error;
                $executed = $sql;
            } else {
                // redirect to new table
                header("Location: ".$_SERVER['PHP_SELF']."?db=".urlencode($dbName)."&table=".urlencode($newTable));
                exit;
            }
        }
    }

    /*************** EDITAR COLUMNA *****************/
    if (isset($_POST["edit_column"])) {
        $old = $_POST["old_name"] ?? '';
        $new = $_POST["name"] ?? '';
        $type = $_POST["type"] ?? '';
        $length = trim($_POST["length"] ?? "");
        $null = $_POST["null"] ?? "YES";
        $defaultRaw = $_POST["default"] ?? "";
        $extra = trim($_POST["extra"] ?? "");
        $comment = trim($_POST["comment"] ?? "");

        $old_safe = safeIdentifier($old);
        $new_safe = safeIdentifier($new);

        if (!$old_safe || !$new_safe) {
            $error = "Nombres inválidos (solo letras, números y guion bajo).";
        } else {
            $type_base = strtolower($type);
            $type_sql = $type_base . ($length !== "" ? "($length)" : "");
            $null_sql = ($null === "YES") ? "NULL" : "NOT NULL";
            $default_sql = buildDefaultSQL($conn, $defaultRaw);
            $extra_sql = $extra ? strtoupper($conn->real_escape_string($extra)) : "";
            $comment_sql = $comment !== "" ? "COMMENT '" . $conn->real_escape_string($comment) . "'" : "";

            $sql_parts = array_filter([
                "CHANGE `".$conn->real_escape_string($old)."` `".$conn->real_escape_string($new)."`",
                $type_sql,
                $null_sql,
                $default_sql,
                $extra_sql,
                $comment_sql
            ], function($v){ return $v !== ""; });

            $sql = "ALTER TABLE `".$conn->real_escape_string($table)."` " . implode(" ", $sql_parts);

            if (!$conn->query($sql)) {
                $error = $conn->error;
                $executed = $sql;
            }
        }
    }

    /*************** AGREGAR COLUMNA *****************/
    if (isset($_POST["add_column"])) {
        $name = $_POST["name"] ?? '';
        $type = $_POST["type"] ?? '';
        $length = trim($_POST["length"] ?? "");
        $null = $_POST["null"] ?? "YES";
        $defaultRaw = $_POST["default"] ?? "";
        $extra = trim($_POST["extra"] ?? "");
        $comment = trim($_POST["comment"] ?? "");

        $name_safe = safeIdentifier($name);
        if (!$name_safe) {
            $error = "Nombre de columna inválido.";
        } else {
            $type_sql = strtolower($type) . ($length !== "" ? "($length)" : "");
            $null_sql = ($null === "YES") ? "NULL" : "NOT NULL";
            $default_sql = buildDefaultSQL($conn, $defaultRaw);
            $extra_sql = $extra ? strtoupper($conn->real_escape_string($extra)) : "";
            $comment_sql = $comment !== "" ? "COMMENT '" . $conn->real_escape_string($comment) . "'" : "";

            $sql_parts = array_filter([
                "ADD `".$conn->real_escape_string($name)."`",
                $type_sql,
                $null_sql,
                $default_sql,
                $extra_sql,
                $comment_sql
            ], function($v){ return $v !== ""; });

            $sql = "ALTER TABLE `".$conn->real_escape_string($table)."` " . implode(" ", $sql_parts);

            if (!$conn->query($sql)) {
                $error = $conn->error;
                $executed = $sql;
            }
        }
    }

    /*************** ELIMINAR COLUMNA *****************/
    if (isset($_POST["delete_column"])) {
        $name = $_POST["col_name_delete"] ?? '';
        if (!safeIdentifier($name)) {
            $error = "Nombre de columna inválido.";
        } else {
            $sql = "ALTER TABLE `".$conn->real_escape_string($table)."` DROP COLUMN `".$conn->real_escape_string($name)."`";
            if (!$conn->query($sql)) {
                $error = $conn->error;
                $executed = $sql;
            }
        }
    }

    /*************** RENOMBRAR TABLA *****************/
    if (isset($_POST["rename_table"])) {
        $newName = $_POST["new_table_name"] ?? '';
        if (!safeIdentifier($newName)) {
            $error = "Nombre de tabla inválido.";
        } else {
            $sql = "RENAME TABLE `".$conn->real_escape_string($table)."` TO `".$conn->real_escape_string($newName)."`";
            if (!$conn->query($sql)) {
                $error = $conn->error;
                $executed = $sql;
            } else {
                $table = $newName;
            }
        }
    }

    /*************** ELIMINAR TABLA *****************/
    if (isset($_POST["delete_table"])) {
        $sql = "DROP TABLE `".$conn->real_escape_string($table)."`";
        if (!$conn->query($sql)) {
            $error = $conn->error;
            $executed = $sql;
        } else {
            $table = null;
        }
    }

    /*************** MOVER COLUMNA HACIA ARRIBA ***************/
    if (isset($_POST["move_up"])) {
        $col = $_POST["col"] ?? '';
        if (!safeIdentifier($col)) {
            $error = "Nombre de columna inválido para mover.";
        } else {
            $cols = getColumns($conn, $db, $table);
            $names = array_column($cols, "Field");
            $index = array_search($col, $names, true);

            if ($index !== false && $index > 0) {
                // si queremos mover al primer lugar (poner FIRST) o AFTER otra columna
                if ($index === 1) {
                    // poner FIRST
                    $info = $cols[$index];
                    $type = $info["Type"];
                    $null = ($info["Null"] == "YES") ? "NULL" : "NOT NULL";
                    $default = $info["Default"] !== null ? buildDefaultSQL($conn, $info["Default"]) : "";
                    $extra = $info["Extra"];
                    $comment = $info["Comment"] ? "COMMENT '".$conn->real_escape_string($info["Comment"])."'" : "";

                    $sql = "ALTER TABLE `".$conn->real_escape_string($table)."` MODIFY COLUMN `".$conn->real_escape_string($col)."` $type $null $default $extra $comment FIRST";
                    if (!$conn->query($sql)) { $error = $conn->error; $executed = $sql; }
                } else {
                    // poner AFTER names[index-2]
                    $after = $names[$index - 2];
                    $info = $cols[$index];
                    $type = $info["Type"];
                    $null = ($info["Null"] == "YES") ? "NULL" : "NOT NULL";
                    $default = $info["Default"] !== null ? buildDefaultSQL($conn, $info["Default"]) : "";
                    $extra = $info["Extra"];
                    $comment = $info["Comment"] ? "COMMENT '".$conn->real_escape_string($info["Comment"])."'" : "";

                    $sql = "ALTER TABLE `".$conn->real_escape_string($table)."` MODIFY COLUMN `".$conn->real_escape_string($col)."` $type $null $default $extra $comment AFTER `".$conn->real_escape_string($after)."`";
                    if (!$conn->query($sql)) { $error = $conn->error; $executed = $sql; }
                }
            }
        }

        // redirect to refresh
        header("Location: ".$_SERVER['PHP_SELF']."?db=".urlencode($db)."&table=".urlencode($table));
        exit;
    }

    /*************** MOVER COLUMNA HACIA ABAJO ***************/
    if (isset($_POST["move_down"])) {
        $col = $_POST["col"] ?? '';
        if (!safeIdentifier($col)) {
            $error = "Nombre de columna inválido para mover.";
        } else {
            $cols = getColumns($conn, $db, $table);
            $names = array_column($cols, "Field");
            $index = array_search($col, $names, true);

            if ($index !== false && $index < count($names) - 1) {
                $afterColumn = $names[$index + 1];
                $info = $cols[$index];
                $type = $info["Type"];
                $null = ($info["Null"] == "YES") ? "NULL" : "NOT NULL";
                $default = $info["Default"] !== null ? buildDefaultSQL($conn, $info["Default"]) : "";
                $extra = $info["Extra"];
                $comment = $info["Comment"] ? "COMMENT '".$conn->real_escape_string($info["Comment"])."'" : "";

                $sql = "ALTER TABLE `".$conn->real_escape_string($table)."` MODIFY COLUMN `".$conn->real_escape_string($col)."` $type $null $default $extra $comment AFTER `".$conn->real_escape_string($afterColumn)."`";
                if (!$conn->query($sql)) { $error = $conn->error; $executed = $sql; }
            }
        }

        // redirect to refresh
        header("Location: ".$_SERVER['PHP_SELF']."?db=".urlencode($db)."&table=".urlencode($table));
        exit;
    }

    // redirect by default after other actions
    $location = $_SERVER['PHP_SELF'] . "?db=" . urlencode($db) . ($table ? "&table=" . urlencode($table) : "");
    header("Location: $location");
    exit;
}

/****************************************************
 * VARIABLES DEL GET
 ****************************************************/
$selectDB = $_GET["db"] ?? null;
$selectTable = $_GET["table"] ?? null;

?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Administrador de Base de Datos</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">

<div class="container py-4">

    <div class="d-flex justify-content-between align-items-center mb-3">
        <h2>Administrador de Base de Datos</h2>
        <div>
            <!-- Botón crear tabla -->
            <button class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#createTableModal">Crear tabla</button>
        </div>
    </div>

    <!-- Mensajes -->
    <?php if (!empty($error)): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
        <?php if (!empty($executed)): ?>
            <pre class="small bg-light p-2 border"><?= htmlspecialchars($executed) ?></pre>
        <?php endif; ?>
    <?php endif; ?>

    <!-- Seleccionar DB -->
    <form method="GET" class="mb-3 d-flex align-items-center gap-3">
        <label class="mb-0 fw-bold">Base de datos:</label>
        <select name="db" class="form-select w-auto" onchange="this.form.submit()">
            <option value="">-- seleccionar --</option>
            <?php foreach (getDatabases($conn) as $db): ?>
                <option value="<?= htmlspecialchars($db) ?>" <?= ($db == $selectDB) ? "selected" : "" ?>><?= htmlspecialchars($db) ?></option>
            <?php endforeach; ?>
        </select>
    </form>

    <?php if ($selectDB): ?>
        <!-- Seleccionar tabla -->
        <form method="GET" class="mb-3 d-flex align-items-center gap-3">
            <input type="hidden" name="db" value="<?= htmlspecialchars($selectDB) ?>">
            <label class="mb-0 fw-bold">Tabla:</label>
            <select name="table" class="form-select w-auto" onchange="this.form.submit()">
                <option value="">-- seleccionar --</option>
                <?php foreach (getTables($conn, $selectDB) as $tb): ?>
                    <option value="<?= htmlspecialchars($tb) ?>" <?= ($tb == $selectTable) ? "selected" : "" ?>><?= htmlspecialchars($tb) ?></option>
                <?php endforeach; ?>
            </select>
        </form>
    <?php endif; ?>

    <?php if ($selectDB && $selectTable): ?>

        <div class="mb-3">
            <button class="btn btn-warning me-2" data-bs-toggle="modal" data-bs-target="#renameTableModal">Renombrar tabla</button>
            <button class="btn btn-danger me-2" data-bs-toggle="modal" data-bs-target="#deleteTableModal">Eliminar tabla</button>
            <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addColumnModal">Agregar columna</button>
        </div>

        <h4 class="mb-3">Columnas de: <span class="text-primary"><?= htmlspecialchars($selectTable) ?></span></h4>

        <?php
        // recoger columnas y preparar arrays para modales
        $columns = getColumns($conn, $selectDB, $selectTable);
        $modal_edit = [];
        $modal_delete = [];
        ?>

        <table class="table table-bordered table-striped">
            <thead class="table-dark">
                <tr>
                    <th style="width:50px">Orden</th>
                    <th>Columna</th>
                    <th>Tipo</th>
                    <th>Nulo</th>
                    <th>Default</th>
                    <th>Extra</th>
                    <th>Comentario</th>
                    <th style="width:220px">Acciones</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($columns as $i => $col): 
                    $idEdit = "modal_edit_" . $i;
                    $idDelete = "modal_delete_" . $i;

                    // parse type and length
                    preg_match('/^([^\s(]+)(?:\((.*?)\))?(.*)$/', $col["Type"], $m);
                    $typeBase = $m[1] ?? $col["Type"];
                    $typeLen = $m[2] ?? "";
                    $typeRest = trim($m[3] ?? "");
                ?>
                <tr>
                    <td><?= $i+1 ?></td>
                    <td><?= htmlspecialchars($col["Field"]) ?></td>
                    <td><?= htmlspecialchars($col["Type"]) ?></td>
                    <td><?= htmlspecialchars($col["Null"]) ?></td>
                    <td><?= htmlspecialchars((string)$col["Default"]) ?></td>
                    <td><?= htmlspecialchars($col["Extra"]) ?> <?= $typeRest ? ' '.htmlspecialchars($typeRest) : '' ?></td>
                    <td><?= htmlspecialchars($col["Comment"]) ?></td>

                    <td class="text-center">

                        <!-- Mover arriba -->
                        <form method="POST" class="d-inline">
                            <input type="hidden" name="move_up" value="1">
                            <input type="hidden" name="col" value="<?= htmlspecialchars($col["Field"]) ?>">
                            <input type="hidden" name="db" value="<?= htmlspecialchars($selectDB) ?>">
                            <input type="hidden" name="table" value="<?= htmlspecialchars($selectTable) ?>">
                            <button class="btn btn-outline-secondary btn-sm" title="Subir">▲</button>
                        </form>

                        <!-- Mover abajo -->
                        <form method="POST" class="d-inline">
                            <input type="hidden" name="move_down" value="1">
                            <input type="hidden" name="col" value="<?= htmlspecialchars($col["Field"]) ?>">
                            <input type="hidden" name="db" value="<?= htmlspecialchars($selectDB) ?>">
                            <input type="hidden" name="table" value="<?= htmlspecialchars($selectTable) ?>">
                            <button class="btn btn-outline-secondary btn-sm" title="Bajar">▼</button>
                        </form>

                        <!-- Editar -->
                        <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#<?= $idEdit ?>">✏</button>

                        <!-- Eliminar -->
                        <button class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#<?= $idDelete ?>">🗑</button>

                    </td>
                </tr>

                <?php
                    $modal_edit[] = ['id'=>$idEdit,'col'=>$col,'typeBase'=>$typeBase,'typeLen'=>$typeLen,'typeRest'=>$typeRest,'index'=>$i];
                    $modal_delete[] = ['id'=>$idDelete,'col'=>$col,'index'=>$i];
                endforeach; ?>
            </tbody>
        </table>

        <!-- RENDER MODALES DE ELIMINAR -->
        <?php foreach ($modal_delete as $m): 
            $col = $m['col'];
            $id = $m['id'];
        ?>
        <div class="modal fade" id="<?= htmlspecialchars($id) ?>" tabindex="-1">
            <div class="modal-dialog">
                <form method="POST" class="modal-content">
                    <div class="modal-header bg-danger text-white">
                        <h5 class="modal-title">Eliminar columna</h5>
                        <button class="btn-close" data-bs-dismiss="modal"></button>
                    </div>

                    <div class="modal-body">
                        ¿Eliminar <b><?= htmlspecialchars($col["Field"]) ?></b>?
                        <input type="hidden" name="delete_column" value="1">
                        <input type="hidden" name="db" value="<?= htmlspecialchars($selectDB) ?>">
                        <input type="hidden" name="table" value="<?= htmlspecialchars($selectTable) ?>">
                        <input type="hidden" name="col_name_delete" value="<?= htmlspecialchars($col["Field"]) ?>">
                    </div>

                    <div class="modal-footer">
                        <button class="btn btn-danger">Eliminar</button>
                        <button class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    </div>
                </form>
            </div>
        </div>
        <?php endforeach; ?>

        <!-- RENDER MODALES DE EDIT -->
        <?php foreach ($modal_edit as $m): 
            $col = $m['col'];
            $id = $m['id'];
            $typeBase = $m['typeBase'];
            $typeLen = $m['typeLen'];
            $typeRest = $m['typeRest'];
        ?>
        <div class="modal fade" id="<?= htmlspecialchars($id) ?>" tabindex="-1">
            <div class="modal-dialog">
                <form method="POST" class="modal-content">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title">Editar columna: <?= htmlspecialchars($col['Field']) ?></h5>
                        <button class="btn-close" data-bs-dismiss="modal"></button>
                    </div>

                    <div class="modal-body">
                        <input type="hidden" name="edit_column" value="1">
                        <input type="hidden" name="db" value="<?= htmlspecialchars($selectDB) ?>">
                        <input type="hidden" name="table" value="<?= htmlspecialchars($selectTable) ?>">
                        <input type="hidden" name="old_name" value="<?= htmlspecialchars($col['Field']) ?>">

                        <div class="mb-2">
                            <label class="form-label">Nombre</label>
                            <input class="form-control" name="name" value="<?= htmlspecialchars($col['Field']) ?>">
                        </div>

                        <div class="row">
                            <div class="col-6 mb-2">
                                <label class="form-label">Tipo</label>
                                <input class="form-control" name="type" value="<?= htmlspecialchars($typeBase) ?>">
                            </div>
                            <div class="col-6 mb-2">
                                <label class="form-label">Longitud / Precisión</label>
                                <input class="form-control" name="length" value="<?= htmlspecialchars($typeLen) ?>">
                            </div>
                        </div>

                        <div class="mb-2">
                            <label class="form-label">Extras (unsigned, AUTO_INCREMENT...)</label>
                            <input class="form-control" name="extra" value="<?= htmlspecialchars(trim($typeRest.' '.$col['Extra'])) ?>">
                        </div>

                        <div class="row">
                            <div class="col-6 mb-2">
                                <label class="form-label">Null</label>
                                <select name="null" class="form-select">
                                    <option value="YES" <?= $col['Null']=='YES' ? 'selected' : '' ?>>YES</option>
                                    <option value="NO" <?= $col['Null']=='NO' ? 'selected' : '' ?>>NO</option>
                                </select>
                            </div>
                            <div class="col-6 mb-2">
                                <label class="form-label">Default</label>
                                <input class="form-control" name="default" value="<?= htmlspecialchars((string)$col['Default']) ?>">
                            </div>
                        </div>

                        <div class="mb-2">
                            <label class="form-label">Comentario</label>
                            <input class="form-control" name="comment" value="<?= htmlspecialchars($col['Comment']) ?>">
                        </div>
                    </div>

                    <div class="modal-footer">
                        <button class="btn btn-primary">Guardar cambios</button>
                        <button class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    </div>
                </form>
            </div>
        </div>
        <?php endforeach; ?>

    <?php endif; ?>

</div>

<!-- MODAL: AGREGAR COLUMNA -->
<div class="modal fade" id="addColumnModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title">Agregar columna</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <input type="hidden" name="add_column" value="1">
                <input type="hidden" name="db" value="<?= htmlspecialchars($selectDB) ?>">
                <input type="hidden" name="table" value="<?= htmlspecialchars($selectTable) ?>">

                <div class="mb-2">
                    <label class="form-label">Nombre</label>
                    <input name="name" class="form-control" required>
                </div>

                <div class="row">
                    <div class="col-6 mb-2">
                        <label class="form-label">Tipo</label>
                        <select name="type" class="form-select">
                            <?php foreach (['int','varchar','text','json','timestamp','date','float','double','tinyint','bigint'] as $tt): ?>
                                <option value="<?= $tt ?>"><?= $tt ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-6 mb-2">
                        <label class="form-label">Longitud / Precisión</label>
                        <input name="length" class="form-control" placeholder="ej: 255">
                    </div>
                </div>

                <div class="mb-2">
                    <label class="form-label">Extras</label>
                    <input name="extra" class="form-control" placeholder="AUTO_INCREMENT unsigned">
                </div>

                <div class="row">
                    <div class="col-6 mb-2">
                        <label class="form-label">Null</label>
                        <select name="null" class="form-select">
                            <option value="YES">YES</option>
                            <option value="NO">NO</option>
                        </select>
                    </div>

                    <div class="col-6 mb-2">
                        <label class="form-label">Default</label>
                        <input name="default" class="form-control" placeholder="NULL or CURRENT_TIMESTAMP or value">
                    </div>
                </div>

                <div class="mb-2">
                    <label class="form-label">Comentario</label>
                    <input name="comment" class="form-control">
                </div>

            </div>

            <div class="modal-footer">
                <button class="btn btn-success">Agregar</button>
                <button class="btn btn-secondary" type="button" data-bs-dismiss="modal">Cancelar</button>
            </div>
        </form>
    </div>
</div>

<!-- MODAL: RENOMBRAR TABLA -->
<div class="modal fade" id="renameTableModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title">Renombrar tabla</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <input type="hidden" name="rename_table" value="1">
                <input type="hidden" name="db" value="<?= htmlspecialchars($selectDB) ?>">
                <input type="hidden" name="table" value="<?= htmlspecialchars($selectTable) ?>">

                <div class="mb-2">
                    <label class="form-label">Nuevo nombre</label>
                    <input name="new_table_name" class="form-control" required>
                </div>
            </div>

            <div class="modal-footer">
                <button class="btn btn-warning">Renombrar</button>
                <button class="btn btn-secondary" type="button" data-bs-dismiss="modal">Cancelar</button>
            </div>
        </form>
    </div>
</div>

<!-- MODAL: ELIMINAR TABLA -->
<div class="modal fade" id="deleteTableModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">Eliminar tabla</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                ¿Seguro que deseas eliminar la tabla <b><?= htmlspecialchars($selectTable) ?></b>?
                <input type="hidden" name="delete_table" value="1">
                <input type="hidden" name="db" value="<?= htmlspecialchars($selectDB) ?>">
                <input type="hidden" name="table" value="<?= htmlspecialchars($selectTable) ?>">
            </div>

            <div class="modal-footer">
                <button class="btn btn-danger">Eliminar</button>
                <button class="btn btn-secondary" type="button" data-bs-dismiss="modal">Cancelar</button>
            </div>
        </form>
    </div>
</div>

<!-- MODAL: CREAR TABLA -->
<div class="modal fade" id="createTableModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Crear Nueva Tabla</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <?php $databases = getDatabases($conn); ?>
                <div class="mb-3">
                    <label class="form-label">Base de Datos</label>
                    <select name="db_name" class="form-select" required>
                        <option value="">Seleccione una base</option>
                        <?php foreach ($databases as $d): ?>
                            <option value="<?= htmlspecialchars($d) ?>"><?= htmlspecialchars($d) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="mb-3">
                    <label class="form-label">Nombre de la Tabla</label>
                    <input type="text" name="table_name" class="form-control" placeholder="ejemplo: usuarios" required>
                </div>

                <div class="alert alert-info p-2">
                    La tabla iniciará con:<br>
                    <b>id INT AUTO_INCREMENT PRIMARY KEY</b>
                </div>
            </div>

            <div class="modal-footer">
                <button type="submit" name="create_table" class="btn btn-primary">Crear</button>
                <button class="btn btn-secondary" type="button" data-bs-dismiss="modal">Cancelar</button>
            </div>
        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
