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

include '../includes/header2.php';

if ($seller_name != 'aa' && $seller_name != 'admin') {
    echo "<div class='alert alert-danger'>Acesso negado. Apenas administrador.</div>";
    include '../includes/footer2.php';
    exit();
}

echo "<div style='padding: 20px;'>";
echo "<h2>Corrigindo estrutura da tabela ibo</h2>";

$db = new SQLite3('../a/.eggziedb.db');
$db->busyTimeout(5000);

// Verificar e remover coluna inválida 'COLLUMN extra'
$table_info = $db->query("PRAGMA table_info(ibo)");
$invalid_columns = [];
$valid_columns = [];

while ($col = $table_info->fetchArray(SQLITE3_ASSOC)) {
    if ($col['name'] == 'COLLUMN') {
        $invalid_columns[] = $col['name'];
        echo "<p style='color:orange'>Coluna inválida encontrada: <strong>{$col['name']}</strong></p>";
    } else {
        $valid_columns[] = $col['name'];
    }
}

if (!empty($invalid_columns)) {
    echo "<p>Criando tabela temporária...</p>";
    
    // Criar tabela temporária com estrutura correta
    $db->exec("CREATE TABLE ibo_temp (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        mac_address VARCHAR(100),
        username VARCHAR(100),
        password VARCHAR(100),
        expire_date VARCHAR(100),
        url VARCHAR(100),
        title VARCHAR(100),
        created_at VARCHAR(100),
        seller TEXT,
        extra TEXT,
        is_test INTEGER DEFAULT 0
    )");
    
    // Copiar dados da tabela antiga para a nova
    $db->exec("INSERT INTO ibo_temp (id, mac_address, username, password, expire_date, url, title, created_at, seller, extra, is_test)
               SELECT id, mac_address, username, password, expire_date, url, title, created_at, seller, extra, is_test FROM ibo");
    
    // Remover tabela antiga
    $db->exec("DROP TABLE ibo");
    
    // Renomear tabela temporária
    $db->exec("ALTER TABLE ibo_temp RENAME TO ibo");
    
    echo "<p style='color:green'>✓ Tabela corrigida com sucesso!</p>";
} else {
    echo "<p style='color:green'>✓ Nenhuma coluna inválida encontrada.</p>";
}

// Garantir que a coluna extra existe corretamente
$has_extra = false;
$table_info = $db->query("PRAGMA table_info(ibo)");
while ($col = $table_info->fetchArray(SQLITE3_ASSOC)) {
    if ($col['name'] == 'extra') {
        $has_extra = true;
        break;
    }
}

if (!$has_extra) {
    $db->exec("ALTER TABLE ibo ADD COLUMN extra TEXT");
    echo "<p style='color:green'>✓ Coluna extra adicionada.</p>";
}

// Verificar estrutura final
echo "<h3>Estrutura final da tabela ibo:</h3>";
$result = $db->query("PRAGMA table_info(ibo)");
echo "<table border='1' cellpadding='5' style='border-collapse: collapse;'>";
echo "<tr style='background:#f0f0f0'><th>Nome</th><th>Tipo</th><th>Default</th></tr>";
while ($col = $result->fetchArray(SQLITE3_ASSOC)) {
    echo "<tr>";
    echo "<td>" . htmlspecialchars($col['name']) . "</td>";
    echo "<td>" . htmlspecialchars($col['type']) . "</td>";
    echo "<td>" . htmlspecialchars($col['dflt_value']) . "</td>";
    echo "</tr>";
}
echo "</table>";

$db->close();

echo "<br><a href='users_create.php' class='btn btn-primary'>Voltar para criação de usuários</a>";
echo "</div>";

include '../includes/footer2.php';
?>