<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$results_per_page = 50;

// ========== PROCESSAMENTO DE EXCLUSÃO ANTES DE QUALQUER SAÍDA ==========
if (isset($_GET['delete'])) {
    session_start();
    $reseller_name = isset($_SESSION['reseller_name']) ? $_SESSION['reseller_name'] : '';
    if (empty($reseller_name)) {
        header('Location: ../login.php');
        exit();
    }

    $db = new SQLite3('../a/.eggziedb.db');
    $ids_to_delete = explode(',', $_GET['delete']);
    foreach ($ids_to_delete as $id) {
        $id = intval($id);
        $user_info = $db->query("SELECT seller FROM ibo WHERE id = $id");
        if ($user_info) {
            $user_row = $user_info->fetchArray(SQLITE3_ASSOC);
            if ($user_row && $user_row['seller'] == $reseller_name) {
                $db->exec('DELETE FROM ibo WHERE id=' . $id);
            }
        }
    }
    $db->close();
    header('Location: index.php');
    exit();
}
// ========== FIM DO PROCESSAMENTO ==========

include '../includes/header3.php';

if (!isset($db) || !$db) {
    die("Erro: Conexão com banco de dados não disponível.");
}

require_once '../includes/DNSDatabase.php';
$dnsDB = DNSDatabase::getInstance();

$reseller_name = isset($_SESSION['reseller_name']) ? $_SESSION['reseller_name'] : '';

if (empty($reseller_name)) {
    echo "<script>alert('Erro: Sessão não identificada. Faça login novamente.'); window.location.href='../login.php';</script>";
    exit();
}

$table_check = $db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='ibo'");
if (!$table_check || !$table_check->fetchArray()) {
    $db->exec("CREATE TABLE IF NOT EXISTS ibo (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT,
        mac_address TEXT,
        url TEXT,
        seller TEXT,
        title TEXT,
        extra TEXT,
        expire_date TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
}

$table_info = $db->query("PRAGMA table_info(ibo)");
$has_is_test = false;
if ($table_info) {
    while ($col = $table_info->fetchArray(SQLITE3_ASSOC)) {
        if ($col['name'] == 'is_test') { $has_is_test = true; break; }
    }
}
if (!$has_is_test) {
    $db->exec("ALTER TABLE ibo ADD COLUMN is_test INTEGER DEFAULT 0");
}

$searchTerm = isset($_GET['search']) ? $_GET['search'] : '';
$searchQuery = '';
if (!empty($searchTerm)) {
    $searchTerm = $db->escapeString($searchTerm);
    $searchQuery = "AND (mac_address LIKE '%$searchTerm%' OR title LIKE '%$searchTerm%' OR username LIKE '%$searchTerm%')";
}

$count_query = "SELECT COUNT(id) AS total FROM ibo WHERE seller = '$reseller_name' $searchQuery";
$result = $db->query($count_query);
if (!$result) {
    die("Erro na consulta: " . $db->lastErrorMsg());
}
$rownew = $result->fetchArray(SQLITE3_ASSOC);
$totaleview = $rownew ? $rownew['total'] : 0;
$total_pages = $totaleview > 0 ? ceil($totaleview / $results_per_page) : 1;
$page = isset($_GET['view']) ? (int)$_GET['view'] : 1;
$start_from = ($page - 1) * $results_per_page;

$query = "SELECT * FROM ibo WHERE seller = '$reseller_name' $searchQuery ORDER BY id ASC LIMIT $start_from, $results_per_page";
$res1 = $db->query($query);
if (!$res1) {
    die("Erro na consulta de usuários: " . $db->lastErrorMsg());
}
?>

<style>
* {
    box-sizing: border-box;
}
html, body {
    width: 100%;
    overflow-x: hidden;
}
.main-container {
    width: 100%;
    padding: 1.5rem;
}
.content-wrapper {
    width: 100%;
    max-width: 100%;
    margin: 0 auto;
}
.card-container {
    margin-bottom: 1.5rem;
    width: 100%;
}
.card {
    background: white;
    border-left: 4px solid #dc3545;
    border-radius: 0.35rem;
    box-shadow: 0 .15rem 1.75rem 0 rgba(58,59,69,.15);
    width: 100%;
}
.card-header {
    padding: 1rem;
    border-bottom: 1px solid #e3e6f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
}
.card-header h6 {
    margin: 0;
    font-weight: bold;
    color: #dc3545;
}
.card-body {
    padding: 1rem;
}
.search-group {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 1rem;
}
.input-group {
    display: flex;
    flex: 2;
    min-width: 200px;
}
.input-group input {
    flex: 1;
    padding: 0.375rem 0.75rem;
    border: 1px solid #ced4da;
    border-radius: 0.25rem 0 0 0.25rem;
}
.input-group button {
    padding: 0.375rem 0.75rem;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 0 0.25rem 0.25rem 0;
    cursor: pointer;
}
.btn-secondary {
    background: #6c757d;
    color: white;
    padding: 0.375rem 0.75rem;
    text-decoration: none;
    border-radius: 0.25rem;
    display: inline-block;
}
.btn-primary {
    background: #007bff;
    color: white;
    padding: 0.375rem 0.75rem;
    text-decoration: none;
    border-radius: 0.25rem;
    display: inline-block;
}
.btn-danger {
    background: #dc3545;
    color: white;
    padding: 0.25rem 0.5rem;
    border: none;
    border-radius: 0.2rem;
    cursor: pointer;
    font-size: 0.75rem;
}
.btn-sm {
    padding: 0.25rem 0.5rem;
    font-size: 0.75rem;
    line-height: 1.5;
    border-radius: 0.2rem;
    text-decoration: none;
    display: inline-block;
}
.btn-warning {
    background: #ffc107;
    color: #1f2d3d;
}
.btn-warning:hover {
    background: #e0a800;
}
.table-responsive {
    overflow-x: auto;
}
.table {
    width: 100%;
    border-collapse: collapse;
}
.table th {
    background-color: rgba(255, 255, 255, 0.9);
    color: #007bff;
    font-weight: bold;
    padding: 0.75rem;
    border-bottom: 2px solid #dee2e6;
    text-align: left;
    white-space: nowrap;
}
.table td {
    padding: 0.75rem;
    border-top: 1px solid #dee2e6;
    color: #000000;
    white-space: nowrap;
}
.table-striped tbody tr:nth-child(odd) {
    background-color: rgba(0, 123, 255, 0.1);
}
.table-striped tbody tr:nth-child(even) {
    background-color: rgba(0, 0, 0, 0.05);
}
.table-striped tbody tr:hover {
    background-color: rgba(0, 123, 255, 0.2);
}
.text-center {
    text-align: center;
}
.pagination {
    margin-top: 1rem;
    text-align: center;
}
.pagination-gap {
    margin: 2px;
    background: #28a745;
    color: white;
    padding: 5px 10px;
    display: inline-block;
    border-radius: 4px;
    text-decoration: none;
}
.pagination-red {
    margin: 2px;
    background: #007bff;
    color: white;
    padding: 5px 10px;
    display: inline-block;
    border-radius: 4px;
    text-decoration: none;
}
.badge-test {
    background: #ffc107;
    color: #1f2d3d;
    padding: 3px 8px;
    border-radius: 4px;
    font-size: 11px;
    display: inline-block;
}
.badge-annual {
    background: #28a745;
    color: white;
    padding: 3px 8px;
    border-radius: 4px;
    font-size: 11px;
    display: inline-block;
}
.badge-expired {
    background: #dc3545;
    color: white;
    padding: 3px 8px;
    border-radius: 4px;
    font-size: 11px;
    display: inline-block;
}
.btn-action {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    border-radius: 6px;
    transition: all 0.2s ease;
    text-decoration: none;
    font-size: 1rem;
}
.btn-edit {
    background-color: #ffc107;
    color: #1f2d3d;
}
.btn-edit:hover {
    background-color: #e0a800;
    transform: scale(1.05);
    box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}
.btn-delete {
    background-color: #dc3545;
    color: white;
}
.btn-delete:hover {
    background-color: #c82333;
    transform: scale(1.05);
    box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}
.table td {
    font-weight: bold;
    color: #000000;
}
</style>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        window.toggleSelectAll = function(sourceCheckbox) {
            let checkboxes = document.querySelectorAll("input[name='delete_check[]']");
            checkboxes.forEach(cb => cb.checked = sourceCheckbox.checked);
        };

        document.getElementById("excluirSelecionados")?.addEventListener("click", function() {
            let ids = [];
            document.querySelectorAll("input[name='delete_check[]']:checked").forEach(cb => ids.push(cb.value));
            if(ids.length) {
                if(confirm("Tem certeza de que deseja excluir os itens selecionados?\n\nATENÇÃO: Usuários anuais NÃO DEVOLVEM MACs ao serem excluídos!"))
                    window.location.href = 'index.php?delete=' + ids.join(',');
            } else alert("Selecione pelo menos um item.");
        });

        window.SetModalFun = function(id) {
            document.getElementById('deletar_modal').href = 'index.php?delete=' + id;
        }
    });
</script>

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h2>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" id="deletar_modal">Deletar</a>
            </div>
        </div>
    </div>
</div>

<div class="main-container">
    <div class="content-wrapper">
        <div class="card-container">
            <div class="card">
                <div class="card-header">
                    <h6><i class="fas fa-fw fa-user-plus"></i> Usuários - Sub Revenda</h6>
                    <button type="button" id="excluirSelecionados" class="btn-danger">
                        <i class="fas fa-trash"></i> Excluir Selecionados
                    </button>
                </div>
                <div class="card-body">
                    <div class="search-group">
                        <form method="get" style="flex:2; margin:0;">
                            <div class="input-group">
                                <input type="text" name="search" placeholder="Pesquise por MAC, Título, Username..." value="<?php echo htmlspecialchars($searchTerm); ?>">
                                <button type="submit"><i class="fas fa-search"></i> Pesquisar</button>
                            </div>
                        </form>
                        <?php if(!empty($searchTerm)): ?>
                            <a href="index.php" class="btn-secondary"><i class="fas fa-times"></i> Limpar</a>
                        <?php endif; ?>
                    </div>
                    <div style="margin-bottom:1rem;">
                        <a href="./users_create.php" class="btn-primary"><i class="fas fa-plus"></i> Criar</a>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th style="width:30px;"><input type="checkbox" onclick="toggleSelectAll(this)"></th>
                                    <th>SERVIDOR</th>
                                    <th>CLIENTE</th>
                                    <th>DNS</th>
                                    <th>USUÁRIO</th>
                                    <th>TIPO</th>
                                    <th>VALIDADE</th>
                                    <th>MAC ADDRESS</th>
                                    <th style="width:60px;">EDITAR</th>
                                    <th style="width:60px;">EXCLUIR</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $total_registros = 0;
                                while($row = $res1->fetchArray(SQLITE3_ASSOC)) {
                                    $total_registros++;
                                    $id = $row['id'];
                                    $title = htmlspecialchars($row['title']);
                                    $extra = htmlspecialchars($row['extra']);
                                    $username = htmlspecialchars($row['username']);
                                    $mac = htmlspecialchars($row['mac_address']);
                                    $expire = $row['expire_date'];
                                    $url = $row['url'];
                                    $is_test = isset($row['is_test']) ? $row['is_test'] : 0;
                                    $expired = strtotime($expire) < time();
                                    $dns_info = $dnsDB->getByDns($url, 'sub_revenda', $reseller_name);
                                    $dns_display = $dns_info ? htmlspecialchars($dns_info['nome']) : htmlspecialchars($url);
                                ?>
                                <tr>
                                    <td class="text-center"><input type="checkbox" name="delete_check[]" value="<?php echo $id; ?>"></td>
                                    <td><?php echo $title; ?></td>
                                    <td><?php echo $extra; ?></td>
                                    <td><?php echo $dns_display; ?></td>
                                    <td><?php echo $username; ?></td>
                                    <td>
                                        <?php if($is_test) echo '<span class="badge-test"><i class="fas fa-flask"></i> TESTE</span>';
                                        elseif($expired) echo '<span class="badge-expired"><i class="fas fa-hourglass-end"></i> EXPIRADO</span>';
                                        else echo '<span class="badge-annual"><i class="fas fa-calendar-check"></i> ANUAL</span>'; ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($expire); if(!$expired && !$is_test) echo ' <small class="text-success">(Ativo)</small>'; elseif($expired) echo ' <small class="text-danger">(Expirado)</small>'; ?></td>
                                    <td><?php echo $mac; ?></td>
                                    <td class="text-center"><a class="btn-action btn-edit" href="./users_update.php?update=<?php echo $id; ?>" title="Editar"><i class="fas fa-edit"></i></a></td>
                                    <td class="text-center"><a class="btn-action btn-delete delete-btn" href="#" onclick="SetModalFun('<?php echo $id;?>');" data-toggle="modal" data-target="#confirm-delete" title="Excluir"><i class="fas fa-trash-alt"></i></a></td>
                                </tr>
                                <?php } ?>
                                <?php if($total_registros==0): ?>
                                <tr>
                                    <td colspan="10" class="text-center">Nenhum usuário encontrado</td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php if($results_per_page < $totaleview): ?>
                    <div class="pagination">
                        <?php if($page>1): ?><a class="pagination-gap" href='index.php?view=<?php echo ($page-1); ?>&search=<?php echo urlencode($searchTerm); ?>'>&lt; Previous</a><?php endif; ?>
                        <?php for($i=1;$i<=$total_pages;$i++): ?>
                            <a class="<?php echo $i==$page?'pagination-red':'pagination-gap'; ?>" href='index.php?view=<?php echo $i; ?>&search=<?php echo urlencode($searchTerm); ?>'><?php echo $i; ?></a>
                        <?php endfor; ?>
                        <?php if($page<$total_pages): ?><a class="pagination-gap" href='index.php?view=<?php echo ($page+1); ?>&search=<?php echo urlencode($searchTerm); ?>'>Next &gt;</a><?php endif; ?>
                    </div>
                    <?php endif; ?>
                    <?php include '../includes/footer3.php'; ?>
                </div>
            </div>
        </div>
    </div>
</div>