<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$results_per_page = 5;

if (isset($_GET['view'])) {
    $page = $_GET['view'];
} else {
    $page = 1;
}

$start_from = ($page - 1) * $results_per_page;
$db1 = new SQLite3('a/.eggziedb.db');

// Search functionality
$searchTerm = isset($_GET['search']) ? $_GET['search'] : '';
$searchQuery = '';
if (!empty($searchTerm)) {
    $searchQuery = "WHERE nome LIKE '%$searchTerm%' OR usuario LIKE '%$searchTerm%'";
}

$result = $db1->query("SELECT COUNT(id) AS total FROM sub_revenda $searchQuery");
$rownew = $result->fetchArray();
$totaleview = $rownew['total'];
$total_pages = ceil($rownew['total'] / $results_per_page);
$res1 = $db1->query("SELECT * FROM sub_revenda $searchQuery ORDER BY id ASC LIMIT $start_from, $results_per_page");

if (isset($_GET['delete'])) {
    $result = $db1->query('SELECT usuario FROM sub_revenda WHERE id= ' . $_GET['delete']);
    while ($row = $result->fetchArray()) {
        $user = $row['usuario'];
        break;
    }
    $db1->exec('DELETE FROM sub_revenda WHERE id=' . $_GET['delete']);
    $db1->exec("UPDATE ibo SET seller = 'ADM' WHERE seller= '$user'");
    // remover arquivos e outros
    @unlink("a/rtx/Setting_$user.json");
    @unlink("a/rtx/logo_filenames_$user.json");
    @unlink("a/rtx/image_filenames_$user.json");
    @unlink("a/note_$user.json");
    @unlink("api/theme_$user.json");
    
    $db2 = new SQLite3("api/.adb.db");
    $db2->exec("DELETE FROM ads WHERE owner = '$user'");
    $db3 = new SQLite3("api/intro.db");
    $db3->exec("DELETE FROM intro WHERE owner = '$user'");
    header("Location: sub_revenda.php");
    exit;
}

// Carregar bloqueios
$block_file = 'a/subrevenda_block.json';
$blocked_data = file_exists($block_file) ? json_decode(file_get_contents($block_file), true) : [];

include 'includes/header.php';
?>

<style>
/* === ESTILOS ESPECÍFICOS PARA SUB REVENDA FUTURISTA === */
.main-content {
    background: transparent !important;
    padding: 20px;
}

.card {
    background: var(--surface-light) !important;
    border: 1px solid var(--border) !important;
    border-radius: 20px !important;
    box-shadow: 0 8px 40px rgba(0,0,0,0.4) !important;
    color: var(--text-primary) !important;
    overflow: hidden;
}

.card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, var(--primary), var(--accent), var(--secondary));
    animation: borderGlow 3s ease-in-out infinite;
}

@keyframes borderGlow {
    0%, 100% { opacity: 0.7; }
    50% { opacity: 1; }
}

.card-header {
    background: linear-gradient(135deg, var(--surface-light), var(--surface-lighter)) !important;
    border-bottom: 1px solid var(--border) !important;
    color: var(--text-primary) !important;
    font-weight: 700 !important;
    padding: 20px !important;
}

.card-body {
    background: transparent !important;
    color: var(--text-primary) !important;
    padding: 25px !important;
}

/* Tabela futurista */
.table {
    background: var(--surface-light) !important;
    color: var(--text-primary) !important;
    border: 1px solid var(--border) !important;
    border-radius: 16px !important;
    overflow: hidden;
    box-shadow: 0 4px 20px rgba(0,0,0,0.3);
}

.table thead {
    background: linear-gradient(135deg, var(--surface-lighter), var(--surface-light)) !important;
}

.table th {
    border-bottom: 2px solid var(--primary) !important;
    color: var(--text-primary) !important;
    font-weight: 700 !important;
    padding: 18px 12px !important;
    text-transform: uppercase;
    letter-spacing: 1px;
    font-size: 0.85rem;
}

.table td {
    border-bottom: 1px solid var(--border) !important;
    color: var(--text-secondary) !important;
    padding: 16px 12px !important;
    vertical-align: middle !important;
    transition: all 0.3s ease;
}

.table tbody tr:hover {
    background: rgba(0, 212, 255, 0.15) !important;
    transform: translateX(8px);
}

.table tbody tr:hover td {
    color: var(--text-primary) !important;
}

/* Formulários futuristas */
.form-control {
    background: var(--surface-lighter) !important;
    border: 1px solid var(--border) !important;
    color: var(--text-primary) !important;
    border-radius: 12px !important;
    padding: 14px 18px !important;
    font-size: 1rem;
    transition: all 0.3s ease;
}

.form-control:focus {
    border-color: var(--primary) !important;
    box-shadow: 0 0 0 0.3rem rgba(0, 212, 255, 0.25) !important;
    background: var(--surface-lighter) !important;
    color: var(--text-primary) !important;
}

.form-control::placeholder {
    color: var(--text-muted) !important;
}

/* Botões futuristas */
.btn-primary {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark)) !important;
    border: none !important;
    border-radius: 12px !important;
    box-shadow: var(--glow) !important;
    padding: 12px 24px !important;
    font-weight: 600 !important;
    transition: all 0.3s ease !important;
    text-transform: uppercase;
    letter-spacing: 1px;
}

.btn-primary:hover {
    transform: translateY(-3px) !important;
    box-shadow: 0 8px 25px rgba(0, 212, 255, 0.5) !important;
}

/* BOTÃO EXCLUIR SELECIONADOS VERMELHO */
.btn-danger {
    background: linear-gradient(135deg, #ff3860, #d1262b) !important;
    border: none !important;
    border-radius: 12px !important;
    box-shadow: 0 4px 15px rgba(255, 56, 96, 0.3) !important;
    padding: 12px 24px !important;
    font-weight: 600 !important;
    transition: all 0.3s ease !important;
    text-transform: uppercase;
    letter-spacing: 1px;
}

.btn-danger:hover {
    background: linear-gradient(135deg, #ff5470, #e74a3f) !important;
    transform: translateY(-3px) !important;
    box-shadow: 0 8px 25px rgba(255, 84, 112, 0.5) !important;
}

/* Botão de deletar específico */
.delete-btn {
    background: linear-gradient(135deg, #ff3860, #d1262b) !important;
    border: none !important;
    border-radius: 10px !important;
    padding: 10px 14px !important;
    color: white !important;
    transition: all 0.3s ease !important;
    box-shadow: 0 4px 12px rgba(255, 56, 96, 0.3) !important;
    position: relative;
    overflow: hidden;
}

.delete-btn::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
    transition: left 0.5s;
}

.delete-btn:hover::before {
    left: 100%;
}

.delete-btn:hover {
    background: linear-gradient(135deg, #ff5470, #e74a3f) !important;
    transform: translateY(-2px) scale(1.05) !important;
    box-shadow: 0 6px 20px rgba(255, 56, 96, 0.5) !important;
}

/* Checkboxes futuristas */
input[type="checkbox"] {
    width: 20px !important;
    height: 20px !important;
    accent-color: var(--primary) !important;
    cursor: pointer !important;
    border-radius: 4px !important;
}

/* Ícones */
.fa-pencil-square {
    color: var(--primary) !important;
    transition: all 0.3s ease !important;
    font-size: 20px !important;
}

.fa-ban {
    color: white !important;
    font-size: 16px !important;
}

.delete-btn:hover .fa-ban {
    transform: scale(1.2) !important;
    filter: drop-shadow(0 0 6px rgba(255, 255, 255, 0.8)) !important;
}

.fa-pencil-square:hover {
    transform: scale(1.3) !important;
    filter: drop-shadow(0 0 8px currentColor) !important;
}

/* Input group */
.input-group {
    border-radius: 12px !important;
    overflow: hidden !important;
    box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}

.input-group .form-control {
    border-radius: 12px 0 0 12px !important;
    border-right: none !important;
}

.input-group-append .btn {
    border-radius: 0 12px 12px 0 !important;
    border-left: none !important;
}

/* Badges e labels */
.text-primary2 {
    color: var(--primary) !important;
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    font-size: 1.3rem !important;
}

/* Paginação futurista */
.pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 8px;
    margin-top: 25px;
}

.pagination a {
    background: var(--surface-light);
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 10px 16px;
    color: var(--text-primary);
    text-decoration: none;
    transition: all 0.3s ease;
    font-weight: 600;
}

.pagination a:hover {
    background: var(--primary);
    color: white;
    transform: translateY(-2px);
    box-shadow: var(--glow);
}

.pagination .active {
    background: linear-gradient(135deg, var(--primary), var(--accent));
    color: white;
    box-shadow: var(--glow);
}

/* Botões de ação */
.btn-icon-split {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark)) !important;
    border: none !important;
    border-radius: 12px !important;
    padding: 12px 20px !important;
    color: white !important;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 10px;
    transition: all 0.3s ease;
    box-shadow: var(--glow);
}

.btn-icon-split:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 212, 255, 0.5);
    color: white !important;
    text-decoration: none;
}

/* Estados dos dados */
.code-text {
    background: var(--surface-lighter);
    padding: 4px 8px;
    border-radius: 6px;
    font-family: 'Courier New', monospace;
    font-size: 0.85rem;
    color: var(--accent);
}

/* Modal futurista */
.modal-content {
    background: var(--surface-light) !important;
    border: 1px solid var(--border) !important;
    border-radius: 20px !important;
    box-shadow: 0 20px 60px rgba(0,0,0,0.5) !important;
    color: var(--text-primary) !important;
}

.modal-header {
    background: linear-gradient(135deg, var(--surface-light), var(--surface-lighter)) !important;
    border-bottom: 1px solid var(--border) !important;
    color: var(--text-primary) !important;
    border-radius: 20px 20px 0 0 !important;
}

.modal-body {
    background: transparent !important;
    color: var(--text-primary) !important;
    padding: 25px !important;
}

.modal-footer {
    background: transparent !important;
    border-top: 1px solid var(--border) !important;
    border-radius: 0 0 20px 20px !important;
}

/* Responsividade */
@media (max-width: 768px) {
    .main-content {
        padding: 10px !important;
    }
    
    .table-responsive {
        border: 1px solid var(--border) !important;
        border-radius: 12px !important;
    }
    
    .table th, .table td {
        padding: 12px 8px !important;
        font-size: 0.8rem !important;
    }
    
    .btn {
        padding: 10px 15px !important;
        font-size: 0.85rem !important;
    }
    
    .card-body {
        padding: 15px !important;
    }
}

/* Efeito de partículas */
@keyframes moveParticles {
    from { transform: translateY(0); opacity: 0.7; }
    to { transform: translateY(-1000px); opacity: 0; }
}

.particle {
    position: fixed;
    bottom: 0;
    width: 2px;
    height: 2px;
    background: #4e73df;
    opacity: 0.5;
    animation: moveParticles linear infinite;
    z-index: -1;
}

.particle:nth-child(odd) { background: #6b8cff; }

/* Botões pequenos e alinhados na tabela */
.table .btn-sm {
    padding: 6px 10px !important;
    font-size: 0.8rem !important;
    border-radius: 8px !important;
    margin: 0 2px;
}

.table .btn-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.table .btn-icon i {
    font-size: 14px !important;
}
</style>

<script>
document.addEventListener("DOMContentLoaded", function() {
    const numParticles = 30;
    const particlesContainer = document.createElement('div');
    particlesContainer.style.position = 'fixed';
    particlesContainer.style.top = '0';
    particlesContainer.style.left = '0';
    particlesContainer.style.width = '100%';
    particlesContainer.style.height = '100%';
    particlesContainer.style.pointerEvents = 'none';
    particlesContainer.style.zIndex = '-1';
    for (let i = 0; i < numParticles; i++) {
        const particle = document.createElement('div');
        particle.classList.add('particle');
        particle.style.left = Math.random() * 100 + 'vw';
        particle.style.animationDuration = (2 + Math.random() * 8) + 's';
        particle.style.animationDelay = Math.random() * 10 + 's';
        particle.style.width = particle.style.height = (1 + Math.random() * 3) + 'px';
        particlesContainer.appendChild(particle);
    }
    document.body.appendChild(particlesContainer);
});


// Função para selecionar ou desmarcar todos os checkboxes
function toggle(source) {
    const checkboxes = document.querySelectorAll('input[name="selected_ids[]"]');
    checkboxes.forEach(checkbox => checkbox.checked = source.checked);
}

// Função para excluir os selecionados
function deleteSelected() {
    const selected = Array.from(document.querySelectorAll('input[name="selected_ids[]"]:checked'))
                          .map(cb => cb.value);

    if (selected.length === 0) {
        alert("Nenhuma sub revenda selecionada!");
        return;
    }

    if (confirm(`Deseja realmente excluir ${selected.length} sub revenda(s)?`)) {
        // Redireciona para o script de exclusão múltipla
        window.location.href = "sub_revenda_delete_multiple.php?ids=" + selected.join(",");
    }
}

</script>

<script>
// Função para selecionar ou desmarcar todos os checkboxes
function toggle(source) {
    const checkboxes = document.querySelectorAll('input[name="selected_ids[]"]');
    checkboxes.forEach(checkbox => checkbox.checked = source.checked);
}

// Função para excluir os selecionados
function deleteSelected() {
    const selected = Array.from(document.querySelectorAll('input[name="selected_ids[]"]:checked'))
                          .map(cb => cb.value);

    if (selected.length === 0) {
        alert("Nenhuma sub revenda selecionada!");
        return;
    }

    if (confirm(`Deseja realmente excluir ${selected.length} sub revenda(s)?`)) {
        // Redireciona para o script de exclusão múltipla
        window.location.href = "sub_revenda_delete_multiple.php?ids=" + selected.join(",");
    }
}
</script>





<main role="main" class="col-12 pt-4 px-4 main-content">
    <div id="main">
        <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-primary2">
                            <i class="fas fa-fw fa-user-plus" style="margin-right: 10px;"></i> SUB REVENDA
                        </h6>
                    </div>
                    <div class="card-body">
                        <!-- Formulário de pesquisa -->
                        <form method="get" class="mb-4">
                            <div class="input-group">
                                <input type="text" name="search" class="form-control" placeholder="🔍 Pesquise por nome ou usuário..." value="<?php echo htmlspecialchars($searchTerm); ?>">
                                <div class="input-group-append">
                                    <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Pesquisar</button>
                                </div>
                            </div>
                        </form>

                        <!-- Botões -->
                        <div class="form-group">
                            <a href="./sub_revenda_create.php" class="btn btn-primary btn-icon-split">
                                <i class="fas fa-plus"></i> Criar Sub Revenda
                            </a>
                            <button type="button" class="btn btn-danger ml-2" id="excluirSelecionados" onclick="deleteSelected()">
                                <i class="fas fa-trash"></i> Excluir Selecionados
                            </button>
                        </div>
                        <br>

                        <!-- Tabela -->
                        <div class="table-responsive">
                            <table class="table table-striped table-sm">
                                <thead>
                                    <tr>
                                        <th><input type="checkbox" onClick="toggle(this)"></th>
                                        <th>Ref.ID</th>
                                        <th>Nome</th>
                                        <th>Usuário</th>
                                        <th>Senha</th>
                                        <th>Registro</th>
                                        <th>Registrado por</th>
                                        <th>MACs</th>
                                        <th>Extra</th>
                                        <th>Editar</th>
                                        <th>Bloquear</th>
                                        <th>Deletar</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <?php while ($row1 = $res1->fetchArray()) { 
                                    $subrevenda_id = $row1['id'];
                                    $subrevenda_usuario = $row1['usuario'];
                                    $isBlocked = isset($blocked_data[$subrevenda_usuario]) && $blocked_data[$subrevenda_usuario]['blocked'];
                                ?>
                                    <tr>
                                        <td><input type="checkbox" name="selected_ids[]" value="<?php echo $subrevenda_id; ?>"></td>
                                        <td><span class="code-text"><?php echo $row1['id_ref']; ?></span></td>
                                        <td><strong><?php echo htmlspecialchars($row1['nome']); ?></strong></td>
                                        <td><span class="code-text"><?php echo htmlspecialchars($subrevenda_usuario); ?></span></td>
                                        <td><span class="code-text"><?php echo htmlspecialchars($row1['senha']); ?></span></td>
                                        <td><?php echo htmlspecialchars($row1['registro']); ?></td>
                                        <td><?php echo htmlspecialchars($row1['registrado_por']); ?></td>
                                        <td><span class="code-text"><?php echo htmlspecialchars($row1['macs']); ?></span></td>
                                        <td><?php echo htmlspecialchars($row1['extra']); ?></td>
                                        <td>
                                            <a class="btn btn-sm btn-icon" href="./sub_revenda_update.php?update=<?php echo $subrevenda_id; ?>">
                                                <i class="fa fa-pencil-square"></i>
                                            </a>
                                        </td>
                                        <td>
                                            <?php if ($isBlocked) { ?>
                                                <a class="btn btn-sm btn-danger" href="subrevenda_block.php?action=unblock&id=<?php echo $subrevenda_id; ?>" onclick="return confirm('Desbloquear esta subrevenda?')">
                                                    <i class="fa fa-unlock"></i>
                                                </a>
                                            <?php } else { ?>
                                                <a class="btn btn-sm btn-primary" href="subrevenda_block.php?action=block&id=<?php echo $subrevenda_id; ?>" onclick="return confirm('Bloquear esta subrevenda?')">
                                                    <i class="fa fa-lock"></i>
                                                </a>
                                            <?php } ?>
                                        </td>
                                        <td>
                                            <a class="btn btn-sm delete-btn" href="sub_revenda.php?delete=<?php echo $subrevenda_id; ?>" onclick="return confirm('Tem certeza que deseja excluir esta subrevenda?')">
                                                <i class="fa fa-ban"></i>
                                            </a>
                                        </td>
                                    </tr>
                                <?php } ?>
                                </tbody>
                            </table>
                        </div>

                        <?php if ($totaleview == 0): ?>
                            <div class="text-center py-5">
                                <i class="fas fa-user-plus fa-4x text-muted mb-3"></i>
                                <h5 class="text-muted">Nenhuma sub revenda encontrada</h5>
                                <p class="text-muted">Use o botão "Criar Sub Revenda" para adicionar novas sub revendas.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

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