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

/* =========================================================
   DELETE + REDIRECT (PRECISA RODAR ANTES DE QUALQUER HTML)
========================================================= */
if (isset($_GET['delete'])) {
    $limit_tmp  = isset($_GET['limit']) ? $_GET['limit'] : 5;
    $search_tmp = isset($_GET['search']) ? $_GET['search'] : '';
    $view_tmp   = isset($_GET['view']) ? (int)$_GET['view'] : 1;

    $db_del = new SQLite3('../a/.eggziedb.db');
    $db_del->exec('DELETE FROM ibo WHERE id=' . (int)$_GET['delete']);
    $db_del->close();

    // volta para a listagem principal (mesmo arquivo) mantendo estado
    $redirect = 'index.php?limit=' . urlencode($limit_tmp) .
                '&search=' . urlencode($search_tmp) .
                '&view=' . (int)$view_tmp;

    header('Location: ' . $redirect);
    exit;
}

/* =========================================================
   PAGINAÇÃO / LISTAGEM
========================================================= */

// Captura a quantidade por página. Se for 'all', usamos um número gigante.
$limit_get = isset($_GET['limit']) ? $_GET['limit'] : 5;
$results_per_page = ($limit_get === 'all') ? 999999 : (int)$limit_get;

// (importante: o header só entra depois do delete/redirect)
include '../includes/header3.php';

error_reporting(0);

if (isset($_GET['view'])) {
    $page = (int)$_GET['view'];
} else {
    if($_SESSION['aviso_reseller'] == 0) {    
        $page = 1;
        $file_path = '../a/revenda_mensagem.json';
        $file_content = file_get_contents($file_path);
        $data_array = json_decode($file_content, true);
        $titulo = $data_array['title'];
        $mensagem = $data_array['content'];
        $_SESSION['aviso_reseller'] = 1;
    } else {
        $page = 1;
    }
}

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

// Funcionalidade de Pesquisa
$searchTerm = isset($_GET['search']) ? $_GET['search'] : '';
$searchQuery = "WHERE seller = '$seller_name'";
if (!empty($searchTerm)) {
    $searchQuery = "WHERE (mac_address LIKE '%$searchTerm%' OR title LIKE '%$searchTerm%' OR username LIKE '%$searchTerm%') AND seller = '$seller_name'";
}

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

$res1 = $db1->query("SELECT * FROM ibo $searchQuery ORDER BY id ASC LIMIT $start_from, $results_per_page");
?>

<style>
/* =========================================================
   TEMA CYBERPUNK DA PÁGINA (somente visual)
========================================================= */
:root{
  --cp-bg: rgba(255,255,255,.06);
  --cp-stroke: rgba(255,255,255,.14);
  --cp-stroke2: rgba(255,255,255,.10);
  --cp-text: rgba(255,255,255,.92);
  --cp-muted: rgba(255,255,255,.68);
  --cp-shadow: 0 18px 60px rgba(0,0,0,.55);
}

/* área principal: tira cara “cinza” */
#content-wrapper,
#content{
  background: transparent !important;
}

/* container padding mais elegante no SB Admin */
main.col-15.pt-4.px-5{
  padding-top: 1.25rem !important;
}

/* ===== Card (caixa principal) ===== */
.card{
  background: linear-gradient(180deg, rgba(255,255,255,.10), rgba(255,255,255,.04)) !important;
  border: 1px solid var(--cp-stroke) !important;
  border-radius: 18px !important;
  backdrop-filter: blur(16px);
  -webkit-backdrop-filter: blur(16px);
  box-shadow: var(--cp-shadow) !important;
  overflow: hidden;
}

.card.border-left-primary{
  border-left: 3px solid rgba(0,242,255,.55) !important;
}

.card-header{
  background: linear-gradient(90deg, rgba(0,242,255,.10), rgba(188,19,254,.06), rgba(255,43,214,.05)) !important;
  border-bottom: 1px solid rgba(255,255,255,.10) !important;
}

.text-primary2{
  color: rgba(0,242,255,.92) !important;
  font-family: 'Orbitron', sans-serif;
  letter-spacing: .06em;
  text-shadow: 0 0 14px rgba(0,242,255,.22);
}

/* ===== Formulário (inputs/select) ===== */
.form-control,
.input-group-text,
.custom-select,
select.form-control{
  background: rgba(0,0,0,.30) !important;
  border: 1px solid rgba(255,255,255,.14) !important;
  color: var(--cp-text) !important;
  border-radius: 14px !important;
  box-shadow: none !important;
}

.form-control::placeholder{
  color: rgba(255,255,255,.45) !important;
}

.input-group .form-control{
  border-top-right-radius: 0 !important;
  border-bottom-right-radius: 0 !important;
}
.input-group-append .btn{
  border-top-left-radius: 0 !important;
  border-bottom-left-radius: 0 !important;
}

/* ===== Botões ===== */
.btn{
  border-radius: 999px !important;
  font-weight: 800 !important;
  letter-spacing: .06em;
  text-transform: uppercase;
  font-family: 'Orbitron', sans-serif;
}

.btn-primary{
  background: rgba(0,242,255,.10) !important;
  border: 1px solid rgba(0,242,255,.35) !important;
  color: rgba(255,255,255,.92) !important;
  box-shadow: 0 0 22px rgba(0,242,255,.12) !important;
}

.btn-primary:hover{
  background: rgba(0,242,255,.16) !important;
  box-shadow: 0 0 34px rgba(0,242,255,.18) !important;
  transform: translateY(-1px);
}

.btn-danger{
  background: rgba(255,75,43,.10) !important;
  border: 1px solid rgba(255,75,43,.55) !important;
  color: rgba(255,255,255,.92) !important;
}

.btn-warning{
  background: rgba(188,19,254,.10) !important;
  border: 1px solid rgba(188,19,254,.40) !important;
  color: rgba(255,255,255,.92) !important;
}

/* ===== Tabela ===== */
.table-responsive{
  border-radius: 16px;
  overflow: hidden;
  border: 1px solid rgba(255,255,255,.10);
}

.table{
  margin-bottom: 0 !important;
  color: rgba(255,255,255,.88) !important;
}

.table thead{
  background: rgba(0,0,0,.35) !important;
}
.table thead th{
  color: rgba(0,242,255,.90) !important;
  border-bottom: 1px solid rgba(255,255,255,.10) !important;
  font-family: 'Orbitron', sans-serif;
  letter-spacing: .06em;
  text-transform: uppercase;
  font-size: 12px;
}

.table-striped tbody tr:nth-of-type(odd){
  background: rgba(255,255,255,.03) !important;
}

.table tbody td{
  border-top: 1px solid rgba(255,255,255,.08) !important;
  vertical-align: middle !important;
}

.table tbody tr:hover{
  background: rgba(0,242,255,.07) !important;
}

/* ===== Ícones editar/deletar ===== */
.table a{
  text-decoration: none !important;
}

.table .fa-pencil-square{
  color: rgba(0,242,255,.92) !important;
  text-shadow: 0 0 14px rgba(0,242,255,.25);
  transition: transform .15s ease, filter .15s ease;
}
.table .fa-ban{
  color: rgba(255,75,43,.92) !important;
  text-shadow: 0 0 14px rgba(255,75,43,.25);
  transition: transform .15s ease, filter .15s ease;
}
.table .fa-pencil-square:hover,
.table .fa-ban:hover{
  transform: translateY(-1px) scale(1.06);
  filter: saturate(1.2);
}

/* ===== Paginação ===== */
.pagination-container{
  margin-top: 18px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.pagination-gap,
.pagination-red{
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 38px;
  padding: 0 14px;
  border-radius: 999px;
  text-decoration: none;
  font-family: 'Orbitron', sans-serif;
  letter-spacing: .06em;
  text-transform: uppercase;
  font-size: 12px;
  user-select: none;
}

.pagination-gap{
  background: rgba(0,0,0,.28);
  border: 1px solid rgba(255,255,255,.14);
  color: rgba(255,255,255,.86);
  box-shadow: 0 0 18px rgba(0,242,255,.06);
}

.pagination-gap:hover{
  background: rgba(0,242,255,.10);
  border-color: rgba(0,242,255,.28);
  color: rgba(255,255,255,.95);
}

.pagination-red{
  background: rgba(188,19,254,.12);
  border: 1px solid rgba(188,19,254,.45);
  color: rgba(255,255,255,.95);
  box-shadow: 0 0 22px rgba(188,19,254,.14);
}

/* ===== Modais ===== */
.modal-content{
  background: linear-gradient(180deg, rgba(255,255,255,.12), rgba(255,255,255,.04)) !important;
  border: 1px solid rgba(0,242,255,.22) !important;
  border-radius: 18px !important;
  color: rgba(255,255,255,.92) !important;
  backdrop-filter: blur(18px);
  -webkit-backdrop-filter: blur(18px);
  box-shadow: 0 18px 70px rgba(0,0,0,.65) !important;
}

.modal-header{
  border-bottom: 1px solid rgba(255,255,255,.10) !important;
  font-family: 'Orbitron', sans-serif;
  letter-spacing: .06em;
  text-transform: uppercase;
}

.modal-body{
  color: rgba(255,255,255,.88) !important;
  font-size: 14px;
  line-height: 1.4;
}

/* Backdrop menos agressivo + níveis corretos */
.modal{ z-index: 99999 !important; }
.modal-backdrop{ z-index: 99990 !important; }
.modal-backdrop.show{ opacity: .45 !important; }

/* Limita largura do modal */
.modal-dialog{ max-width: 560px; }
</style>

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

<!-- Modal confirmar delete -->
<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 style="margin:0;font-size:18px;">Confirmar</h2></div>
            <div class="modal-body">Você realmente deseja excluir este usuário?</div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
                <a class="btn btn-danger btn-ok">Deletar</a>
            </div>
        </div>
    </div>
</div>

<?php if(isset($titulo)): ?>
    <div class="modal fade vertical" id="mensagem_revenda" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header"><h2 style="margin:0;font-size:18px;"><?php echo $titulo; ?></h2></div>
                <div class="modal-body"><?php echo $mensagem; ?></div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-warning" data-dismiss="modal">Fechar</button>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>

<main role="main" class="col-15 pt-4 px-5">
    <div id="main">
        <div class="row">
            <div class="col-lg-12">
                <div class="card border-left-primary shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary2">
                          <i class="fas fa-fw fa-user-plus"></i> Usuários
                        </h6>
                    </div>
                    <div class="card-body">
                        
                        <form method="get" class="mb-4">
                            <div class="row">
                                <div class="col-md-7">
                                    <div class="input-group">
                                        <input type="text" name="search" class="form-control" placeholder="Pesquise por MAC, Servidor, Usuário...." value="<?php echo htmlspecialchars($searchTerm); ?>">
                                        <div class="input-group-append">
                                            <button type="submit" class="btn btn-primary">Pesquisar</button>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text">Exibir:</span>
                                        </div>
                                        <select name="limit" class="form-control" onchange="this.form.submit()">
                                            <?php
                                            $options = [5, 10, 20, 30, 50, 100];
                                            foreach ($options as $opt) {
                                                $selected = ($limit_get == $opt) ? 'selected' : '';
                                                echo "<option value='$opt' $selected>$opt</option>";
                                            }
                                            echo "<option value='all' " . ($limit_get === 'all' ? 'selected' : '') . ">Tudo</option>";
                                            ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-2 text-right">
                                    <a href="./users_create.php" class="btn btn-primary btn-block">
                                        <i class="fas fa-plus"></i> Criar
                                    </a>
                                </div>
                            </div>
                        </form>

                        <div class="table-responsive">
                            <table class="table table-striped table-sm">
                                <thead class="text-primary">
                                    <tr>
                                        <th>Servidor</th>
                                        <th>Endereço Mac</th>
                                        <th>Usuário</th>
                                        <th>Vendedor</th>
                                        <th>Validade</th>
                                        <th>DNS</th>
                                        <th>Extra</th>
                                        <th>Editar</th>
                                        <th>Deletar</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($row1 = $res1->fetchArray()): ?>
                                        <tr>
                                            <td><?php echo $row1['title']; ?></td>
                                            <td><?php echo $row1['mac_address']; ?></td>
                                            <td><?php echo $row1['username']; ?></td>
                                            <td><?php echo $row1['seller']; ?></td>
                                            <td><?php echo date('d/m/Y', strtotime($row1['expire_date'])); ?></td>
                                            <td><?php echo $row1['url']; ?></td>
                                            <td><?php echo $row1['extra']; ?></td>
                                            <td>
                                                <a href="./users_update.php?update=<?php echo $row1['id']; ?>">
                                                    <i class="fa fa-pencil-square" style="font-size:24px;"></i>
                                                </a>
                                            </td>
                                            <td>
                                                <a class="delete-btn"
                                                   href="#"
                                                   data-href="index.php?delete=<?php echo $row1['id']; ?>&limit=<?php echo urlencode($limit_get); ?>&search=<?php echo urlencode($searchTerm); ?>&view=<?php echo (int)$page; ?>"
                                                   data-toggle="modal"
                                                   data-target="#confirm-delete">
                                                    <i class="fa fa-ban" style="font-size:24px;"></i>
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>

                        <?php if ($total_pages > 1 && $limit_get !== 'all'): ?>
                        <div class="pagination-container">
                            <?php 
                                $base_url = "index.php?limit=$limit_get&search=" . urlencode($searchTerm);
                            ?>
                            
                            <?php if ($page > 1): ?>
                                <a class="pagination-gap" href='<?php echo $base_url; ?>&view=<?php echo ($page - 1); ?>'>&lt; Anterior</a>
                            <?php endif; ?>

                            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                <?php if ($i == $page): ?>
                                    <a class="active pagination-red" href='#'><?php echo $i; ?></a>
                                <?php else: ?>
                                    <a class="pagination-gap" href='<?php echo $base_url; ?>&view=<?php echo $i; ?>'><?php echo $i; ?></a>
                                <?php endif; ?>
                            <?php endfor; ?>

                            <?php if ($page < $total_pages): ?>
                                <a class="pagination-gap" href='<?php echo $base_url; ?>&view=<?php echo ($page + 1); ?>'>Próximo &gt;</a>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>

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

<?php
include '../includes/footer3.php';
require '../includes/egz3.php';

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