
<?php
/*
 * @ https://hospedagem.matrixch.store 
 * @ PHP 7.4
 * @ Decoder version: 1.0.2
 * @ Release: 17/06/2024
*/

include "includes/header.php";

// Obter todos os usuários
$users = $db->select("playlist", "*", "", "") ?: [];

// Obter todas as entradas DNS
$dns_entries = $db->select("dns", "*", "", "") ?: [];

// Obter todos os anúncios (usando SQLite3 diretamente)
$ads = [];
$adsResult = $adb->query("SELECT * FROM ads");
if ($adsResult) {
    while ($row = $adsResult->fetchArray(SQLITE3_ASSOC)) {
        $ads[] = $row;
    }
}

// Obter tema atual
$themes = $db->select("themes", "*", "", "") ?: [];
$current_theme = !empty($themes) ? $themes[0]['theme_id'] : 1;

// Contar totais
$total_users = count($users);
$total_dns = count($dns_entries);
$total_ads = count($ads);

// Preparar dados para gráficos
$user_dns_distribution = [];
foreach ($dns_entries as $dns) {
    $count = $db->select("playlist", "COUNT(*) as count", "dns_id = :dns_id", "", [":dns_id" => $dns['id']]);
    $user_dns_distribution[] = [
        'dns' => $dns['title'],
        'users' => $count[0]['count'] ?? 0
    ];
}

// Obter usuários recentes (últimos 10)
$recent_users = array_slice(array_reverse($users), 0, 10);

// Lidar com ações de usuários
if (isset($_POST["submit"])) {
    unset($_POST["submit"]);
    $db->insert("playlist", $_POST);
    echo "<script>window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "?status=5'</script>";
}

$resU = @$db->select("playlist", "*", "id = :id", "", [":id" => $_GET["update"]]);

if (isset($_POST["submitU"])) {
    unset($_POST["submitU"]);
    $updateData = $_POST;

    // Verificar se a senha foi alterada; se não, manter a senha antiga
    if (empty($updateData['password'])) {
        unset($updateData['password']); // Remover a senha para não sobrescrever
    }

    $db->update("playlist", $updateData, "id = :id", [":id" => $_POST["id"]]);
    echo "<script>window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "?status=5'</script>";
}

if (isset($_GET["delete"])) {
    $db->delete("playlist", "id = :id", [":id" => $_GET["delete"]]);
    // Remover redirecionamento para não mudar a página
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IBO VS4 By P2PLAY</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
    :root {
        --primary: #1a237e;
        --primary-dark: #0d1541;
        --primary-light: rgba(67, 97, 238, 0.1);
        --success: #28a745;
        --warning: #fd7e14;
        --danger: #dc3545;
        --dark: #343a40;
        --light: #f8f9fa;
        --gray: #6c757d;
        --border-radius: 10px;
        --box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
        --transition: all 0.3s ease;
    }

    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        background-color: #f5f7fb;
        overflow-x: hidden;
    }

    .container-fluid {
        padding: 25px;
    }

    /* Cards de Estatísticas */
    .stats-card {
        border: none;
        border-radius: var(--border-radius);
        box-shadow: var(--box-shadow);
        transition: var(--transition);
        background: white;
        margin-bottom: 25px;
        height: 100%;
    }

    .stats-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
    }

    .stats-card .card-body {
        padding: 25px;
        text-align: center;
    }

    .card-icon {
        font-size: 2.5rem;
        margin-bottom: 20px;
        color: var(--primary);
    }

    .stats-card.success .card-icon { color: var(--success); }
    .stats-card.warning .card-icon { color: var(--warning); }
    .stats-card.danger .card-icon { color: var(--danger); }

    .stat-number {
        font-size: 2.2rem;
        font-weight: 700;
        margin: 15px 0;
        color: var(--dark);
    }

    .card-title {
        font-size: 1.1rem;
        color: var(--gray);
        margin-bottom: 0;
        font-weight: 500;
    }

    /* Cards Principais */
    .main-card {
        border: none;
        border-radius: var(--border-radius);
        box-shadow: var(--box-shadow);
        margin-bottom: 25px;
        background: white;
        height: 100%;
        display: flex;
        flex-direction: column;
    }

    .main-card .card-header {
        background: linear-gradient(135deg, #4B79A1, #283E51); /* Gradiente mais profissional */
        color: white;
        border-radius: var(--border-radius) var(--border-radius) 0 0 !important;
        padding: 18px 25px;
        font-weight: 600;
        font-size: 1.1rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .main-card .card-header .title {
        display: flex;
        align-items: center;
    }

    .main-card .card-header .title i {
        margin-right: 12px;
        font-size: 1.2rem;
    }

    .main-card .card-header .subtitle {
        font-size: 0.85rem;
        font-weight: 400;
        opacity: 0.9;
    }

    .main-card .card-body {
        padding: 25px;
        flex: 1;
    }

    /* Gráficos */
    .chart-container {
        position: relative;
        height: 300px;
        width: 100%;
        border-radius: var(--border-radius);
        box-shadow: var(--box-shadow);
        background: white;
        padding: 15px;
    }

    /* Tabelas */
    .table-responsive {
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
    }

    .table {
        width: 100%;
        border-collapse: collapse;
        font-size: 0.95rem;
    }

    .table th {
        background-color: var(--light);
        padding: 15px;
        text-align: left;
        border-bottom: 2px solid #dee2e6;
        font-weight: 600;
        color: var(--dark);
    }

    .table td {
        padding: 15px;
        border-bottom: 1px solid #e9ecef;
        vertical-align: middle;
    }

    .table tr:last-child td {
        border-bottom: none;
    }

    .table-hover tbody tr:hover {
        background-color: rgba(0, 0, 0, 0.02);
    }

    /* Seção de Download */
    .download-section {
        display: flex;
        flex-direction: column;
        height: 100%;
    }

    .download-option {
        background: white;
        border-radius: var(--border-radius);
        padding: 25px;
        margin-bottom: 20px;
        box-shadow: var(--box-shadow);
        transition: var(--transition);
        border: 1px solid rgba(0, 0, 0, 0.05);
        height: 100%;
    }

    .download-option:hover {
        transform: translateY(-5px);
        box-shadow: 0 12px 25px rgba(0, 0, 0, 0.1);
    }

    .download-icon {
        font-size: 2.8rem;
        margin-bottom: 20px;
        display: block;
        text-align: center;
    }

    .download-title {
        text-align: center;
        margin-bottom: 20px;
        font-weight: 600;
        color: var(--dark);
        font-size: 1.2rem;
    }

    .download-features {
        list-style: none;
        padding: 0;
        margin-bottom: 25px;
    }

    .download-features li {
        padding: 8px 0;
        display: flex;
        align-items: center;
        font-size: 0.95rem;
    }

    .download-features i {
        margin-right: 10px;
        color: var(--success);
        font-size: 1.1rem;
    }

    .download-btn {
        width: 100%;
        padding: 14px;
        font-weight: 600;
        border: none;
        border-radius: var(--border-radius);
        display: flex;
        align-items: center;
        justify-content: center;
        transition: var(--transition);
        font-size: 1rem;
    }

    .download-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    }

    .download-btn i {
        margin-right: 10px;
        font-size: 1.3rem;
    }

    .version-info {
        background-color: var(--primary-light);
        border-left: 4px solid var(--primary);
        padding: 18px;
        margin-bottom: 25px;
        border-radius: var(--border-radius);
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .badge-new {
        background-color: var(--success);
        color: white;
        padding: 5px 12px;
        border-radius: 50px;
        font-size: 0.8rem;
        font-weight: 600;
    }

    .more-info-btn {
        background: none;
        border: none;
        color: var(--primary);
        text-decoration: none;
        cursor: pointer;
        font-size: 0.95rem;
        margin-top: 15px;
        display: inline-flex;
        align-items: center;
        transition: var(--transition);
    }

    .more-info-btn:hover {
        color: #3a56d4;
        text-decoration: underline;
    }

    .more-info-btn i {
        margin-right: 8px;
    }

    /* Modal Styles */
    .modal-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.6);
        backdrop-filter: blur(8px);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1050;
        opacity: 0;
        visibility: hidden;
        transition: all 0.3s ease;
    }

    .modal-overlay.active {
        opacity: 1;
        visibility: visible;
    }

    .modal-content {
        background: white;
        border-radius: var(--border-radius);
        box-shadow: 0 15px 40px rgba(0, 0, 0, 0.2);
        width: 90%;
        max-width: 850px;
        max-height: 90vh;
        overflow-y: auto;
        transform: translateY(30px);
        transition: all 0.4s ease;
        position: relative;
    }

    .modal-overlay.active .modal-content {
        transform: translateY(0);
    }

    .modal-close {
        position: absolute;
        top: 20px;
        right: 20px;
        background: none;
        border: none;
        font-size: 1.8rem;
        cursor: pointer;
        color: var(--gray);
        z-index: 10;
        transition: var(--transition);
    }

    .modal-close:hover {
        color: var(--dark);
        transform: rotate(90deg);
    }

    .modal-body {
        padding: 40px;
    }

    .install-steps {
        background-color: var(--light);
        padding: 25px;
        border-radius: var(--border-radius);
        margin-bottom: 25px;
    }

    .step-title {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
    }

    .step-number {
        background-color: var(--primary);
        color: white;
        width: 28px;
        height: 28px;
        border-radius: 50%;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
        font-size: 0.9rem;
        font-weight: bold;
    }

    .alert-warning {
        background-color: rgba(253, 126, 20, 0.1);
        border-left: 4px solid var(--warning);
        padding: 20px;
        border-radius: var(--border-radius);
        margin: 25px 0;
    }

    .alert-warning i {
        color: var(--warning);
    }

    .faq-item {
        margin-bottom: 20px;
        border-bottom: 1px solid #eee;
        padding-bottom: 20px;
    }

    .faq-item:last-child {
        border-bottom: none;
    }

    /* Responsividade */
    @media (max-width: 1200px) {
        .modal-content {
            max-width: 700px;
        }
    }

    @media (max-width: 992px) {
        .stats-card .card-body {
            padding: 20px;
        }
        
        .main-card .card-body {
            padding: 20px;
        }
        
        .download-option {
            padding: 20px;
        }
    }

    @media (max-width: 768px) {
        .container-fluid {
            padding: 15px;
        }
        
        .stat-number {
            font-size: 1.8rem;
        }
        
        .card-icon {
            font-size: 2rem;
        }
        
        .main-card .card-header {
            padding: 15px;
            font-size: 1rem;
            flex-direction: column;
            align-items: flex-start;
        }
        
        .main-card .card-header .subtitle {
            margin-top: 5px;
            align-self: flex-start;
        }
        
        .modal-body {
            padding: 30px 20px;
        }
        
        .download-title {
            font-size: 1.1rem;
        }
        
        .download-btn {
            padding: 12px;
            font-size: 0.95rem;
        }
    }

    @media (max-width: 576px) {
        .modal-content {
            width: 95%;
        }
        
        .table th, .table td {
            padding: 12px 8px;
            font-size: 0.85rem;
        }
        
        .version-info {
            flex-direction: column;
            text-align: center;
            padding: 15px;
        }
        
        .badge-new {
            margin-top: 10px;
        }
    }
    </style>
</head>
<body>
    <div class="container-fluid py-3">
        <!-- Cartões ajustáveis, com animação, responsivos e clicáveis -->
        <div class="d-flex justify-content-between w-100 flex-wrap">
            <a href="playlists.php" class="card stats-card flex-grow-1 m-1" style="min-width: 180px;">
                <div class="card-body text-center">
                    <i class="fas fa-users card-icon"></i>
                    <div class="stat-number text-primary"><?= $total_users ?></div>
                    <h5 class="card-title">Total de Usuários</h5>
                </div>
            </a>

            <a href="dns.php" class="card stats-card success flex-grow-1 m-1" style="min-width: 180px;">
                <div class="card-body text-center">
                    <i class="fas fa-network-wired card-icon"></i>
                    <div class="stat-number text-success"><?= $total_dns ?></div>
                    <h5 class="card-title">Servidores DNS</h5>
                </div>
            </a>

            <a href="ads.php" class="card stats-card warning flex-grow-1 m-1" style="min-width: 180px;">
                <div class="card-body text-center">
                    <i class="fas fa-ad card-icon"></i>
                    <div class="stat-number text-warning"><?= $total_ads ?></div>
                    <h5 class="card-title">Anúncios Ativos</h5>
                </div>
            </a>

            <?php
            // Função para mapear tema para número exibido
            function numeroPorTema($tema) {
                switch ($tema) {
                    case 4:
                        return 2;
                    case 2:
                        return 3;
                    case 5:
                        return 4;
                    default:
                        return $tema;
                }
            }

            // Aplica a função
            $numero_mostrado = numeroPorTema($current_theme);
            ?>

            <a href="themes.php" class="card stats-card danger flex-grow-1 m-1" style="min-width: 180px;">
                <div class="card-body text-center">
                    <i class="fas fa-palette card-icon"></i>
                    <div class="stat-number text-danger"><?= $numero_mostrado ?></div>
                    <h5 class="card-title">Tema Atual</h5>
                </div>
            </a>
        </div>

        <!-- Linha de Gráficos e Downloads -->
        <div class="row">
            <!-- Gráfico de Distribuição -->
            <div class="col-xl-6 col-lg-12 mb-4">
                <div class="main-card">
                    <div class="card-header">
                        <div class="title">
                            <i class="fas fa-chart-bar"></i>
                            <span>Distribuição de Usuários por DNS</span>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="dnsDistributionChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Seção de Download -->
            <div class="col-xl-6 col-lg-12 mb-4">
                <div class="main-card">
                    <div class="card-header">
                        <div class="title">
                            <i class="fas fa-mobile-alt"></i>
                            <span>Download do Aplicativo</span>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="version-info">
                            <div>
                                <h6 class="mb-1"><i class="fas fa-info-circle text-primary me-2"></i> Versão Atual</h6>
                                <p class="mb-0 text-muted small">v2.3.4 (Atualizado em <?= date('d/m/Y') ?>)</p>
                            </div>
                            <span class="badge-new">NOVO</span>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-4">
                                <div class="download-option">
                                    <i class="fas fa-file-download download-icon text-primary"></i>
                                    <h5 class="download-title">Download Direto</h5>
                                    <ul class="download-features">
                                        <li><i class="fas fa-check-circle"></i> Versão mais recente</li>
                                        <li><i class="fas fa-check-circle"></i> Instalação offline</li>
                                        <li><i class="fas fa-check-circle"></i> Sem necessidade de loja</li>
                                    </ul>
                                    <button class="download-btn btn-primary">
                                        <i class="fas fa-download"></i> Baixar APK (45 MB)
                                    </button>
                                </div>
                            </div>
                            
                            <div class="col-md-6 mb-4">
                                <div class="download-option">
                                    <i class="fab fa-google-play download-icon text-success"></i>
                                    <h5 class="download-title">Google Play Store</h5>
                                    <ul class="download-features">
                                        <li><i class="fas fa-check-circle"></i> Atualizações automáticas</li>
                                        <li><i class="fas fa-check-circle"></i> Verificação de segurança</li>
                                        <li><i class="fas fa-check-circle"></i> Fácil instalação</li>
                                    </ul>
                                    <button class="download-btn btn-success">
                                        <i class="fab fa-google-play"></i> Instalar via Play Store
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <button class="more-info-btn" id="showMoreInfo">
                            <i class="fas fa-info-circle"></i> Mais informações sobre instalação
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Tabela de Usuários Recentes -->
        <div class="row">
            <div class="col-12">
                <div class="main-card">
                    <div class="card-header">
                        <div class="title">
                            <i class="fas fa-users"></i>
                            <span>Usuários Recentes</span>
                        </div>
                        <div class="subtitle">Últimos 10 usuários registrados</div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Nome de Usuário</th>
                                        <th>Endereço MAC</th>
                                        <th>Servidor DNS</th>
                                        <th>PIN Parental</th>
                                        <th class="text-center">Ações</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($recent_users as $user): 
                                        $dns_info = $db->select("dns", "title", "id = :id", "", [":id" => $user['dns_id']]);
                                        $dns_title = !empty($dns_info) ? $dns_info[0]['title'] : 'N/A';
                                    ?>
                                    <tr>
                                        <td><?= $user['id'] ?></td>
                                        <td><?= htmlspecialchars($user['username']) ?></td>
                                        <td><code><?= htmlspecialchars($user['mac_address']) ?></code></td>
                                        <td><?= htmlspecialchars($dns_title) ?></td>
                                        <td><?= htmlspecialchars($user['pin']) ?></td>
                                        <td class="text-center">
                                            <button class="btn btn-sm btn-outline-primary edit-user" data-id="<?= $user['id'] ?>" data-username="<?= htmlspecialchars($user['username']) ?>" data-mac="<?= htmlspecialchars($user['mac_address']) ?>" data-dns="<?= $user['dns_id'] ?>" data-pin="<?= htmlspecialchars($user['pin']) ?>" data-password="<?= htmlspecialchars($user['password']) ?>">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <a href="#" class="btn btn-sm btn-outline-danger" onclick="event.preventDefault(); deleteUser(<?= $user['id'] ?>);">
                                                <i class="fas fa-trash-alt"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal para edição de usuários -->
    <div class="modal-overlay" id="editUserModal">
        <div class="modal-content">
            <button class="modal-close" id="closeEditModal">&times;</button>
            <div class="modal-body">
                <h3 class="mb-4"><i class="fas fa-user-edit text-primary me-2"></i> Editar Usuário</h3>
                <form id="editUserForm" method="post">
                    <input type="hidden" name="id" id="editUserId" value="">
                    <div class="mb-3">
                        <label class="form-label" for="editUsername">Nome de Usuário</label>
                        <input type="text" class="form-control" id="editUsername" name="username" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label" for="editMacAddress">Endereço MAC</label>
                        <input type="text" class="form-control" id="editMacAddress" name="mac_address" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label" for="editDnsId">Servidor DNS</label>
                        <select class="form-control" id="editDnsId" name="dns_id" required>
                            <?php foreach ($dns_entries as $dns): ?>
                                <option value="<?= $dns["id"] ?>"><?= htmlspecialchars($dns["title"]) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label" for="editPassword">Senha</label>
                        <input type="password" class="form-control" id="editPassword" name="password">
                    </div>
                    <div class="mb-3">
                        <label class="form-label" for="editPin">PIN Parental</label>
                        <input type="text" class="form-control" id="editPin" name="pin" required>
                    </div>
                    <div class="text-center mt-4">
                        <button type="submit" name="submitU" class="btn btn-primary px-4">
                            <i class="fas fa-save me-2"></i>Salvar
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Seção de Mais Informações sobre Instalação -->
    <div class="modal-overlay" id="infoModal">
        <div class="modal-content">
            <button class="modal-close" id="closeInfoModal">&times;</button>
            <div class="modal-body">
                <h3 class="mb-4"><i class="fas fa-info-circle text-primary me-2"></i> Informações de Instalação</h3>
                <p>Para instalar o aplicativo, siga os passos abaixo:</p>
                <ol>
                    <li>Baixe o arquivo APK usando o botão acima.</li>
                    <li>Vá em Configurações > Segurança no seu dispositivo.</li>
                    <li>Ative a opção "Fontes desconhecidas".</li>
                    <li>Localize o arquivo baixado e toque para instalar.</li>
                    <li>Siga as instruções na tela.</li>
                    <li>Aguarde o processo de instalação completar.</li>
                </ol>
                <div class="alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>Atenção:</strong> A instalação via APK requer que você ative a instalação de fontes desconhecidas nas configurações do seu dispositivo.
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Função para gerar cores neutras e profissionais
        function generateProfessionalColors(count) {
            const colors = [
                '#4B79A1', // Azul suave
                '#283E51', // Azul escuro
                '#F6B93B', // Amarelo suave
                '#A33D5D', // Vermelho suave
                '#6C757D', // Cinza
                '#28A745'  // Verde
            ];
            
            return colors.slice(0, count);
        }

        // Obter dados do PHP
        const dnsLabels = <?= json_encode(array_column($user_dns_distribution, 'dns')) ?>;
        const dnsData = <?= json_encode(array_column($user_dns_distribution, 'users')) ?>;
        
        // Gerar cores do gráfico
        const backgroundColors = generateProfessionalColors(dnsLabels.length);

        // Gráfico de Barras - Distribuição DNS
        const dnsCtx = document.getElementById('dnsDistributionChart').getContext('2d');
        new Chart(dnsCtx, {
            type: 'bar',  // Gráfico de barras
            data: {
                labels: dnsLabels,
                datasets: [{
                    label: 'Usuários',
                    data: dnsData,
                    backgroundColor: backgroundColors,
                    borderColor: '#fff',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'Número de Usuários'
                        },
                        grid: {
                            color: 'rgba(0, 0, 0, 0.1)', // Linhas de grade mais suaves
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: 'Servidores DNS'
                        },
                        grid: {
                            color: 'rgba(0, 0, 0, 0.1)', // Linhas de grade mais suaves
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false // Remover a legenda para um visual mais limpo
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const label = context.label || '';
                                const value = context.raw || 0;
                                return `${label}: ${value}`;
                            }
                        }
                    }
                }
            }
        });

        // Função para abrir o modal de edição
        const editUserModal = document.getElementById('editUserModal');
        const closeEditModal = document.getElementById('closeEditModal');
        
        const editButtons = document.querySelectorAll('.edit-user');
        editButtons.forEach(button => {
            button.addEventListener('click', function() {
                const userId = this.getAttribute('data-id');
                const username = this.getAttribute('data-username');
                const macAddress = this.getAttribute('data-mac');
                const dnsId = this.getAttribute('data-dns');
                const pin = this.getAttribute('data-pin');
                const password = this.getAttribute('data-password');

                document.getElementById('editUserId').value = userId;
                document.getElementById('editUsername').value = username;
                document.getElementById('editMacAddress').value = macAddress;
                document.getElementById('editDnsId').value = dnsId;
                document.getElementById('editPin').value = pin;
                document.getElementById('editPassword').value = password;

                editUserModal.classList.add('active');
                document.body.style.overflow = 'hidden';
            });
        });

        // Fechar modal de edição
        closeEditModal.addEventListener('click', function() {
            editUserModal.classList.remove('active');
            document.body.style.overflow = '';
        });

        // Fechar modal ao clicar no overlay
        editUserModal.addEventListener('click', function(e) {
            if (e.target === editUserModal) {
                closeEditModal.click();
            }
        });

        // Fechar com ESC
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && editUserModal.classList.contains('active')) {
                closeEditModal.click();
            }
        });

        // Função para abrir o modal de informações
        const infoModal = document.getElementById('infoModal');
        const showMoreInfoButton = document.getElementById('showMoreInfo');
        const closeInfoModal = document.getElementById('closeInfoModal');

        showMoreInfoButton.addEventListener('click', function() {
            infoModal.classList.add('active');
            document.body.style.overflow = 'hidden';
        });

        // Fechar modal de informações
        closeInfoModal.addEventListener('click', function() {
            infoModal.classList.remove('active');
            document.body.style.overflow = '';
        });

        // Fechar modal de informações ao clicar no overlay
        infoModal.addEventListener('click', function(e) {
            if (e.target === infoModal) {
                closeInfoModal.click();
            }
        });

        // Fechar modal de informações com ESC
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && infoModal.classList.contains('active')) {
                closeInfoModal.click();
            }
        });

        // Função para excluir usuário sem redirecionar
        window.deleteUser = function(userId) {
            if (confirm('Tem certeza que deseja excluir este usuário?')) {
                const xhr = new XMLHttpRequest();
                xhr.open('GET', '<?= basename($_SERVER["SCRIPT_NAME"]) ?>?delete=' + userId, true);
                xhr.onload = function() {
                    if (this.status === 200) {
                        // Recarregar a página para mostrar a lista atualizada
                        location.reload();
                    }
                };
                xhr.send();
            }
        };

        // Download buttons
        document.querySelector('.btn-primary').addEventListener('click', function() {
            window.location.href = 'apkaqui/IBO-PLAY-VS.apk';
        });
        
        document.querySelector('.btn-success').addEventListener('click', function() {
            window.location.href = 'https://play.google.com/store/apps/details?id=com.suaapp';
        });
    });
    </script>
</body>
</html>

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