<?php

//<----------------------------------------------------------->
//<-------------------COPIA AI BRUXÃO------------------------->
//<-------------CONTATO: https://t.me/eonbry------------------>
//<-------------DEVELOPER: EMANUEL NASCIMENTO----------------->
//<----------------------------------------------------------->


include('includes/header.php');

// nome da tabela
$table_name = "dns";
$page = "main.php";

// ====== FUNÇÃO: GERAR API/portals.json ======
function syncPortalsJson($db, $table_name)
{
    $apiDir  = __DIR__ . "/api";
    $apiFile = $apiDir . "/portals.json";

    $rows = $db->select($table_name, '*', '', '');

    $portals = [];
    $i = 0;

    if (is_array($rows)) {
        foreach ($rows as $r) {
            $portals[] = [
                "id"      => $i++,
                "name"    => $r["title"] ?? "",
                "url"     => $r["url"] ?? "",
                "epg_url" => $r["epg_url"] ?? ""
            ];
        }
    }

    $payload = ["portals" => $portals];

    if (!is_dir($apiDir)) {
        @mkdir($apiDir, 0755, true);
    }

    $json = json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

    if ($json === false) {
        return false;
    }

    return (file_put_contents($apiFile, $json) !== false);
}

// chamada da tabela
$res = $db->select($table_name, '*', '', '');

// chamada de atualização
@$resU = $db->select($table_name, '*', 'id = :id', '', [':id' => $_GET['update']]);

if (isset($_POST['submitU'])) {
    unset($_POST['submitU']);
    $updateData = $_POST;
    unset($updateData['id']);
    $db->update($table_name, $updateData, 'id = :id', [':id' => $_GET['update']]);
    syncPortalsJson($db, $table_name);
    echo "<script>window.location.href='" . $page . "?status=1'</script>";
    exit;
}

if (isset($_POST['submit'])) {
    unset($_POST['submit']);
    $db->insert($table_name, $_POST);
    syncPortalsJson($db, $table_name);
    $db->close();
    echo "<script>window.location.href='" . $page . "?status=1'</script>";
    exit;
}

if (isset($_GET['delete'])) {
    $db->delete($table_name, 'id = :id', [':id' => $_GET['delete']]);
    syncPortalsJson($db, $table_name);
    echo "<script>window.location.href='" . $page . "?status=2'</script>";
    exit;
}
?>

<style>
    :root {
        --deep-blue: #0a0f1a;
        --dark-gray: #1e293b;
        --accent-blue: #3b82f6;
        --text-main: #e2e8f0;
        --text-muted: #94a3b8;
        --glass-bg: rgba(30, 41, 59, 0.7);
        --glass-border: rgba(255, 255, 255, 0.08);
    }

    .main-content {
        padding: 40px 20px;
    }

    .glass-card {
        background: var(--glass-bg);
        backdrop-filter: blur(16px);
        -webkit-backdrop-filter: blur(16px);
        border: 1px solid var(--glass-border);
        border-radius: 20px;
        padding: 30px;
        box-shadow: 0 20px 40px rgba(0, 0, 0, 0.4);
        margin-bottom: 30px;
    }

    .header-section {
        margin-bottom: 25px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 15px;
    }

    .header-section h2 {
        font-size: 1.5rem;
        font-weight: 700;
        color: #ffffff;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .header-section h2 i {
        color: var(--accent-blue);
    }

    .btn-action {
        background: var(--accent-blue);
        color: white;
        border: none;
        border-radius: 10px;
        padding: 10px 20px;
        font-weight: 600;
        transition: all 0.3s ease;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

    .btn-action:hover {
        background: #2563eb;
        transform: translateY(-1px);
        color: white;
        text-decoration: none;
    }

    /* Table Styling */
    .table-responsive {
        border-radius: 12px;
        overflow: hidden;
        border: 1px solid var(--glass-border);
    }

    .table {
        margin-bottom: 0;
        color: var(--text-main);
    }

    .table thead th {
        background: rgba(15, 23, 42, 0.8);
        border-bottom: 2px solid var(--glass-border);
        color: var(--text-muted);
        text-transform: uppercase;
        font-size: 0.75rem;
        letter-spacing: 0.05em;
        padding: 15px;
    }

    .table tbody td {
        padding: 15px;
        vertical-align: middle;
        border-top: 1px solid var(--glass-border);
        background: rgba(30, 41, 59, 0.4);
    }

    .table tbody tr:hover td {
        background: rgba(59, 130, 246, 0.05);
    }

    .btn-icon {
        width: 36px;
        height: 36px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border-radius: 8px;
        transition: 0.2s;
    }

    .btn-edit {
        background: rgba(59, 130, 246, 0.1);
        color: var(--accent-blue);
    }

    .btn-edit:hover {
        background: var(--accent-blue);
        color: white;
    }

    .btn-delete {
        background: rgba(239, 68, 68, 0.1);
        color: #ef4444;
    }

    .btn-delete:hover {
        background: #ef4444;
        color: white;
    }

    /* Form Styling */
    .form-group label {
        color: var(--text-muted);
        font-size: 0.85rem;
        font-weight: 600;
        margin-bottom: 8px;
    }

    .form-control {
        background: rgba(15, 23, 42, 0.6);
        border: 1px solid var(--glass-border);
        border-radius: 10px;
        padding: 12px 15px;
        color: white;
        transition: 0.2s;
    }

    .form-control:focus {
        background: rgba(15, 23, 42, 0.8);
        border-color: var(--accent-blue);
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        color: white;
    }

    /* Modal Styling */
    .modal-content {
        background: var(--sidebar-bg);
        border: 1px solid var(--glass-border);
        border-radius: 20px;
        color: white;
    }

    .modal-header {
        border-bottom: 1px solid var(--glass-border);
    }

    .modal-footer {
        border-top: 1px solid var(--glass-border);
    }
</style>

<div class="main-content">
    <?php if (isset($_GET['create']) || isset($_GET['update'])) { ?>
        <!-- Formulário de Adição/Edição -->
        <div class="glass-card mx-auto" style="max-width: 600px;">
            <div class="header-section">
                <h2>
                    <i class="fa <?= isset($_GET['update']) ? 'fa-pencil' : 'fa-plus-circle' ?>"></i>
                    <?= isset($_GET['update']) ? 'Editar Servidor' : 'Novo Servidor DNS' ?>
                </h2>
                <a href="<?= $page ?>" class="btn-action" style="background: rgba(255,255,255,0.1); color: var(--text-muted);">Voltar</a>
            </div>

            <form method="post">
                <?php if (isset($_GET['update'])) { ?>
                    <input type="hidden" name="id" value="<?= $_GET['update'] ?>">
                <?php } ?>

                <div class="form-group">
                    <label>Título do Servidor</label>
                    <input type="text" class="form-control" name="title" value="<?= $resU[0]['title'] ?? '' ?>" placeholder="Ex: Servidor Principal" required>
                </div>

                <div class="form-group">
                    <label>URL do DNS</label>
                    <input type="text" class="form-control" name="url" value="<?= $resU[0]['url'] ?? '' ?>" placeholder="http://exemplo.com:8080" required>
                </div>

                <div class="form-group">
                    <label>URL do EPG (Opcional)</label>
                    <input type="text" class="form-control" name="epg_url" value="<?= $resU[0]['epg_url'] ?? '' ?>" placeholder="http://exemplo.com/epg.xml">
                </div>

                <button type="submit" name="<?= isset($_GET['update']) ? 'submitU' : 'submit' ?>" class="btn-action w-100 justify-content-center mt-3">
                    <i class="fa fa-check"></i> Salvar Configurações
                </button>
            </form>
        </div>

    <?php } else { ?>
        <!-- Listagem de Servidores -->
        <div class="glass-card">
            <div class="header-section">
                <h2><i class="fa fa-server"></i> Servidores DNS Ativos</h2>
                <a href="<?= $page ?>?create" class="btn-action">
                    <i class="fa fa-plus"></i> Adicionar Novo
                </a>
            </div>

            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Título</th>
                            <th>DNS / URL</th>
                            <th>EPG URL</th>
                            <th class="text-center">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($res)) { ?>
                            <tr>
                                <td colspan="4" class="text-center text-muted">Nenhum servidor cadastrado.</td>
                            </tr>
                        <?php } else { ?>
                            <?php foreach ($res as $row) { ?>
                                <tr>
                                    <td style="font-weight: 600;"><?= $row['title'] ?></td>
                                    <td style="font-family: monospace; font-size: 0.9rem; color: var(--accent-blue);"><?= $row['url'] ?></td>
                                    <td class="text-muted small"><?= $row['epg_url'] ?: '---' ?></td>
                                    <td class="text-center">
                                        <a href="<?= $page ?>?update=<?= $row['id'] ?>" class="btn-icon btn-edit" title="Editar">
                                            <i class="fa fa-pencil"></i>
                                        </a>
                                        <a href="#" data-href="<?= $page ?>?delete=<?= $row['id'] ?>" data-toggle="modal" data-target="#confirm-delete" class="btn-icon btn-delete" title="Excluir">
                                            <i class="fa fa-trash"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php } ?>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php } ?>
</div>

<!-- Modal de Confirmação -->
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Confirmar Exclusão</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="color: white;">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body text-center p-4">
                <i class="fa fa-exclamation-triangle mb-3" style="font-size: 3rem; color: #ef4444;"></i>
                <p>Você tem certeza que deseja excluir este servidor? Esta ação não pode ser desfeita.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal" style="border-radius: 10px;">Cancelar</button>
                <a class="btn btn-danger btn-ok" style="border-radius: 10px; padding: 8px 20px;">Sim, Excluir</a>
            </div>
        </div>
    </div>
</div>

<script>
    // Script para passar a URL de exclusão para o modal
    $('#confirm-delete').on('show.bs.modal', function(e) {
        $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
    });
    
    // Função para criar e exibir alertas que desaparecem sozinhos
function createAlert(title, message, type) {
    const container = document.getElementById('pageMessages');
    if (!container) return;

    // Criar o elemento do alerta
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.role = 'alert';
    alertDiv.style.boxShadow = '0 10px 30px rgba(0,0,0,0.4)';
    alertDiv.style.borderRadius = '12px';
    alertDiv.style.border = '1px solid rgba(255,255,255,0.1)';
    alertDiv.style.background = type === 'success' ? 'rgba(16, 185, 129, 0.95)' : 'rgba(239, 68, 68, 0.95)';
    alertDiv.style.color = '#fff';
    alertDiv.style.backdropFilter = 'blur(12px)';
    alertDiv.style.marginBottom = '10px';
    alertDiv.style.padding = '15px 20px';

    alertDiv.innerHTML = `
        <div class="d-flex align-items-center justify-content-between">
            <div>
                <i class="fa ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'} mr-2"></i>
                <strong>${title}</strong> ${message}
            </div>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close" style="color: #fff; opacity: 0.8; position: static; padding: 0; margin-left: 15px;">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    `;

    // Adicionar ao container
    container.appendChild(alertDiv);

    // AUTO-OCULTAR APÓS 2 SEGUNDOS (2000ms)
    setTimeout(function() {
        $(alertDiv).fadeTo(500, 0).slideUp(500, function(){
            $(this).remove(); 
        });
    }, 2000);
}

// Verificar se existe status na URL ao carregar a página
$(document).ready(function() {
    const urlParams = new URLSearchParams(window.location.search);
    
    if (urlParams.has('status')) {
        const status = urlParams.get('status');
        
        // Exibir o alerta baseado no status
        if (status == '1') {
            createAlert('Sucesso!', 'As alterações foram salvas com êxito.', 'success');
        } else if (status == '2') {
            createAlert('Excluído!', 'O item foi removido do sistema.', 'success');
        } else if (status == '0') {
            createAlert('Erro!', 'Ocorreu um problema na operação.', 'danger');
        }
        
        // --- SOLUÇÃO PARA NÃO REPETIR AO ATUALIZAR (F5) ---
        // Remove o "?status=X" da URL sem recarregar a página
        const newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
        window.history.replaceState({path: newUrl}, '', newUrl);
    }
});

</script>

<?php include('includes/footer.php'); ?>
</body>
</html>
