<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

// --- LÓGICA DE FILTROS E PAGINAÇÃO ---
$limit_get = isset($_GET['limit']) ? $_GET['limit'] : 20;
$results_per_page = ($limit_get === 'all') ? 999999 : (int)$limit_get;
$page = isset($_GET['view']) ? (int)$_GET['view'] : 1;
$start_from = ($page - 1) * $results_per_page;

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

// Contagem total
$resultCount = $db1->query("SELECT COUNT(id) AS total FROM revenda $searchQuery");
$rowCount = $resultCount->fetchArray();
$totaleview = $rowCount['total'];
$total_pages = ceil($totaleview / $results_per_page);

// Query Final
$res1 = $db1->query("SELECT * FROM revenda $searchQuery ORDER BY id ASC LIMIT $start_from, $results_per_page");

// Lógica de Exclusão (Mantida original com exclusão de arquivos)
if (isset($_GET['delete'])) {
    $ids_to_delete = explode(',', $_GET['delete']);
    foreach ($ids_to_delete as $id) {
        $id = (int)$id;
        $revenda_result = $db1->query("SELECT usuario FROM revenda WHERE id = $id");
        if ($revenda_row = $revenda_result->fetchArray()) {
            $usuario = $revenda_row['usuario'];
            $db1->exec("DELETE FROM revenda WHERE id = $id");

            // Remove arquivos associados
            @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");

            $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');
    exit();
}

include 'includes/header.php';
?>

<style>
    :root {
        --neon-blue: #00d4ff;
        --dark-bg: #06090c;
        --card-glass: rgba(13, 18, 24, 0.95);
        --border-glass: rgba(0, 212, 255, 0.2);
    }

    /* --- REMOÇÃO TOTAL DO FUNDO BRANCO --- */
    html, body, 
    #wrapper, 
    #content-wrapper, 
    #content, 
    .container-fluid,
    .bg-white,
    .bg-light {
        background-color: var(--dark-bg) !important;
        color: #f8f9fc !important;
    }

    body { 
        font-family: 'Poppins', sans-serif;
    }

    .card-futuristic {
        background: var(--card-glass) !important;
        backdrop-filter: blur(15px);
        border: 1px solid var(--border-glass) !important;
        border-radius: 15px !important;
        box-shadow: 0 10px 30px rgba(0,0,0,0.5);
    }

    .card-header-futuristic {
        background: rgba(0, 212, 255, 0.03) !important;
        border-bottom: 1px solid var(--border-glass) !important;
        padding: 1.2rem !important;
    }

    .card-header-futuristic h6 {
        font-family: 'Orbitron', sans-serif;
        color: var(--neon-blue) !important;
        text-shadow: 0 0 10px var(--neon-blue);
        letter-spacing: 2px;
        margin: 0;
    }

    .table-modern {
        color: #e0e0e0 !important;
        border-collapse: separate;
        border-spacing: 0 10px;
    }

    .table-modern thead th {
        border: none !important;
        color: var(--neon-blue) !important;
        text-transform: uppercase;
        font-size: 0.75rem;
        letter-spacing: 1px;
        padding: 12px;
    }

    .table-modern tbody tr {
        background: rgba(255, 255, 255, 0.02);
        transition: all 0.3s ease;
    }

    .table-modern tbody tr:hover {
        background: rgba(0, 212, 255, 0.08);
        transform: scale(1.005);
    }

    .table-modern td {
        border: none !important;
        padding: 12px !important;
        vertical-align: middle !important;
    }

    .form-control-futuristic {
        background: rgba(0, 0, 0, 0.4) !important;
        border: 1px solid var(--border-glass) !important;
        color: #fff !important;
        border-radius: 8px;
    }

    .form-control-futuristic:focus {
        border-color: var(--neon-blue) !important;
        box-shadow: 0 0 10px var(--neon-blue);
        outline: none;
    }

    .btn-neon {
        background: transparent;
        border: 1px solid var(--neon-blue);
        color: var(--neon-blue) !important;
        transition: 0.3s;
        border-radius: 8px;
    }

    .btn-neon:hover {
        background: var(--neon-blue);
        color: #000 !important;
        box-shadow: 0 0 15px var(--neon-blue);
    }

    .page-link-neon {
        padding: 8px 15px;
        border: 1px solid var(--border-glass);
        background: rgba(255,255,255,0.02);
        color: #fff;
        margin: 0 3px;
        border-radius: 5px;
        text-decoration: none;
    }

    .page-link-neon.active {
        border-color: var(--neon-blue);
        color: var(--neon-blue);
        background: rgba(0, 212, 255, 0.1);
    }
    
    code {
        background-color: transparent !important;
        color: var(--neon-blue);
    }
</style>

<main role="main" class="col-15 pt-4 px-5">
    <div class="card card-futuristic shadow mb-4">
        <div class="card-header-futuristic d-flex justify-content-between align-items-center">
            <h6><i class="fas fa-user-tie mr-2"></i> GERENCIAMENTO DE REVENDAS</h6>
            <span class="badge" style="border: 1px solid var(--neon-blue); color: var(--neon-blue);">Total: <?php echo $totaleview; ?></span>
        </div>
        <div class="card-body">
            
            <form method="get" class="mb-4">
                <div class="row align-items-end">
                    <div class="col-md-4">
                        <label class="small text-uppercase">Pesquisar Revenda</label>
                        <div class="input-group">
                            <input type="text" name="search" class="form-control form-control-futuristic" placeholder="Nome ou Usuario..." value="<?php echo htmlspecialchars($searchTerm); ?>">
                            <div class="input-group-append">
                                <button type="submit" class="btn btn-neon"><i class="fas fa-search"></i></button>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <label class="small text-uppercase">Exibir</label>
                        <select name="limit" class="form-control form-control-futuristic" onchange="this.form.submit()">
                            <?php $opts = [5, 10, 20, 30, 50, 100, 'all']; foreach($opts as $o): ?>
                                <option value="<?php echo $o; ?>" <?php echo $limit_get == $o ? 'selected' : ''; ?>><?php echo $o == 'all' ? 'Ver Tudo' : "$o por pagina"; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-5 text-right">
                        <a href="./revenda_create.php" class="btn btn-neon p-2 px-3"><i class="fas fa-plus mr-2"></i>CRIAR NOVA</a>
                        <button type="button" class="btn btn-outline-danger p-2 px-3" id="excluirSelecionados" style="border-radius:8px;"><i class="fas fa-trash-alt mr-2"></i>EXCLUIR SELECIONADOS</button>
                    </div>
                </div>
            </form>

            <div class="table-responsive">
                <table class="table table-modern">
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="selecionarTodosCheckbox"></th>
                            <th>Ref ID</th>
                            <th>Nome</th>
                            <th>Usuario</th>
                            <th>Senha</th>
                            <th>Registro</th>
                            <th>MACs</th>
                            <th>Extra</th>
                            <th>Editar</th>
                            <th>Deletar</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($row1 = $res1->fetchArray()): ?>
                            <tr>
                                <td><input type="checkbox" name="delete_check[]" value="<?php echo $row1['id']; ?>"></td>
                                <td><span style="color:var(--neon-blue);"><?php echo $row1['id_ref']; ?></span></td>
                                <td class="font-weight-bold" style="color:#fff;"><?php echo $row1['nome']; ?></td>
                                <td><code><?php echo $row1['usuario']; ?></code></td>
                                <td><?php echo $row1['senha']; ?></td>
                                <td><small><?php echo $row1['registro']; ?></small></td>
                                <td><span class="badge" style="background: rgba(0, 212, 255, 0.2); color: var(--neon-blue); border: 1px solid var(--neon-blue);"><?php echo $row1['macs']; ?></span></td>
                                <td><small style="opacity:0.5;"><?php echo $row1['extra']; ?></small></td>
                                <td>
                                    <a href="./revenda_update.php?update=<?php echo $row1['id']; ?>">
                                        <i class="fa fa-edit" style="font-size:18px; color:var(--neon-blue)"></i>
                                    </a>
                                </td>
                                <td>
                                    <a href="./revenda.php?delete=<?php echo $row1['id']; ?>" onclick="return confirm('Excluir esta revenda e todos os seus arquivos?');">
                                        <i class="fa fa-times-circle" style="font-size:18px; color:#ff3e3e"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($total_pages > 1 && $limit_get !== 'all'): ?>
                <div class="d-flex justify-content-center mt-4">
                    <?php 
                        $url_params = "&limit=$limit_get&search=".urlencode($searchTerm);
                        if($page > 1) echo "<a href='revenda.php?view=".($page-1)."$url_params' class='page-link-neon'>&lt;</a>";
                        for($i=1; $i<=$total_pages; $i++) {
                            $active = ($i == $page) ? 'active' : '';
                            echo "<a href='revenda.php?view=$i$url_params' class='page-link-neon $active'>$i</a>";
                        }
                        if($page < $total_pages) echo "<a href='revenda.php?view=".($page+1)."$url_params' class='page-link-neon'>&gt;</a>";
                    ?>
                </div>
            <?php endif; ?>

        </div>
    </div>
</main>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        const selTodos = document.getElementById("selecionarTodosCheckbox");
        selTodos.addEventListener("click", function() {
            var checkboxes = document.querySelectorAll("input[name='delete_check[]']");
            checkboxes.forEach(function(checkbox) {
                checkbox.checked = selTodos.checked;
            });
        });

        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) {
                if (confirm("ATENÇÃO: Isso excluirá as revendas selecionadas e todos os arquivos vinculados. Confirmar?")) {
                    window.location.href = 'revenda.php?delete=' + selectedIds.join(',');
                }
            } else {
                alert("Selecione ao menos uma revenda.");
            }
        });
    });
</script>

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