<?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 = '';
include '../includes/header2.php';

// CORREÇÃO: Query SQL corrigida com parênteses
if (!empty($searchTerm)) {
    $searchQuery = "WHERE (nome LIKE '%$searchTerm%' OR usuario LIKE '%$searchTerm%') AND registrado_por = '$seller_name'";
} else {
    $searchQuery = "WHERE registrado_por = '$seller_name'";
}

$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'");
}
?>

<style>
/* === DESIGN FUTURISTA PARA SUB REVENDAS === */
:root {
    --primary: #FF6B9D;
    --primary-dark: #D94A7E;
    --secondary: #00D4FF;
    --accent: #FFD166;
    --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(255, 107, 157, 0.3);
    --glow-accent: 0 0 20px rgba(255, 209, 102, 0.3);
}

.card {
    background: var(--surface-light) !important;
    border: 1px solid var(--border) !important;
    border-radius: 16px !important;
    box-shadow: var(--glow) !important;
    backdrop-filter: blur(10px);
}

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

.text-primary2 {
    color: var(--text-primary) !important;
    font-weight: 600;
    font-size: 1.2rem;
    display: flex;
    align-items: center;
    gap: 12px;
}

.text-primary2 i {
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

/* === FORMULÁRIOS FUTURISTAS === */
.form-control {
    background: var(--surface-lighter) !important;
    border: 1px solid var(--border) !important;
    border-radius: 12px !important;
    color: var(--text-primary) !important;
    padding: 12px 16px;
    transition: all 0.3s ease;
}

.form-control:focus {
    background: var(--surface-lighter) !important;
    border-color: var(--primary) !important;
    box-shadow: 0 0 0 0.2rem rgba(255, 107, 157, 0.25) !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;
    padding: 12px 24px;
    font-weight: 600;
    transition: all 0.3s ease;
    box-shadow: var(--glow);
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 0 30px rgba(255, 107, 157, 0.5);
}

.btn-icon-split {
    background: linear-gradient(135deg, var(--secondary), var(--primary-dark)) !important;
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s ease;
    box-shadow: var(--glow);
}

.btn-icon-split:hover {
    transform: translateY(-2px);
    box-shadow: 0 0 30px rgba(0, 212, 255, 0.5);
}

/* === TABELA FUTURISTA === */
.table-responsive {
    border-radius: 12px;
    overflow: hidden;
}

.table {
    background: var(--surface-lighter) !important;
    border-radius: 12px;
    margin-bottom: 0;
}

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

.table thead th {
    border-bottom: 2px solid var(--primary) !important;
    color: var(--text-primary) !important;
    font-weight: 600;
    padding: 16px 12px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    font-size: 0.9rem;
}

.table tbody tr {
    background: var(--surface-lighter);
    transition: all 0.3s ease;
    border-bottom: 1px solid var(--border);
}

.table tbody tr:hover {
    background: rgba(255, 107, 157, 0.1);
    transform: translateX(4px);
}

.table tbody td {
    color: var(--text-secondary) !important;
    padding: 14px 12px;
    border-color: var(--border) !important;
    vertical-align: middle;
}

/* === BOTÕES DE AÇÃO === */
.btn-icon {
    background: transparent;
    border: none;
    border-radius: 8px;
    padding: 8px;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.btn-icon:hover {
    background: rgba(255, 255, 255, 0.1);
    transform: scale(1.1);
}

/* === PAGINAÇÃO FUTURISTA === */
.pagination {
    display: flex;
    gap: 8px;
    justify-content: center;
    align-items: center;
    margin-top: 24px;
    flex-wrap: wrap;
}

.pagination-gap {
    background: var(--surface-lighter) !important;
    border: 1px solid var(--border) !important;
    color: var(--text-secondary) !important;
    padding: 10px 16px;
    border-radius: 10px;
    text-decoration: none;
    transition: all 0.3s ease;
    font-weight: 500;
    min-width: 44px;
    text-align: center;
}

.pagination-gap:hover {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark)) !important;
    color: var(--text-primary) !important;
    transform: translateY(-2px);
    box-shadow: var(--glow);
}

.pagination-red {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark)) !important;
    color: var(--text-primary) !important;
    border: none !important;
    padding: 10px 16px;
    border-radius: 10px;
    text-decoration: none;
    font-weight: 600;
    min-width: 44px;
    text-align: center;
    box-shadow: var(--glow);
}

/* === MODAIS FUTURISTAS === */
.modal-content {
    background: var(--surface-light) !important;
    border: 1px solid var(--border) !important;
    border-radius: 16px !important;
    box-shadow: var(--glow) !important;
    backdrop-filter: blur(20px);
}

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

.modal-body {
    color: var(--text-secondary) !important;
    padding: 24px !important;
}

.modal-footer {
    border-top: 1px solid var(--border) !important;
    padding: 20px !important;
}

.btn-default {
    background: var(--surface-lighter) !important;
    border: 1px solid var(--border) !important;
    color: var(--text-primary) !important;
    border-radius: 10px;
    padding: 10px 20px;
    transition: all 0.3s ease;
}

.btn-default:hover {
    background: var(--surface) !important;
    transform: translateY(-1px);
}

.btn-danger {
    background: linear-gradient(135deg, #FF4757, #FF3742) !important;
    border: none !important;
    border-radius: 10px;
    padding: 10px 20px;
    color: white !important;
    font-weight: 600;
    transition: all 0.3s ease;
}

.btn-danger:hover {
    transform: translateY(-2px);
    box-shadow: 0 0 20px rgba(255, 71, 87, 0.4);
}

/* === BADGES E STATUS === */
.mac-badge {
    background: linear-gradient(135deg, var(--accent), var(--primary));
    color: var(--surface);
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.ref-id-badge {
    background: linear-gradient(135deg, var(--secondary), var(--primary-dark));
    color: var(--surface);
    padding: 4px 10px;
    border-radius: 8px;
    font-family: 'Courier New', monospace;
    font-weight: 600;
    font-size: 0.85rem;
}

/* === RESPONSIVIDADE === */
@media (max-width: 768px) {
    .table-responsive {
        border-radius: 8px;
    }
    
    .table thead th {
        padding: 12px 8px;
        font-size: 0.8rem;
    }
    
    .table tbody td {
        padding: 10px 8px;
        font-size: 0.9rem;
    }
    
    .pagination {
        gap: 4px;
    }
    
    .pagination-gap,
    .pagination-red {
        padding: 8px 12px;
        font-size: 0.9rem;
        min-width: 36px;
    }
    
    .card-body {
        padding: 16px !important;
    }
}

/* === ANIMAÇÕES === */
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
}

.card {
    animation: fadeIn 0.6s ease-out;
}

.table tbody tr {
    animation: fadeIn 0.4s ease-out;
}

/* === HEADER STYLES === */
.h3 {
    color: var(--text-primary) !important;
    font-weight: 700;
    margin-bottom: 24px;
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

/* === CONTADOR DE MACS DO REVENDEDOR === */
.seller-mac-counter {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    color: var(--text-primary);
    padding: 12px 20px;
    border-radius: 12px;
    margin-bottom: 20px;
    text-align: center;
    box-shadow: var(--glow);
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 8px;
}

.seller-mac-counter i {
    font-size: 1.1rem;
}
</style>

<!-- Modal de Confirmação de Exclusão -->
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">Confirmar Exclusão</h2>
            </div>
            <div class="modal-body">
                <i class="fas fa-exclamation-triangle" style="color: var(--accent); font-size: 2rem; margin-bottom: 16px;"></i>
                <p>Você realmente deseja excluir este Sub Revendedor?</p>
                <p class="text-muted" style="font-size: 0.9rem; color: var(--text-muted);">
                    <strong>Atenção:</strong> Esta ação não pode ser desfeita e removerá todos os dados associados.
                </p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">
                    <i class="fas fa-times"></i> Cancelar
                </button>
                <a class="btn btn-danger btn-ok">
                    <i class="fas fa-trash"></i> Deletar
                </a>
            </div>
        </div>
    </div>
</div>

<main role="main" class="col-15 pt-4 px-5">
    <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">
            <div style="position:absolute; width:1000000px; height:1000000px; left:0; top:0"></div>
        </div>
        <div class="chartjs-size-monitor-shrink">
            <div style="position:absolute; width:200%; height:200%; left:0; top:0"></div>
        </div>
    </div>
    
    <div id="main">
        <!-- Content Row -->
        <div class="row">
            <div class="col-lg-12">
                <!-- Contador de MACs do Revendedor -->
                <?php
                // Buscar MACs disponíveis do revendedor atual
                $macsResult = $db1->query("SELECT macs FROM revenda WHERE usuario = '$seller_name'");
                $macsRow = $macsResult->fetchArray();
                $availableMacs = $macsRow ? $macsRow['macs'] : 0;
                ?>
                <div class="seller-mac-counter">
                    <i class="fas fa-coins"></i>
                    Seus MACs Disponíveis: <strong><?php echo $availableMacs; ?></strong>
                </div>

                <!-- Card de Sub Revendas -->
                <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-network-wired"></i> Gerenciar Sub Revendas
                        </h6>
                    </div>
                    <div class="card-body">
                        <!-- Barra 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ão Criar -->
                        <div class="form-group mb-4">
                            <a href="./sub_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 Nova Sub Revenda</span>
                            </a>
                        </div>

                        <!-- Tabela de Sub Revendas -->
                        <div class="table-responsive">
                            <table class="table table-striped table-sm">
                                <thead class="text-primary">
                                    <tr>
                                        <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>Ações</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $res1->reset(); // Reset do resultado para iterar novamente
                                    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>
                                                <span class="ref-id-badge"><?php echo $row1['id_ref']; ?></span>
                                            </td>
                                            <td><strong><?php echo htmlspecialchars($subrevenda_nome); ?></strong></td>
                                            <td><code><?php echo htmlspecialchars($subrevenda_usuario); ?></code></td>
                                            <td><?php echo htmlspecialchars($subrevenda_senha); ?></td>
                                            <td><?php echo htmlspecialchars($subrevenda_registro); ?></td>
                                            <td><?php echo htmlspecialchars($subrevenda_registradoPor); ?></td>
                                            <td>
                                                <span class="mac-badge"><?php echo $subrevenda_macs; ?> MACs</span>
                                            </td>
                                            <td><?php echo htmlspecialchars($row1['extra']); ?></td>
                                            <td>
                                                <div class="btn-group" role="group">
                                                    <a class="btn btn-icon" href="./sub_revenda_update.php?update=<?php echo $subrevenda_id; ?>" title="Editar">
                                                        <i class="fa fa-pencil-square" style="font-size:20px;color:var(--secondary);"></i>
                                                    </a>
                                                    <a class="btn btn-icon delete-btn" href="#" 
                                                       data-href="./sub_revenda.php?delete=<?php echo $subrevenda_id; ?>" 
                                                       data-toggle="modal" data-target="#confirm-delete" title="Excluir">
                                                        <i class="fa fa-trash" style="font-size:20px;color:#FF4757;"></i>
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Paginação -->
                        <?php if ($results_per_page < $totaleview): ?>
                            <div class="pagination">
                                <?php if ($page > 1): ?>
                                    <a class="pagination-gap" href='sub_revenda.php?view=<?php echo ($page - 1); echo !empty($searchTerm) ? "&search=" . urlencode($searchTerm) : ""; ?>'>
                                        <i class="fas fa-chevron-left"></i> Anterior
                                    </a>
                                <?php endif; ?>
                                
                                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                    <?php if ($i == $page): ?>
                                        <a class="pagination-red" href='sub_revenda.php?view=<?php echo $i; echo !empty($searchTerm) ? "&search=" . urlencode($searchTerm) : ""; ?>'>
                                            <?php echo $i; ?>
                                        </a>
                                    <?php else: ?>
                                        <a class="pagination-gap" href='sub_revenda.php?view=<?php echo $i; echo !empty($searchTerm) ? "&search=" . urlencode($searchTerm) : ""; ?>'>
                                            <?php echo $i; ?>
                                        </a>
                                    <?php endif; ?>
                                <?php endfor; ?>
                                
                                <?php if ($page < $total_pages): ?>
                                    <a class="pagination-gap" href='sub_revenda.php?view=<?php echo ($page + 1); echo !empty($searchTerm) ? "&search=" . urlencode($searchTerm) : ""; ?>'>
                                        Próximo <i class="fas fa-chevron-right"></i>
                                    </a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<script>
// Script para o modal de confirmação de exclusão
$(document).ready(function() {
    $('#confirm-delete').on('show.bs.modal', function(e) {
        $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
    });
});

// Efeitos de hover nas linhas da tabela
document.addEventListener('DOMContentLoaded', function() {
    const tableRows = document.querySelectorAll('.table tbody tr');
    tableRows.forEach((row, index) => {
        row.style.animationDelay = `${index * 0.1}s`;
    });
});
</script>

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