<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';
include 'session_check.php';

$page_title = "DNS Page";

$page_content = '
<style>
/* ═══════════════════════════
   PAGE HEADER GRADIENT
═══════════════════════════ */
.dns-page-header {
    background: linear-gradient(135deg, #0d1117 0%, #1a2744 50%, #0d1117 100%);
    border: 1px solid rgba(99,179,237,0.12);
    border-radius: 16px;
    padding: 28px 32px;
    margin-bottom: 24px;
    position: relative;
    overflow: hidden;
}
.dns-page-header::before {
    content: "";
    position: absolute;
    top: -60px; right: -60px;
    width: 200px; height: 200px;
    background: radial-gradient(circle, rgba(99,179,237,0.12) 0%, transparent 70%);
    pointer-events: none;
}
.dns-page-header::after {
    content: "";
    position: absolute;
    bottom: -40px; left: 30%;
    width: 150px; height: 150px;
    background: radial-gradient(circle, rgba(139,92,246,0.08) 0%, transparent 70%);
    pointer-events: none;
}
.dns-page-header h1 {
    color: #e2e8f0;
    font-size: 22px;
    font-weight: 700;
    margin: 0 0 6px;
    display: flex;
    align-items: center;
    gap: 12px;
}
.dns-page-header h1 .icon-wrap {
    width: 40px; height: 40px;
    background: rgba(99,179,237,0.15);
    border: 1px solid rgba(99,179,237,0.25);
    border-radius: 10px;
    display: flex; align-items: center; justify-content: center;
    font-size: 18px;
    color: #63b3ed;
    flex-shrink: 0;
}
.dns-page-header p {
    color: rgba(148,163,184,0.7);
    font-size: 13px;
    margin: 0;
}
.dns-page-header .header-stats {
    display: flex;
    align-items: center;
    gap: 16px;
    flex-shrink: 0;
}
.dns-stat-pill {
    background: rgba(99,179,237,0.08);
    border: 1px solid rgba(99,179,237,0.15);
    border-radius: 50px;
    padding: 6px 14px;
    color: #63b3ed;
    font-size: 12px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 6px;
}

/* ═══════════════════════════
   CARD
═══════════════════════════ */
.dns-card {
    background: #161b22;
    border: 1px solid rgba(99,179,237,0.08);
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 4px 24px rgba(0,0,0,0.3);
}
.dns-card-header {
    background: rgba(255,255,255,0.02);
    border-bottom: 1px solid rgba(255,255,255,0.06);
    padding: 18px 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    flex-wrap: wrap;
}
.dns-search-wrap {
    position: relative;
}
.dns-search-wrap i {
    position: absolute;
    left: 14px;
    top: 50%;
    transform: translateY(-50%);
    color: rgba(148,163,184,0.4);
    font-size: 14px;
    pointer-events: none;
}
.dns-search-wrap input {
    background: rgba(255,255,255,0.04) !important;
    border: 1px solid rgba(255,255,255,0.08) !important;
    border-radius: 10px !important;
    color: #e2e8f0 !important;
    padding: 9px 14px 9px 38px !important;
    font-size: 13px !important;
    width: 240px;
    transition: all 0.2s ease !important;
}
.dns-search-wrap input::placeholder { color: rgba(148,163,184,0.4) !important; }
.dns-search-wrap input:focus {
    border-color: rgba(99,179,237,0.4) !important;
    background: rgba(99,179,237,0.04) !important;
    box-shadow: 0 0 0 3px rgba(99,179,237,0.08) !important;
    outline: none !important;
}
.btn-add-dns {
    background: linear-gradient(135deg, #3b82f6, #6366f1) !important;
    border: none !important;
    border-radius: 10px !important;
    color: #fff !important;
    font-size: 13px !important;
    font-weight: 600 !important;
    padding: 9px 18px !important;
    display: flex;
    align-items: center;
    gap: 8px;
    transition: all 0.2s ease !important;
    box-shadow: 0 4px 12px rgba(59,130,246,0.3) !important;
    cursor: pointer;
}
.btn-add-dns:hover {
    transform: translateY(-1px) !important;
    box-shadow: 0 6px 20px rgba(59,130,246,0.4) !important;
}

/* ═══════════════════════════
   TABLE
═══════════════════════════ */
.dns-card .card-body { padding: 0 !important; }

#kt_customers_table {
    width: 100% !important;
    border-collapse: collapse !important;
}
#kt_customers_table thead tr {
    background: rgba(255,255,255,0.02);
    border-bottom: 1px solid rgba(255,255,255,0.06);
}
#kt_customers_table thead th {
    color: rgba(148,163,184,0.6) !important;
    font-size: 11px !important;
    font-weight: 700 !important;
    text-transform: uppercase !important;
    letter-spacing: 0.08em !important;
    padding: 14px 20px !important;
    white-space: nowrap;
}
#kt_customers_table tbody tr {
    border-bottom: 1px solid rgba(255,255,255,0.04) !important;
    transition: background 0.15s ease;
}
#kt_customers_table tbody tr:last-child {
    border-bottom: none !important;
}
#kt_customers_table tbody tr:hover {
    background: rgba(99,179,237,0.04) !important;
}
#kt_customers_table tbody td {
    color: rgba(203,213,225,0.85) !important;
    font-size: 13px !important;
    padding: 14px 20px !important;
    vertical-align: middle !important;
}
#kt_customers_table tbody td:first-child {
    color: rgba(148,163,184,0.5) !important;
    font-size: 12px !important;
    font-weight: 600;
}

/* ID badge */
.td-id {
    background: rgba(99,179,237,0.08);
    border: 1px solid rgba(99,179,237,0.12);
    border-radius: 6px;
    padding: 3px 10px;
    font-size: 12px;
    font-weight: 700;
    color: #63b3ed !important;
    display: inline-block;
}
/* URL */
.td-url {
    color: rgba(148,163,184,0.5) !important;
    font-family: monospace;
    font-size: 12px !important;
    max-width: 260px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: block;
}
/* Badge Principal */
.badge-principal {
    background: rgba(99,179,237,0.12);
    border: 1px solid rgba(99,179,237,0.2);
    color: #63b3ed;
    border-radius: 50px;
    padding: 2px 10px;
    font-size: 10px;
    font-weight: 700;
    letter-spacing: 0.05em;
    margin-left: 8px;
    vertical-align: middle;
}

/* Action buttons */
.btn-edit-dns {
    background: rgba(251,191,36,0.1) !important;
    border: 1px solid rgba(251,191,36,0.2) !important;
    color: #fbbf24 !important;
    border-radius: 8px !important;
    font-size: 14px !important;
    width: 34px; height: 34px;
    padding: 0 !important;
    display: inline-flex; align-items: center; justify-content: center;
    transition: all 0.2s ease !important;
    cursor: pointer;
}
.btn-edit-dns:hover {
    background: rgba(251,191,36,0.22) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(251,191,36,0.2) !important;
}
.btn-delete-dns {
    background: rgba(248,113,113,0.1) !important;
    border: 1px solid rgba(248,113,113,0.2) !important;
    color: #f87171 !important;
    border-radius: 8px !important;
    font-size: 14px !important;
    width: 34px; height: 34px;
    padding: 0 !important;
    display: inline-flex; align-items: center; justify-content: center;
    transition: all 0.2s ease !important;
    cursor: pointer;
}
.btn-delete-dns:hover {
    background: rgba(248,113,113,0.22) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(248,113,113,0.2) !important;
}
.btn-delete-dns:disabled {
    opacity: 0.25 !important;
    cursor: not-allowed !important;
    transform: none !important;
    box-shadow: none !important;
}

/* DataTables dark override */
.dataTables_wrapper .dataTables_length label,
.dataTables_wrapper .dataTables_info,
.dataTables_wrapper .dataTables_filter label {
    color: rgba(148,163,184,0.6) !important;
    font-size: 12px !important;
}
.dataTables_wrapper .dataTables_length select,
.dataTables_wrapper .dataTables_filter input {
    background: rgba(255,255,255,0.04) !important;
    border: 1px solid rgba(255,255,255,0.08) !important;
    color: #e2e8f0 !important;
    border-radius: 8px !important;
    padding: 4px 10px !important;
    font-size: 12px !important;
}
.dataTables_wrapper .dataTables_paginate .paginate_button {
    background: rgba(255,255,255,0.04) !important;
    border: 1px solid rgba(255,255,255,0.08) !important;
    border-radius: 8px !important;
    color: rgba(148,163,184,0.7) !important;
    margin: 0 2px !important;
    font-size: 12px !important;
    transition: all 0.2s ease !important;
}
.dataTables_wrapper .dataTables_paginate .paginate_button:hover {
    background: rgba(99,179,237,0.1) !important;
    border-color: rgba(99,179,237,0.3) !important;
    color: #63b3ed !important;
}
.dataTables_wrapper .dataTables_paginate .paginate_button.current {
    background: linear-gradient(135deg, rgba(99,179,237,0.2), rgba(139,92,246,0.15)) !important;
    border-color: rgba(99,179,237,0.3) !important;
    color: #e2e8f0 !important;
    font-weight: 700 !important;
}
.dataTables_wrapper {
    padding: 16px 24px !important;
}
.dataTables_wrapper .row:first-child { margin-bottom: 12px; }
.dataTables_wrapper .row:last-child  { margin-top: 12px; }

/* ═══════════════════════════
   MODAL
═══════════════════════════ */
#rainbow_dns .modal-content {
    background: #161b22 !important;
    border: 1px solid rgba(99,179,237,0.12) !important;
    border-radius: 16px !important;
    box-shadow: 0 24px 64px rgba(0,0,0,0.6) !important;
}
#rainbow_dns .modal-header {
    background: rgba(255,255,255,0.02);
    border-bottom: 1px solid rgba(255,255,255,0.06) !important;
    padding: 20px 24px !important;
}
#rainbow_dns .modal-header h2 {
    color: #e2e8f0 !important;
    font-size: 16px !important;
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 10px;
}
#rainbow_dns .modal-header h2::before {
    content: "";
    display: inline-block;
    width: 4px; height: 20px;
    background: linear-gradient(180deg, #63b3ed, #8b5cf6);
    border-radius: 4px;
}
#rainbow_dns .btn-close {
    filter: invert(1) opacity(0.4) !important;
    transition: opacity 0.2s ease !important;
}
#rainbow_dns .btn-close:hover { opacity: 0.8 !important; }
#rainbow_dns .modal-body {
    padding: 24px !important;
    background: #161b22;
}
#rainbow_dns .modal-body label {
    color: rgba(148,163,184,0.8) !important;
    font-size: 12px !important;
    font-weight: 600 !important;
    text-transform: uppercase;
    letter-spacing: 0.06em;
    margin-bottom: 8px !important;
    display: block;
}
#rainbow_dns .modal-body .form-control {
    background: rgba(255,255,255,0.04) !important;
    border: 1px solid rgba(255,255,255,0.1) !important;
    border-radius: 10px !important;
    color: #e2e8f0 !important;
    font-size: 13px !important;
    padding: 10px 14px !important;
    transition: all 0.2s ease !important;
}
#rainbow_dns .modal-body .form-control::placeholder { color: rgba(148,163,184,0.3) !important; }
#rainbow_dns .modal-body .form-control:focus {
    border-color: rgba(99,179,237,0.4) !important;
    box-shadow: 0 0 0 3px rgba(99,179,237,0.08) !important;
    background: rgba(99,179,237,0.04) !important;
    outline: none !important;
}
#rainbow_dns .modal-footer {
    background: rgba(255,255,255,0.02);
    border-top: 1px solid rgba(255,255,255,0.06) !important;
    padding: 16px 24px !important;
    gap: 10px;
}
#rainbow_dns .btn-light {
    background: rgba(255,255,255,0.06) !important;
    border: 1px solid rgba(255,255,255,0.1) !important;
    color: rgba(148,163,184,0.8) !important;
    border-radius: 10px !important;
    font-size: 13px !important;
    font-weight: 600 !important;
    padding: 9px 18px !important;
    transition: all 0.2s ease !important;
}
#rainbow_dns .btn-light:hover {
    background: rgba(255,255,255,0.1) !important;
    color: #e2e8f0 !important;
}
#rainbow_dns .btn-primary {
    background: linear-gradient(135deg, #3b82f6, #6366f1) !important;
    border: none !important;
    border-radius: 10px !important;
    color: #fff !important;
    font-size: 13px !important;
    font-weight: 600 !important;
    padding: 9px 20px !important;
    box-shadow: 0 4px 12px rgba(59,130,246,0.3) !important;
    transition: all 0.2s ease !important;
    display: flex; align-items: center; gap: 8px;
}
#rainbow_dns .btn-primary:hover {
    transform: translateY(-1px) !important;
    box-shadow: 0 6px 20px rgba(59,130,246,0.4) !important;
}
</style>

<!-- PAGE HEADER -->
<div class="dns-page-header d-flex align-items-center justify-content-between flex-wrap gap-3" style="margin-top: 24px;">
    <div>
        <h1>
            <span class="icon-wrap"><i class="fa-solid fa-globe"></i></span>
            Gerenciar DNS
        </h1>
        <p>Gerencie os endereços DNS do seu servidor. O DNS Principal não pode ser removido.</p>
    </div>
    <div class="header-stats">
        <div class="dns-stat-pill" id="dns-count-pill">
            <i class="fa-solid fa-server"></i>
            <span id="dns-total">—</span> registros
        </div>
    </div>
</div>

<!-- CARD -->
<div class="dns-card">
    <div class="dns-card-header">
        <div class="dns-search-wrap">
            <i class="fa-solid fa-magnifying-glass"></i>
            <input type="text" id="search_dns" placeholder="Pesquisar DNS..." />
        </div>
        <button class="btn-add-dns" onclick="openAddModal()">
            <i class="fa-solid fa-plus"></i> Adicionar DNS
        </button>
    </div>
    <div class="card-body">
        <table class="table align-middle table-row-dashed fs-6 gy-5" id="kt_customers_table">
            <thead>
                <tr>
                    <th class="min-w-50px">ID</th>
                    <th class="min-w-125px">Título</th>
                    <th class="min-w-200px">URL</th>
                    <th class="min-w-125px">Ações</th>
                </tr>
            </thead>
            <tbody id="dns_table_body"></tbody>
        </table>
    </div>
</div>

<!-- MODAL -->
<div class="modal fade" id="rainbow_dns" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered mw-550px">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modal_title">Adicionar DNS</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="dns_id">
                <div class="mb-5">
                    <label>Título</label>
                    <input type="text" class="form-control" id="dns_title" placeholder="Ex: DNS Principal">
                </div>
                <div class="mb-2">
                    <label>URL</label>
                    <input type="url" class="form-control" id="dns_url" placeholder="http://exemplo.com">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-light btn" data-bs-dismiss="modal">
                    <i class="fa-solid fa-xmark me-1"></i>Cancelar
                </button>
                <button type="button" class="btn-primary btn" onclick="saveDNS()">
                    <i class="fa-solid fa-floppy-disk"></i>Guardar
                </button>
            </div>
        </div>
    </div>
</div>
';

include 'includes/layout.php'; ?>

<script>
let dataTable;

function loadDNSTable() {
    fetch("actions/dns_actions.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "view" }),
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            if ($.fn.DataTable.isDataTable('#kt_customers_table')) {
                $('#kt_customers_table').DataTable().clear().destroy();
            }

            const tableBody = document.getElementById("dns_table_body");
            tableBody.innerHTML = "";

            // Atualiza contador no header
            const total = data.data.length;
            const el = document.getElementById('dns-total');
            if (el) el.textContent = total;

            data.data.forEach((record) => {
                const isFirstDNS = record.id == 1;
                tableBody.innerHTML += `
                    <tr id="row_${record.id}">
                        <td><span class="td-id">#${record.id}</span></td>
                        <td>
                            <span style="color:#e2e8f0;font-weight:600;">${record.title}</span>
                            ${isFirstDNS ? '<span class="badge-principal">PRINCIPAL</span>' : ''}
                        </td>
                        <td><span class="td-url">${record.url}</span></td>
                        <td style="display:flex;gap:8px;align-items:center;">
                            <button class="btn-edit-dns" onclick="editDNS(${record.id})" title="Editar">
                                <i class="fa-solid fa-pen-to-square"></i>
                            </button>
                            <button class="btn-delete-dns" onclick="deleteDNS(${record.id})"
                                ${isFirstDNS ? 'disabled title="DNS Principal não pode ser apagado"' : 'title="Apagar"'}>
                                <i class="fa-solid fa-trash"></i>
                            </button>
                        </td>
                    </tr>`;
            });

            setTimeout(() => {
                dataTable = $('#kt_customers_table').DataTable({
                    searching: true,
                    paging: true,
                    info: true,
                    responsive: false,
                    language: {
                        search: "",
                        searchPlaceholder: "Filtrar...",
                        lengthMenu: "Mostrar _MENU_",
                        info: "_START_–_END_ de _TOTAL_",
                        paginate: { previous: "‹", next: "›" }
                    }
                });

                // Conecta busca customizada ao DataTable
                document.getElementById('search_dns').addEventListener('keyup', function() {
                    dataTable.search(this.value).draw();
                });
            }, 50);
        }
    });
}

function openAddModal() {
    document.getElementById("modal_title").textContent = "Adicionar DNS";
    document.getElementById("dns_id").value = "";
    document.getElementById("dns_title").value = "";
    document.getElementById("dns_url").value = "";
    new bootstrap.Modal(document.getElementById("rainbow_dns")).show();
}

function editDNS(id) {
    fetch("actions/dns_actions.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "view" }),
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            const dns = data.data.find(d => d.id == id);
            if (dns) {
                document.getElementById("modal_title").textContent = "Editar DNS";
                document.getElementById("dns_id").value = dns.id;
                document.getElementById("dns_title").value = dns.title;
                document.getElementById("dns_url").value = dns.url;
                new bootstrap.Modal(document.getElementById("rainbow_dns")).show();
            }
        }
    });
}

function saveDNS() {
    const id    = document.getElementById("dns_id").value;
    const title = document.getElementById("dns_title").value.trim();
    const url   = document.getElementById("dns_url").value.trim();
    const action = id ? "edit" : "add";

    if (!title || !url) {
        Swal.fire("Erro", "Preencha todos os campos!", "error");
        return;
    }

    const payload = { action, title, url };
    if (action === "edit") payload.id = id;

    fetch("actions/dns_actions.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            Swal.fire("Sucesso", data.message, "success");
            bootstrap.Modal.getInstance(document.getElementById("rainbow_dns")).hide();
            loadDNSTable();
        } else {
            Swal.fire("Erro", data.message, "error");
        }
    });
}

function deleteDNS(id) {
    if (id == 1) {
        Swal.fire({
            title: "Ação não permitida",
            text: "O DNS Principal não pode ser apagado.",
            icon: "warning",
            confirmButtonText: "Entendi"
        });
        return;
    }
    Swal.fire({
        title: "Tem a certeza?",
        text: "O registo será removido permanentemente.",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Sim, apagar!",
        cancelButtonText: "Não"
    }).then((result) => {
        if (result.isConfirmed) {
            fetch("actions/dns_actions.php", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ action: "delete", id }),
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    Swal.fire("Apagado!", data.message, "success").then(() => loadDNSTable());
                } else {
                    Swal.fire("Erro", data.message, "error");
                }
            });
        }
    });
}

document.addEventListener("DOMContentLoaded", loadDNSTable);
</script>