<?php
include "includes/header.php";

// Caminho do banco de dados (ajustado para a raiz conforme solicitado anteriormente)
$db_path = './a/.eggziepanels.db';
$message = "";

try {
    $db = new SQLite3($db_path);

    // --- BLOCO DE AUTO-CORREÇÃO DE TABELAS ---
    // Verifica se a coluna 'USER' existe, se não, tenta encontrar 'username' e renomear ou criar
    $tableInfo = $db->query("PRAGMA table_info(USERS)");
    $cols = [];
    while ($row = $tableInfo->fetchArray(SQLITE3_ASSOC)) {
        $cols[] = strtoupper($row['name']);
    }

    // Se não houver coluna PASS mas houver PASSWORD, ou vice-versa, nós tratamos
    // Este bloco garante que o banco tenha: NAME, USER, PASS, LOGO
    if (!in_array('USER', $cols) && in_array('USERNAME', $cols)) {
        $db->exec("ALTER TABLE USERS RENAME COLUMN USERNAME TO USER");
    }
    if (!in_array('PASS', $cols) && in_array('PASSWORD', $cols)) {
        $db->exec("ALTER TABLE USERS RENAME COLUMN PASSWORD TO PASS");
    }
    // ------------------------------------------

    // 1. Carrega os dados atuais
    $res = $db->query("SELECT * FROM USERS WHERE id='1'")->fetchArray(SQLITE3_ASSOC);
    
    // 2. Lógica de Salvamento
    if (isset($_POST['save_profile'])) {
        $name = $_POST['name'];
        $user = $_POST['username'];
        $pass = $_POST['password'];

        // Usamos os nomes de colunas padrão do seu sistema (USER e PASS)
        $stmt = $db->prepare("UPDATE USERS SET NAME = :name, USER = :user, PASS = :pass WHERE id = '1'");
        $stmt->bindValue(':name', $name, SQLITE3_TEXT);
        $stmt->bindValue(':user', $user, SQLITE3_TEXT);
        $stmt->bindValue(':pass', $pass, SQLITE3_TEXT);

        if ($stmt->execute()) {
            $message = "success";
            $res['NAME'] = $name;
            $res['USER'] = $user;
            $res['PASS'] = $pass;
        } else {
            $message = "error";
        }
    }
    $db->close();
} catch (Exception $e) {
    echo "<div class='alert alert-danger'>Erro crítico: " . $e->getMessage() . "</div>";
}
?>

<style>
    #content-wrapper, #content, .container-fluid, main { background-color: #06070a !important; }
    .profile-card { background: #0f111a !important; border: 1px solid rgba(255,255,255,0.05) !important; border-radius: 1.5rem !important; }
    .input-group-thai { background: rgba(255,255,255,0.02) !important; border: 1px solid rgba(255, 255, 255, 0.08) !important; border-radius: 12px !important; color: #fff !important; padding: 12px 15px !important; width: 100%; }
    .label-thai { font-size: 10px; font-weight: 800; text-transform: uppercase; color: #8b5cf6; margin-bottom: 8px; display: block; }
</style>

<main class="py-10 px-4">
    <div class="max-w-2xl mx-auto">
        <div class="mb-8 flex items-center justify-between">
            <h1 class="text-2xl font-black text-white uppercase italic">Configurações de Acesso</h1>
            <a href="logo.php" class="text-[10px] bg-violet-600/20 text-violet-400 px-4 py-2 rounded-lg font-bold border border-violet-500/30">
                GERENCIAR LOGO <i class="fas fa-external-link-alt ml-1"></i>
            </a>
        </div>

        <?php if($message == "success"): ?>
            <div class="mb-6 p-4 bg-emerald-500/10 border border-emerald-500/50 text-emerald-400 rounded-2xl flex items-center gap-3">
                <i class="fas fa-check-circle"></i>
                <span class="text-xs font-bold uppercase">Senha e Usuário atualizados!</span>
            </div>
        <?php endif; ?>

        <div class="profile-card p-8">
            <form method="POST" class="space-y-6">
                <div class="text-center p-4 bg-white/5 rounded-xl border border-white/5 mb-6">
                    <img src="<?php echo $res['LOGO']; ?>" class="mx-auto" style="max-height: 70px;">
                    <p class="text-[9px] text-gray-500 mt-2 uppercase">Identidade Atual: <?php echo $res['NAME']; ?></p>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="label-thai">Nome do Painel</label>
                        <input type="text" name="name" value="<?php echo $res['NAME']; ?>" class="input-group-thai" required>
                    </div>
                    <div>
                        <label class="label-thai">Usuário de Login</label>
                        <input type="text" name="username" value="<?php echo $res['USER']; ?>" class="input-group-thai" required>
                    </div>
                </div>

                <div>
                    <label class="label-thai">Senha de Administrador</label>
                    <input type="text" name="password" value="<?php echo $res['PASS']; ?>" class="input-group-thai" required>
                    <small class="text-[9px] text-gray-600 mt-1 block uppercase italic">Nota: A senha é salva em texto simples conforme padrão do painel.</small>
                </div>

                <button type="submit" name="save_profile" class="w-full py-4 bg-violet-600 hover:bg-violet-500 text-white rounded-xl text-xs font-black uppercase transition-all">
                    <i class="fas fa-sync-alt mr-2"></i> Aplicar e Corrigir Tabelas
                </button>
            </form>
        </div>
    </div>
</main>

<?php include "includes/footer.php"; ?>