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

// --- CONFIGURAÇÃO DE RESULTADOS POR PÁGINA (FILTRO) ---
$limit_get = isset($_GET['limit']) ? $_GET['limit'] : 5;
$results_per_page = ($limit_get === 'all') ? 999999 : (int)$limit_get;

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

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

$searchTerm = isset($_GET['search']) ? $_GET['search'] : '';
include '../includes/header2.php';

// --- LÓGICA DE PESQUISA ORIGINAL ---
if (!empty($searchTerm)) {
    $searchQuery = "WHERE (nome LIKE '%$searchTerm%' OR usuario LIKE '%$searchTerm%') AND registrado_por = '$seller_name'";
} else {
    $searchQuery = "WHERE registrado_por = '$seller_name'";
}

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

// Query Final com Limite Dinâmico
$res1 = $db1->query("SELECT * FROM sub_revenda $searchQuery ORDER BY id ASC LIMIT $start_from, $results_per_page");

// --- LÓGICA DE EXCLUSÃO ORIGINAL ---
if (isset($_GET['delete'])) {
    $result = $db1->query('SELECT usuario FROM sub_revenda WHERE id= ' . (int)$_GET['delete']);
    while ($row = $result->fetchArray()) {
        $user = $row['usuario'];
        break;
    }
    $db1->exec('DELETE FROM sub_revenda WHERE id=' . (int)$_GET['delete']);
    $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'");
    
    echo "<script>window.location.href='sub_revenda.php';</script>";
    exit();
}
?>

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

    :root {
        --neon-emerald: #00ff88;
        --neon-gold: #ffcc00;
        --dark-bg: #050a0e;
        --glass-bg: rgba(255, 255, 255, 0.02);
        --glass-border: rgba(0, 255, 136, 0.15);
    }

    /* Blindagem total contra fundo branco */
    html, body, #wrapper, #content-wrapper, #content, .bg-white, .container-fluid, .card-body {
        background-color: var(--dark-bg) !important;
        color: #e0e0e0 !important;
    }

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

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

    .card-header-futuristic h6 {
        font-family: 'Orbitron', sans-serif;
        color: var(--neon-emerald) !important;
        text-shadow: 0 0 8px var(--neon-emerald);
        margin: 0;
        text-transform: uppercase;
    }

    .table-modern { color: #e0e0e0 !important; border-collapse: separate; border-spacing: 0 8px; width: 100%; }
    .table-modern thead th { border: none !important; color: var(--neon-emerald); text-transform: uppercase; font-size: 0.65rem; padding: 12px; }
    .table-modern tbody tr { background: rgba(255, 255, 255, 0.02); transition: 0.3s; }
    .table-modern tbody tr:hover { background: rgba(0, 255, 136, 0.05); }
    .table-modern td { border: none !important; padding: 12px !important; vertical-align: middle !important; font-size: 0.85rem; }

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

    .btn-emerald {
        background: transparent;
        border: 1px solid var(--neon-emerald);
        color: var(--neon-emerald) !important;
        font-family: 'Orbitron', sans-serif;
        font-size: 0.75rem;
        transition: 0.4s;
        text-transform: uppercase;
        padding: 8px 15px;
    }

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

    code { background: transparent; color: var(--neon-gold); font-weight: bold; }
    
    .pagination-neon { display: flex; gap: 5px; justify-content: center; margin-top: 20px; }
    .page-link-neon { background: #000; border: 1px solid var(--glass-border); color: #fff; padding: 6px 12px; border-radius: 4px; text-decoration: none; }
    .page-link-neon.active { border-color: var(--neon-emerald); color: var(--neon-emerald); background: rgba(0, 255, 136, 0.1); }
</style>

<div class="container-fluid 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-fw fa-user-plus mr-2"></i> Sub Revendas</h6>
            <span class="badge" style="border: 1px solid var(--neon-gold); color: var(--neon-gold);">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-4">
                        <label class="small text-uppercase" style="color: var(--neon-emerald)">Pesquisar</label>
                        <input type="text" name="search" class="form-control form-control-futuristic" placeholder="Nome ou usuario" value="<?php echo htmlspecialchars($searchTerm); ?>">
                    </div>
                    
                    <div class="col-md-3">
                        <label class="small text-uppercase" style="color: var(--neon-emerald)">Exibir</label>
                        <select name="limit" class="form-control form-control-futuristic" onchange="this.form.submit()">
                            <?php $opts = [5, 10, 20, 30, 50, 'all']; foreach($opts as $o): ?>
                                <option value="<?php echo $o; ?>" <?php echo $limit_get == $o ? 'selected' : ''; ?>><?php echo $o == 'all' ? 'Tudo' : "$o por pág."; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-5 text-right">
                        <button type="submit" class="btn btn-emerald"><i class="fas fa-search mr-1"></i> Pesquisar</button>
                        <a href="./sub_revenda_create.php" class="btn btn-emerald"><i class="fas fa-plus mr-1"></i> Criar</a>
                    </div>
                </div>
            </form>

            <div class="table-responsive">
                <table class="table table-modern">
                    <thead>
                        <tr>
                            <th>Ref. ID</th>
                            <th>Nome</th>
                            <th>Usuario</th>
                            <th>Senha</th>
                            <th>Registro</th>
                            <th>Registrado por</th>
                            <th>MACs</th>
                            <th>Extra</th>
                            <th class="text-center">Editar</th>
                            <th class="text-center">Deletar</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($row1 = $res1->fetchArray()): 
                            $subrevenda_id = $row1['id'];
                            $subrevenda_nome = $row1['nome'];
                            $subrevenda_usuario = $row1['usuario'];
                            $subrevenda_registradoPor = $row1['registrado_por'];
                            $subrevenda_senha = $row1['senha'];
                            $subrevenda_registro = $row1['registro'];
                            $subrevenda_macs = $row1['macs'];
                        ?>
                            <tr>
                                <td><?php echo $row1['id_ref']; ?></td>
                                <td class="font-weight-bold" style="color: #fff;"><?php echo $subrevenda_nome; ?></td>
                                <td><code><?php echo $subrevenda_usuario; ?></code></td>
                                <td><?php echo $subrevenda_senha; ?></td>
                                <td><?php echo date("d/m/Y", strtotime($subrevenda_registro)); ?></td>
                                <td><span class="badge" style="border: 1px solid #444; color: #aaa; background: transparent;"><?php echo $subrevenda_registradoPor; ?></span></td>
                                <td><?php echo $subrevenda_macs; ?></td>
                                <td><small style="opacity: 0.5;"><?php echo $row1['extra']; ?></small></td>
                                <td class="text-center">
                                    <a href="./sub_revenda_update.php?update=<?php echo $subrevenda_id; ?>">
                                        <i class="fas fa-pencil-alt" style="color: var(--neon-emerald); font-size: 1.1rem;"></i>
                                    </a>
                                </td>
                                <td class="text-center">
                                    <a href="#" data-href="./sub_revenda.php?delete=<?php echo $subrevenda_id; ?>" data-toggle="modal" data-target="#confirm-delete">
                                        <i class="fas fa-ban" style="color: #ff4b2b; font-size: 1.1rem;"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($total_pages > 1 && $limit_get !== 'all'): ?>
                <div class="pagination-neon">
                    <?php 
                    $params = "&limit=$limit_get&search=".urlencode($searchTerm);
                    if($page > 1) echo "<a href='?view=".($page-1)."$params' class='page-link-neon'>&laquo; Previous</a>";
                    
                    for($i=1; $i<=$total_pages; $i++) {
                        $active = ($i == $page) ? 'active' : '';
                        echo "<a href='?view=$i$params' class='page-link-neon $active'>$i</a>";
                    }
                    
                    if($page < $total_pages) echo "<a href='?view=".($page+1)."$params' class='page-link-neon'>Next &raquo;</a>";
                    ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content" style="background: #0a0f14; border: 1px solid var(--neon-emerald); color: #fff;">
            <div class="modal-header border-0"><h5 style="font-family: 'Orbitron'; color: var(--neon-emerald);">Confirmar</h5></div>
            <div class="modal-body">Você realmente deseja excluir este Sub Revenda?</div>
            <div class="modal-footer border-0">
                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancelar</button>
                <a class="btn btn-danger btn-sm btn-ok">Deletar</a>
            </div>
        </div>
    </div>
</div>

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

<?php 
include '../includes/footer2.php';
require '../includes/egz2.php';
?>