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

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

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

//LOGICA DE BLOQUEIO
$block_file = 'a/revenda_block.json';
$blocked_data = file_exists($block_file) ? json_decode(file_get_contents($block_file), true) : [];
if (!is_array($blocked_data)) $blocked_data = [];

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

// BUSCAR DADOS COMBINADOS DE REVENDA E SUB_REVENDA
$result = $db1->query("
    SELECT COUNT(*) AS total FROM (
        SELECT id, nome, usuario, senha, registro, macs, extra, id_ref, 'revenda' as tipo FROM revenda
        UNION ALL
        SELECT id, nome, usuario, senha, registro, macs, extra, id_ref, 'subrevenda' as tipo FROM sub_revenda
    ) AS combined $searchQuery
");
$rownew = $result->fetchArray();
$totaleview = $rownew['total'];
$total_pages = ceil($rownew['total'] / $results_per_page);

// Query combinada com paginação
$res1 = $db1->query("
    SELECT * FROM (
        SELECT id, nome, usuario, senha, registro, macs, extra, id_ref, 'revenda' as tipo FROM revenda
        UNION ALL
        SELECT id, nome, usuario, senha, registro, macs, extra, id_ref, 'subrevenda' as tipo FROM sub_revenda
    ) AS combined $searchQuery 
    ORDER BY id DESC 
    LIMIT $start_from, $results_per_page
");

if (isset($_GET['delete'])) {
    $ids_to_delete = explode(',', $_GET['delete']);
    foreach ($ids_to_delete as $id) {
        // Primeiro verificar se é revenda ou subrevenda
        $check_result = $db1->query("
            SELECT usuario, 'revenda' as tipo FROM revenda WHERE id = $id
            UNION ALL
            SELECT usuario, 'subrevenda' as tipo FROM sub_revenda WHERE id = $id
        ");
        
        if ($check_row = $check_result->fetchArray()) {
            $usuario = $check_row['usuario'];
            $tipo = $check_row['tipo'];
            
            // Deletar do banco correto
            if ($tipo === 'revenda') {
                $db1->exec("DELETE FROM revenda WHERE id = $id");
            } else {
                $db1->exec("DELETE FROM sub_revenda WHERE id = $id");
            }

            // Remover associated files
            unlink("a/rtx/Setting_$usuario.json");
            unlink("a/rtx/logo_filenames_$usuario.json");
            unlink("a/rtx/image_filenames_$usuario.json");
            unlink("a/note_$usuario.json");
            unlink("api/theme_$usuario.json");

            // Update related entries in other tables
            $db1->exec("UPDATE ibo SET seller = 'ADM' WHERE seller = '$usuario'");
            $db2 = new SQLite3("api/.adb.db");
            $db2->exec("DELETE FROM ads WHERE owner = '$usuario'");
            $db3 = new SQLite3("api/intro.db");
            $db3->exec("DELETE FROM intro WHERE owner = '$usuario'");
        }
    }
    header('Location: revenda.php');
}

include 'includes/header.php';
?>

<style>
/* === ESTILOS ESPECÍFICOS PARA REVENDA FUTURISTA === */

 /* === DESIGN FUTURISTA MODERNO === */
    :root {
        --primary: #00D4FF;
        --primary-dark: #0099CC;
        --secondary: #FF6B9D;
        --accent: #00FF88;
        --surface: #0A0F1C;
        --surface-light: #1A1F2C;
        --surface-lighter: #2A2F3C;
        --text-primary: #FFFFFF;
        --text-secondary: #B0B7C3;
        --text-muted: #6B7280;
        --border: rgba(255,255,255,0.1);
        --glow: 0 0 20px rgba(0, 212, 255, 0.3);
        --glow-accent: 0 0 20px rgba(0, 255, 136, 0.3);
    }

.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;
}

/* Badge para tipo */
.tipo-badge {
    padding: 4px 8px;
    border-radius: 6px;
    font-size: 0.7rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.tipo-revenda {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    color: white;
}

.tipo-subrevenda {
    background: linear-gradient(135deg, var(--secondary), #FF416C);
    color: white;
}

/* 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;
}

.btn-danger {
    background: linear-gradient(135deg, #FF6B9D, #FF416C) !important;
    border: none !important;
    border-radius: 12px !important;
    box-shadow: 0 0 20px rgba(255, 107, 157, 0.3) !important;
    padding: 10px 20px !important;
    font-weight: 600 !important;
    transition: all 0.3s ease !important;
}

.btn-danger:hover {
    transform: translateY(-2px) !important;
    box-shadow: 0 0 30px rgba(255, 107, 157, 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: var(--tertiary) !important;
    transition: all 0.3s ease !important;
    font-size: 20px !important;
}

.fa-pencil-square:hover, .fa-ban: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);
}

/* 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ão de deletar específico */
.delete-btn {
    background: linear-gradient(135deg, #d1262b, #a71c1f) !important;
    border: none !important;
    border-radius: 8px !important;
    padding: 8px 12px !important;
    color: white !important;
    transition: all 0.3s ease !important;
}

.delete-btn:hover {
    background: linear-gradient(135deg, #e74a3f, #c23b3b) !important;
    transform: translateY(-2px) !important;
    box-shadow: 0 4px 15px rgba(231, 74, 63, 0.4) !important;
    color: white !important;
}

/* Ícone de deletar */
.fa-ban {
    color: white !important;
    transition: all 0.3s ease !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;
}

/* 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() {
        // Partículas animadas
        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);

        // Selecionar todos os checkboxes
        document.getElementById("selecionarTodos").addEventListener("click", function() {
            var checkboxes = document.querySelectorAll("input[name='delete_check[]']");
            checkboxes.forEach(function(checkbox) {
                checkbox.checked = true;
            });
        });

        // Excluir selecionados
        document.getElementById("excluirSelecionados").addEventListener("click", function() {
            var selectedIds = [];
            var checkboxes = document.querySelectorAll("input[name='delete_check[]']");
            checkboxes.forEach(function(checkbox) {
                if (checkbox.checked) {
                    selectedIds.push(checkbox.value);
                }
            });
            if (selectedIds.length > 0) {
                var confirmation = confirm("Tem certeza de que deseja excluir os itens selecionados?");
                if (confirmation) {
                    window.location.href = 'revenda.php?delete=' + selectedIds.join(',');
                }
            } else {
                alert("Por favor, selecione pelo menos um item para excluir.");
            }
        });

        // Adicionar efeitos hover nas linhas
        const tableRows = document.querySelectorAll('.table tbody tr');
        tableRows.forEach(row => {
            row.style.transition = 'all 0.3s ease';
        });
    });

    function selecionarTodos() {
        var checkboxes = document.querySelectorAll("input[name='delete_check[]']");
        checkboxes.forEach(function(checkbox) {
            checkbox.checked = true;
        });
    }
</script>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<main role="main" class="col-12 pt-4 px-4 main-content">
    <div class="">
        <div class="chartjs-size-monitor" style="position:absolute; left:0; top:0; right:0; bottom:0; overflow:hidden; pointer-events:none; visibility:hidden; z-index:-1;">
            <div class="chartjs-size-monitor-expand" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;">
                <div style="position:absolute;width:1000000px;height:1000000px;left:0;top:0"></div>
            </div>
            <div class="chartjs-size-monitor-shrink" style="position:absolute;left:0;top:0;right:0;bottom:0;overflow:hidden;pointer-events:none;visibility:hidden;z-index:-1;">
                <div style="position:absolute;width:200%;height:200%;left:0; top:0"></div>
            </div>
        </div>
        <div id="main">
            <!-- Content Row -->
            <div class="row">
                <!-- First Column -->
                <div class="col-lg-12">
                    <!-- Custom codes -->
                    <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-store" style="margin-right: 10px;"></i> 
                                REVENDAS E SUB-REVENDAS
                            </h6>
                        </div>
                        <div class="card-body">
                            <!-- Formulário de pesquisa -->
                            <form method="get" class="mb-4">
                                <div class="form-group">
                                    <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>
                                </div>
                            </form>
                            
                            <!-- Botões de ação -->
                            <div class="form-group">
                                <div class="input-group">
                                    <a href="./revenda_create.php" class="btn btn-primary btn-icon-split">
                                        <span class="icon text-white-50">
                                            <i class="fas fa-plus"></i>
                                        </span>
                                        <span class="text">Criar Revenda e Sub_revenda</span>
                                    </a>
                                    <button type="button" class="btn btn-danger ml-2" id="excluirSelecionados">
                                        <i class="fas fa-trash"></i> Excluir Selecionados
                                    </button>
                                </div>
                            </div>
                            
                            <br>
                            
                            <!-- Tabela de revendas e sub-revendas -->
                            <div class="table-responsive">
                                <table class="table table-striped table-sm">
                                    <thead class="text-primary">
                                        <tr>
                                            <th><input type="checkbox" id="selecionarTodos" onclick="selecionarTodos()"></th>
                                            <th>Tipo</th>
                                            <th>Ref.ID</th>
                                            <th>Nome</th>
                                            <th>Usuário</th>
                                            <th>Senha</th>
                                            <th>Registro</th>
                                            <th>MACs</th>
                                            <th>Extra</th>
                                            <th>Editar</th>
                                            <th>Bloquear</th>
                                            <th>Deletar</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php while ($row1 = $res1->fetchArray()) { ?>
                                            <tr>
                                                <?php
                                                $revenda_id = $row1['id'];
                                                $revenda_rid = $row1['id_ref'];
                                                $revenda_nome = $row1['nome'];
                                                $revenda_usuario = $row1['usuario'];
                                                $revenda_senha = $row1['senha'];
                                                $revenda_registro = $row1['registro'];
                                                $revenda_macs = $row1['macs'];
                                                $tipo = $row1['tipo'];
                                                ?>
                                                <td><input type="checkbox" name="delete_check[]" value="<?php echo $revenda_id; ?>"></td>
                                                <td>
                                                    <span class="tipo-badge <?php echo $tipo === 'revenda' ? 'tipo-revenda' : 'tipo-subrevenda'; ?>">
                                                        <?php echo $tipo === 'revenda' ? 'REVENDA' : 'SUB-REVENDA'; ?>
                                                    </span>
                                                </td>
                                                <td><span class="code-text"><?php echo $revenda_rid; ?></span></td>
                                                <td><strong><?php echo htmlspecialchars($revenda_nome); ?></strong></td>
                                                <td><span class="code-text"><?php echo htmlspecialchars($revenda_usuario); ?></span></td>
                                                <td><span class="code-text"><?php echo htmlspecialchars($revenda_senha); ?></span></td>
                                                <td><?php echo htmlspecialchars($revenda_registro); ?></td>
                                                <td><span class="code-text"><?php echo htmlspecialchars($revenda_macs); ?></span></td>
                                                <td><?php echo htmlspecialchars($row1['extra']); ?></td>
                                                <td class="text-center">
                                                    <a class="btn btn-sm btn-icon" href="./revenda_update.php?update=<?php echo $revenda_id; ?>&tipo=<?php echo $tipo; ?>" title="Editar">
                                                        <i class="fa fa-pencil-square"></i>
                                                    </a>
                                                </td>
                                                <td class="text-center">
                                                    <?php
                                                    $isBlocked = isset($blocked_data[$revenda_usuario]) && $blocked_data[$revenda_usuario]['blocked'];
                                                    if ($isBlocked) {
                                                        echo '<a class="btn btn-sm btn-danger" href="revenda_block.php?action=unblock&id='.$revenda_id.'&tipo='.$tipo.'" 
                                                                 title="Desbloquear" onclick="return confirm(\'Desbloquear esta '.$tipo.'?\')">
                                                                 <i class=\'fa fa-unlock\'></i>
                                                              </a>';
                                                    } else {
                                                        echo '<a class="btn btn-sm btn-primary" href="revenda_block.php?action=block&id='.$revenda_id.'&tipo='.$tipo.'" 
                                                                 title="Bloquear" onclick="return confirm(\'Bloquear esta '.$tipo.'?\')">
                                                                 <i class=\'fa fa-lock\'></i>
                                                              </a>';
                                                    }
                                                    ?>
                                                </td>
                                                <td class="text-center">
                                                    <a class="btn btn-sm delete-btn" href="./revenda.php?delete=<?php echo $revenda_id; ?>" 
                                                       onclick="return confirm('Tem certeza de que deseja excluir esta <?php echo $tipo; ?>?')" title="Deletar">
                                                        <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-store fa-4x text-muted mb-3"></i>
                                    <h5 class="text-muted">Nenhuma revenda ou sub-revenda encontrada</h5>
                                    <p class="text-muted">Use o botão "Criar Revenda" para adicionar novas revendas.</p>
                                </div>
                            <?php endif; ?>
                            
                            <!-- Paginação -->
                            <?php if ($results_per_page < $totaleview) { ?>
                                <div class="pagination">
                                    <?php if ($page > 1) { ?>
                                        <a class="pagination pagination-gap" href='revenda.php?view=<?php echo ($page - 1); ?>'>
                                            <i class="fas fa-chevron-left"></i> Anterior
                                        </a>
                                    <?php } ?>
                                    <?php for ($i = 1; $i <= $total_pages; $i++) { ?>
                                        <?php if ($i == $page) { ?>
                                            <a class="active pagination pagination-red" href='revenda.php?view=<?php echo $i; ?>'>
                                                <?php echo $i; ?>
                                            </a>
                                        <?php } else { ?>
                                            <a class="pagination pagination-gap" href='revenda.php?view=<?php echo $i; ?>'>
                                                <?php echo $i; ?>
                                            </a>
                                        <?php } ?>
                                    <?php } ?>
                                    <?php if ($page < $total_pages) { ?>
                                        <a class="pagination pagination-gap" href='revenda.php?view=<?php echo ($page + 1); ?>'>
                                            Próxima <i class="fas fa-chevron-right"></i>
                                        </a>
                                    <?php } ?>
                                </div>
                            <?php } ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

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