<?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'] : '';
$filterRegistrador = isset($_GET['f_registrador']) ? $_GET['f_registrador'] : '';

// Construção da Query Dinâmica
$conditions = [];
if (!empty($searchTerm)) {
    $conditions[] = "(nome LIKE '%$searchTerm%' OR usuario LIKE '%$searchTerm%')";
}
if (!empty($filterRegistrador)) {
    $conditions[] = "registrado_por = '$filterRegistrador'";
}

$whereClause = count($conditions) > 0 ? "WHERE " . implode(" AND ", $conditions) : "";

// Busca lista de quem registrou
$registradoresList = $db1->query("SELECT DISTINCT registrado_por FROM sub_revenda WHERE registrado_por IS NOT NULL AND registrado_por != '' ORDER BY registrado_por ASC");

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

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

// Lógica de Exclusão
if (isset($_GET['delete'])) {
    $ids_to_delete = explode(',', $_GET['delete']);
    foreach ($ids_to_delete as $id_del) {
        $id_del = (int)$id_del;
        $res_user = $db1->query('SELECT usuario FROM sub_revenda WHERE id= ' . $id_del);
        if ($row_user = $res_user->fetchArray()) {
            $user = $row_user['usuario'];
            $db1->exec('DELETE FROM sub_revenda WHERE id=' . $id_del);
            $db1->exec("UPDATE ibo SET seller = 'ADM' WHERE seller= '$user'");
            @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();
}

include 'includes/header.php';
?>

<style>
    @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&family=Poppins:wght@300;400;600&display=swap');

    :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 DE 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; width: 100%; }
    .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; 
    }
    
    .btn-neon { 
        background: transparent; 
        border: 1px solid var(--neon-blue); 
        color: var(--neon-blue) !important; 
        font-family: 'Orbitron', sans-serif;
        font-size: 0.75rem;
        transition: 0.3s; 
        border-radius: 8px; 
        text-transform: uppercase;
        padding: 8px 15px;
    }
    
    .btn-neon:hover { background: var(--neon-blue); color: #000 !important; box-shadow: 0 0 15px var(--neon-blue); }
    
    .btn-neon-danger {
        background: transparent;
        border: 1px solid #ff3e3e;
        color: #ff3e3e !important;
        font-family: 'Orbitron', sans-serif;
        font-size: 0.75rem;
        padding: 8px 15px;
        border-radius: 8px;
        text-transform: uppercase;
    }

    .btn-neon-danger:hover { background: #ff3e3e; color: #fff !important; box-shadow: 0 0 15px rgba(255, 62, 62, 0.4); }

    .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); }
    
    input[type="checkbox"] { accent-color: var(--neon-blue); cursor: pointer; }
    code { background: 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-network-wired mr-2"></i> SUB REVENDAS</h6>
            <span class="badge" style="border: 1px solid var(--neon-blue); color: var(--neon-blue);">Registros: <?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-3">
                        <label class="small text-uppercase">Pesquisar</label>
                        <input type="text" name="search" class="form-control form-control-futuristic" placeholder="Nome ou Usuário..." value="<?php echo htmlspecialchars($searchTerm); ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <label class="small text-uppercase">Registrador</label>
                        <select name="f_registrador" class="form-control form-control-futuristic">
                            <option value="">Todos</option>
                            <?php while($reg = $registradoresList->fetchArray()): ?>
                                <option value="<?php echo $reg['registrado_por']; ?>" <?php echo $filterRegistrador == $reg['registrado_por'] ? 'selected' : ''; ?>>
                                    <?php echo $reg['registrado_por']; ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>

                    <div class="col-md-2">
                        <label class="small text-uppercase">Exibir</label>
                        <select name="limit" class="form-control form-control-futuristic">
                            <?php $opts = [5, 10, 20, 50, 100, 'all']; foreach($opts as $o): ?>
                                <option value="<?php echo $o; ?>" <?php echo $limit_get == $o ? 'selected' : ''; ?>><?php echo $o == 'all' ? 'Tudo' : "$o Itens"; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-5 text-right">
                        <button type="submit" class="btn btn-neon"><i class="fas fa-filter mr-1"></i> Filtrar</button>
                        <a href="./sub_revenda_create.php" class="btn btn-neon"><i class="fas fa-plus mr-1"></i> Novo</a>
                        <button type="button" class="btn btn-neon-danger" onclick="deleteSelected()"><i class="fas fa-trash-alt mr-1"></i> Excluir</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>Usuário</th>
                            <th>Senha</th>
                            <th>Registro</th>
                            <th>Registrador por</th>
                            <th>MACs</th>
                            <th>Editar</th>
                            <th>Deletar</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($row1 = $res1->fetchArray()): ?>
                            <tr>
                                <td><input type="checkbox" name="selected_ids[]" 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 
                                            // CONVERSÃO DE FORMATO DE DATA (Y/m/d -> d/m/Y)
                                            echo date("d/m/Y", strtotime($row1['registro'])); 
                                        ?>
                                    </small>
                                </td>
                                <td>
                                    <span class="badge" style="background:rgba(0,212,255,0.05); border:1px solid rgba(0,212,255,0.3); color: #fff;">
                                        <?php echo (!empty($row1['registrado_por'])) ? $row1['registrado_por'] : 'ADM'; ?>
                                    </span>
                                </td>
                                <td><span class="badge badge-primary" 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>
                                    <a href="./sub_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 class="delete-btn" href="#" data-href="sub_revenda.php?delete=<?php echo $row1['id']; ?>" data-toggle="modal" data-target="#confirm-delete">
                                        <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)."&f_registrador=".urlencode($filterRegistrador);
                        if($page > 1) echo "<a href='sub_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='sub_revenda.php?view=$i$url_params' class='page-link-neon $active'>$i</a>";
                        }
                        if($page < $total_pages) echo "<a href='sub_revenda.php?view=".($page+1)."$url_params' class='page-link-neon'>&gt;</a>";
                    ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</main>

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content card-futuristic">
            <div class="modal-header border-bottom-0"><h2 style="color:var(--neon-blue); font-family: 'Orbitron';">Confirmar</h2></div>
            <div class="modal-body text-white">Deseja realmente excluir este Sub Revenda? Essa ação é irreversível!</div>
            <div class="modal-footer border-top-0">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                <a class="btn btn-danger btn-ok">Deletar</a>
            </div>
        </div>
    </div>
</div>

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

    $('#confirm-delete').on('show.bs.modal', function(e) {
        $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
    });

    function deleteSelected() {
        var selectedIds = [];
        var checkboxes = document.getElementsByName('selected_ids[]');
        for (var i = 0; i < checkboxes.length; i++) {
            if (checkboxes[i].checked) { selectedIds.push(checkboxes[i].value); }
        }
        if (selectedIds.length > 0) {
            if (confirm('Excluir os selecionados permanentemente?')) {
                window.location.href = 'sub_revenda.php?delete=' + selectedIds.join(',');
            }
        } else { alert('Selecione ao menos um item.'); }
    }
</script>

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