<?php
// Arquivo: profile.php (raiz - painel ADM)

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Criar banco de dados automaticamente se não existir
$db_path = './a/.eggziedb.db';
if (!file_exists($db_path)) {
    $db = new SQLite3($db_path);
    $db->exec('CREATE TABLE IF NOT EXISTS revenda (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        nome TEXT,
        usuario TEXT UNIQUE,
        senha TEXT,
        macs INTEGER DEFAULT 0,
        id_ref TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )');
    $db->exec('CREATE TABLE IF NOT EXISTS sub_revenda (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        nome TEXT,
        usuario TEXT UNIQUE,
        senha TEXT,
        macs INTEGER DEFAULT 0,
        id_ref TEXT,
        revenda_id INTEGER,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )');
    $db->exec('CREATE TABLE IF NOT EXISTS ibo (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT,
        mac_address TEXT,
        url TEXT,
        seller TEXT,
        title TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )');
    $db->close();
}

$db = new SQLite3('./a/.eggziedb.db');

include './includes/header.php';

// IMPORTANTE: Buscar o admin logado pela sessão
// O admin está na tabela USERS do banco eggziepanels.db, não na tabela revenda
$id_admin = $_SESSION['id'];
$admin_name = $_SESSION['admin_name'];

// Buscar dados do admin no banco de configuração do painel
$panel_db = new SQLite3('./a/.eggziepanels.db');
$result_admin = $panel_db->query("SELECT * FROM USERS WHERE id = '$id_admin'");
$admin_data = $result_admin->fetchArray(SQLITE3_ASSOC);

if ($admin_data) {
    $name = $admin_data['NAME'];
    $username = $admin_data['USERNAME'] ?? $admin_name;
    $user = $username;
    $password = $admin_data['PASSWORD'] ?? '';
} else {
    // Fallback: usar dados da sessão
    $name = $admin_name;
    $username = $admin_name;
    $user = $username;
    $password = '';
}

if (isset($_POST['submit'])) {
    
    $username_new = trim($_POST['username']);
    $password_new = $_POST['password'];
    $name_new = trim($_POST['name']);
    
    // Verificar se o novo usuário já existe (exceto o próprio)
    if ($username_new != $username) {
        // Verificar em revenda
        $result = $db->query("SELECT COUNT(*) as count FROM revenda WHERE usuario = '$username_new'");
        $row = $result->fetchArray(SQLITE3_ASSOC);
        $count = $row['count'];
        
        // Verificar em sub_revenda
        $result2 = $db->query("SELECT COUNT(*) as count FROM sub_revenda WHERE usuario = '$username_new'");
        $row2 = $result2->fetchArray(SQLITE3_ASSOC);
        $count += $row2['count'];
        
        if ($count > 0 || strtoupper($username_new) == "ADM") {
            echo "<script>alert('Já existe um usuário com esse nome, por favor escolha outro!');window.location.href='profile.php';</script>";
            exit();
        }
    }
    
    // Atualizar dados do admin no banco do painel
    $panel_db->exec("UPDATE USERS SET NAME = '$name_new', USERNAME = '$username_new', PASSWORD = '$password_new' WHERE id = '$id_admin'");
    
    // Atualizar sessão
    $_SESSION['admin_name'] = $username_new;
    
    // Atualizar referências nos usuários IBO (se houver)
    if (!empty($username) && $username != $username_new) {
        $db->exec("UPDATE ibo SET seller = '$username_new' WHERE seller = '$username'");
        
        // Renomear arquivos associados
        if (file_exists("../a/rtx/Setting_$user.json")) {
            rename("../a/rtx/Setting_$user.json", "../a/rtx/Setting_$username_new.json");
        }
        if (file_exists("../a/rtx/logo_filenames_$user.json")) {
            rename("../a/rtx/logo_filenames_$user.json", "../a/rtx/logo_filenames_$username_new.json");
        }
        if (file_exists("../a/rtx/image_filenames_$user.json")) {
            rename("../a/rtx/image_filenames_$user.json", "../a/rtx/image_filenames_$username_new.json");
        }
        if (file_exists("../a/note_$user.json")) {
            rename("../a/note_$user.json", "../a/note_$username_new.json");
        }
        if (file_exists("../api/theme_$user.json")) {
            rename("../api/theme_$user.json", "../api/theme_$username_new.json");
        }
        
        // Atualizar outros bancos de dados
        if (file_exists("../api/.adb.db")) {
            $db2 = new SQLite3("../api/.adb.db");
            $db2->exec("UPDATE ads SET owner = '$username_new' WHERE owner = '$user'");
            $db2->close();
        }
        
        if (file_exists("../api/intro.db")) {
            $db3 = new SQLite3("../api/intro.db");
            $db3->exec("UPDATE intro SET owner = '$username_new' WHERE owner = '$user'");
            $db3->close();
        }
    }
    
    $panel_db->close();
    $db->close();
    
    echo "<script>alert('Perfil atualizado com sucesso!');window.location.href='profile.php';</script>";
    exit();
}

$panel_db->close();
$db->close();
?>

<div class="container-fluid">
    <h1 class="h3 mb-1 text-gray-800">Atualizar Perfil</h1>
    
    <div class="row">
        <div class="col-lg-12">
            <div class="card border-left-primary shadow h-100 card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary"><i class="fa fa-user"></i> Perfil do Administrador</h6>
                </div>
                <div class="card-body">
                    <form method="post">
                        <div class="form-group">
                            <label class="control-label" for="name">
                                <strong>Nome do Administrador</strong>
                            </label>
                            <div class="input-group">
                                <input type="text" class="form-control" name="name" value="<?php echo htmlspecialchars($name);?>" placeholder="Enter Name" required>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="control-label" for="username">
                                <strong>USUÁRIO</strong>
                            </label>
                            <div class="input-group">
                                <input type="text" class="form-control" name="username" value="<?php echo htmlspecialchars($username);?>" placeholder="Enter Username" required>
                            </div>
                            <small class="text-muted">Alterar o usuário irá atualizar automaticamente todos os clientes vinculados.</small>
                        </div>
                        <div class="form-group">
                            <label class="control-label" for="password">
                                <strong>SENHA</strong>
                            </label>
                            <div class="input-group">
                                <input type="password" class="form-control" name="password" value="<?php echo htmlspecialchars($password);?>" id="myInput" placeholder="Enter Password" required>
                            </div>
                        </div>
                        <div class="form-group">
                            <input type="checkbox" onclick="myFunction()">
                            <label class="control-label" for="password">
                                <strong>Mostrar Senha</strong>
                            </label>
                        </div>
                        <div class="form-group">
                            <button class="btn btn-success btn-icon-split" name="submit" type="submit">
                                <span class="icon text-white-50"><i class="fas fa-check"></i></span>
                                <span class="text">Atualizar Perfil</span>
                            </button>
                            <a href="users.php" class="btn btn-secondary btn-icon-split">
                                <span class="icon text-white-50"><i class="fas fa-arrow-left"></i></span>
                                <span class="text">Voltar</span>
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function myFunction() {
    var x = document.getElementById('myInput');
    if (x.type === 'password') {
        x.type = 'text';
    } else {
        x.type = 'password';
    }
}
</script>

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