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

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

$owner_type = 'sub_revenda';
$owner_name = $reseller_name;

$dnsDB = DNSDatabase::getInstance();

// Processar formulário (criar/editar)
if (isset($_POST['submit'])) {
    $nome = trim($_POST['nome']);
    $dns = trim($_POST['dns']);
    if (empty($nome) || empty($dns)) {
        echo "<script>alert('Por favor, preencha todos os campos!');</script>";
    } else {
        if (isset($_POST['id']) && !empty($_POST['id'])) {
            $result = $dnsDB->update($_POST['id'], $nome, $dns, $owner_type, $owner_name);
            $message = $result ? "DNS atualizada!" : "Erro ao atualizar!";
        } else {
            $result = $dnsDB->create($nome, $dns, $owner_type, $owner_name);
            $message = $result ? "DNS criada!" : "Erro ao criar!";
        }
        echo "<script>alert('$message'); window.location.href='dns_manager.php';</script>";
        exit();
    }
}

// Excluir DNS
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $result = $dnsDB->delete($id, $owner_type, $owner_name);
    $message = $result ? "DNS excluída!" : "Erro ao excluir!";
    echo "<script>alert('$message'); window.location.href='dns_manager.php';</script>";
    exit();
}

$edit_dns = null;
$show_form = false;
if (isset($_GET['edit'])) {
    $edit_dns = $dnsDB->getById($_GET['edit'], $owner_type, $owner_name);
    if ($edit_dns) $show_form = true;
}

// Paginação e busca
$results_per_page = 50;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start_from = ($page - 1) * $results_per_page;
$searchTerm = isset($_GET['search']) ? $_GET['search'] : '';

$all_dns = [];
$dns_list_raw = $dnsDB->getAll($owner_type, $owner_name);
if ($dns_list_raw) {
    while ($row = $dns_list_raw->fetchArray(SQLITE3_ASSOC)) {
        $all_dns[] = $row;
    }
}

$filtered_dns = [];
foreach ($all_dns as $dns) {
    if (empty($searchTerm) || stripos($dns['nome'], $searchTerm) !== false || stripos($dns['dns'], $searchTerm) !== false) {
        $filtered_dns[] = $dns;
    }
}
$total_dns = count($filtered_dns);
$total_pages = ceil($total_dns / $results_per_page);
$dns_paginated = array_slice($filtered_dns, $start_from, $results_per_page);

// Contar usuários conectados a cada DNS (apenas usuários desta sub revenda)
$db_ibo = new SQLite3('../a/.eggziedb.db');
foreach ($dns_paginated as &$dns) {
    $url = $dns['dns'];
    $count_query = "SELECT COUNT(*) as total FROM ibo WHERE url = '$url' AND seller = '$owner_name'";
    $result = $db_ibo->query($count_query);
    $row = $result->fetchArray(SQLITE3_ASSOC);
    $dns['users_count'] = $row['total'];
}
unset($dns);
$db_ibo->close();
?>

<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;
}
.btn-danger-sm {
    background: #dc3545;
    color: white;
    padding: 0.25rem 0.5rem;
    border-radius: 0.2rem;
    text-decoration: none;
    display: inline-block;
    font-size: 0.75rem;
}
.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-users {
    background: #17a2b8;
    color: white;
    padding: 3px 8px;
    border-radius: 20px;
    font-size: 12px;
    display: inline-block;
}
/* Melhorias nos ícones de ação (igual ao users.php) */
.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);
}
</style>

<script>
document.addEventListener("DOMContentLoaded", function() {
    window.toggleCreateForm = function() {
        var formCard = document.getElementById('createFormCard');
        if (formCard.style.display === 'none' || formCard.style.display === '') {
            formCard.style.display = 'block';
        } else {
            formCard.style.display = 'none';
        }
    };
    window.buscar = function() {
        var searchTerm = document.getElementById('searchInput').value;
        if (searchTerm) window.location.href = 'dns_manager.php?search=' + encodeURIComponent(searchTerm);
        else window.location.href = 'dns_manager.php';
    };
    window.limparBusca = function() {
        window.location.href = 'dns_manager.php';
    };
    var searchInput = document.getElementById('searchInput');
    if (searchInput) searchInput.addEventListener('keypress', function(e) { if (e.key === 'Enter') buscar(); });
    <?php if ($show_form): ?> document.getElementById('createFormCard').style.display = 'block'; <?php endif; ?>
});
</script>

<div class="main-container">
    <div class="content-wrapper">
        <div class="card-container">
            <div class="card">
                <div class="card-header">
                    <h6><i class="fas fa-database"></i> Minhas DNSs (<?php echo $total_dns; ?>)</h6>
                    <button type="button" class="btn-danger" onclick="toggleCreateForm()"><i class="fas fa-plus"></i> Nova DNS</button>
                </div>
                <div id="createFormCard" class="card-body" style="display: none; border-top: 1px solid #e3e6f0;">
                    <form method="post">
                        <?php if ($edit_dns): ?><input type="hidden" name="id" value="<?php echo $edit_dns['id']; ?>"><?php endif; ?>
                        <div class="row">
                            <div class="col-md-5">
                                <div class="form-group">
                                    <label>Nome da DNS</label>
                                    <input type="text" class="form-control" name="nome" value="<?php echo $edit_dns ? htmlspecialchars($edit_dns['nome']) : ''; ?>" required>
                                </div>
                            </div>
                            <div class="col-md-5">
                                <div class="form-group">
                                    <label>Link da DNS</label>
                                    <input type="text" class="form-control" name="dns" value="<?php echo $edit_dns ? htmlspecialchars($edit_dns['dns']) : ''; ?>" required>
                                    <small class="text-muted">Ex: http://ip:porta</small>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label>&nbsp;</label>
                                    <div>
                                        <button type="submit" name="submit" class="btn btn-primary"><?php echo $edit_dns ? 'Atualizar' : 'Criar'; ?></button>
                                        <?php if ($edit_dns): ?>
                                            <a href="dns_manager.php" class="btn btn-secondary ml-1">Cancelar</a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="card-body">
                    <div class="search-group">
                        <div class="input-group">
                            <input type="text" id="searchInput" class="form-control" placeholder="Pesquise por nome ou DNS..." value="<?php echo htmlspecialchars($searchTerm); ?>">
                            <div class="input-group-append">
                                <button type="button" class="btn btn-primary" onclick="buscar()"><i class="fas fa-search"></i> Pesquisar</button>
                                <?php if (!empty($searchTerm)): ?>
                                    <button type="button" class="btn btn-secondary" onclick="limparBusca()"><i class="fas fa-times"></i> Limpar</button>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Nome</th>
                                    <th>DNS</th>
                                    <th>Usuários Conectados</th>
                                    <th style="width:60px;">Editar</th>
                                    <th style="width:60px;">Excluir</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (count($dns_paginated) > 0): ?>
                                    <?php foreach ($dns_paginated as $dns): ?>
                                    <tr>
                                        <td><?php echo $dns['id']; ?></td>
                                        <td><strong><?php echo htmlspecialchars($dns['nome']); ?></strong></td>
                                        <td><code style="background:#f5f5f5; padding:2px 5px; border-radius:3px; font-family:monospace;"><?php echo htmlspecialchars($dns['dns']); ?></code></td>
                                        <td><span class="badge-users"><i class="fas fa-users"></i> <?php echo $dns['users_count']; ?> usuário(s)</span></td>
                                        <td class="text-center"><a class="btn-action btn-edit" href="dns_manager.php?edit=<?php echo $dns['id']; ?>" title="Editar"><i class="fas fa-edit"></i></a></td>
                                        <td class="text-center"><a class="btn-action btn-delete" href="dns_manager.php?delete=<?php echo $dns['id']; ?>" onclick="return confirm('Excluir DNS: <?php echo htmlspecialchars($dns['nome']); ?>?')" title="Excluir"><i class="fas fa-trash-alt"></i></a></td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr><td colspan="6" class="text-center"><?php echo empty($searchTerm) ? 'Nenhuma DNS cadastrada.' : 'Nenhuma DNS encontrada para "'.htmlspecialchars($searchTerm).'".'; ?></td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php if ($total_pages > 1): ?>
                    <div class="pagination">
                        <?php if ($page > 1): ?><a class="pagination-gap" href="dns_manager.php?page=<?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="dns_manager.php?page=<?php echo $i; ?>&search=<?php echo urlencode($searchTerm); ?>"><?php echo $i; ?></a><?php endfor; ?>
                        <?php if ($page < $total_pages): ?><a class="pagination-gap" href="dns_manager.php?page=<?php echo ($page+1); ?>&search=<?php echo urlencode($searchTerm); ?>">Next &gt;</a><?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php include '../includes/footer3.php'; ?>
    </div>
</div>