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

$page_title = "DNS Page";

$page_content = '
<div class="row g-5 mb-5">
    <div class="col-md-4">
        <div class="card card-flush h-md-100" style="background: linear-gradient(112.14deg, #132143 0%, #20365F 100%)">
            <div class="card-header pt-5">
                <div class="card-title d-flex flex-column">
                    <span class="fs-2hx fw-bold text-white me-2 lh-1 ls-n2" id="total_dns_count">0</span>
                    <span class="text-white opacity-75 pt-1 fw-semibold fs-6">Total de DNS Cadastrados</span>
                </div>
            </div>
            <div class="card-body d-flex align-items-end pb-4">
                <div class="d-flex align-items-center">
                    <span class="badge badge-light-success fs-base"><i class="ki-outline ki-arrow-up fs-5 text-success me-1"></i> Sistema Ativo</span>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-8">
        <div class="card card-flush h-md-100">
            <div class="card-body d-flex flex-column justify-content-center">
                <div class="d-flex flex-stack">
                    <div class="me-5">
                        <span class="text-gray-800 fw-bold fs-2 d-block">Status do Servidor</span>
                        <span class="text-gray-400 fw-semibold fs-6">Sincronização em tempo real com o banco de dados.</span>
                    </div>
                    <div class="symbol symbol-45px symbol-circle">
                        <div class="symbol-label bg-light-success">
                            <span class="pulse pulse-success">
                                <span class="pulse-ring"></span>
                                <i class="ki-outline ki-cloud-change fs-2 text-success"></i>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-header border-0 pt-6">
        <div class="card-title">
            <div class="d-flex align-items-center position-relative my-1">
                <i class="ki-outline ki-magnifier fs-3 position-absolute ms-5"></i>
                <input type="text" id="search_dns" class="form-control form-control-solid w-250px ps-12" placeholder="Pesquisar DNS..." />
            </div>
        </div>
        <div class="card-toolbar">
            <div class="d-flex justify-content-end">
                <button type="button" class="btn btn-primary shadow-sm" onclick="openAddModal()">
                    <i class="ki-outline ki-plus fs-2"></i> Adicionar DNS
                </button>
            </div>
        </div>
    </div>
    <div class="card-body pt-0">
        <table class="table align-middle table-row-dashed fs-6 gy-5" id="kt_customers_table">
            <thead>
                <tr class="text-start text-gray-800 fw-bold fs-7 text-uppercase gs-0">
                    <th class="min-w-50px">ID</th>
                    <th class="min-w-150px">Título</th>
                    <th class="min-w-250px">URL do Servidor</th>
                    <th class="min-w-100px text-end">Ações</th>
                </tr>
            </thead>
            <tbody id="dns_table_body" class="fw-semibold text-gray-600"></tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="rainbow_dns" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered mw-650px">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modal_title" class="fw-bold">Add DNS</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="dns_id" name="dns_id">
                <div class="mb-7">
                    <label for="dns_title" class="fs-6 fw-semibold mb-2">Title</label>
                    <input type="text" class="form-control" id="dns_title" name="title" placeholder="Enter Title" required>
                </div>
                <div class="mb-7">
                    <label for="dns_url" class="fs-6 fw-semibold mb-2">URL</label>
                    <input type="url" class="form-control" id="dns_url" name="url" placeholder="Enter URL" required>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="saveDNS()">Save</button>
            </div>
        </div>
    </div>
</div>

<style>
    .table-hover-custom tr:hover { background-color: #f9f9f9; transition: 0.3s; }
    .copy-badge { cursor: pointer; transition: 0.2s; }
    .copy-badge:active { transform: scale(0.9); }
</style>
';

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((response) => response.json())
        .then((data) => {
            if (data.success) {
                const tableBody = document.getElementById("dns_table_body");
                tableBody.innerHTML = "";
                
                // Atualiza o contador novo
                document.getElementById("total_dns_count").innerText = data.data.length;

                data.data.forEach((record) => {
                    tableBody.innerHTML += `
                        <tr id="row_${record.id}" class="table-hover-custom">
                            <td><span class="text-gray-800 fw-bold">${record.id}</span></td>
                            <td>
                                <div class="d-flex align-items-center">
                                    <div class="symbol symbol-30px me-3">
                                        <div class="symbol-label bg-light-primary">
                                            <i class="ki-outline ki-world text-primary fs-4"></i>
                                        </div>
                                    </div>
                                    <span class="text-gray-800 fw-bold text-hover-primary mb-1 fs-6">${record.title}</span>
                                </div>
                            </td>
                            <td>
                                <code class="p-2 bg-light rounded text-primary fs-7 copy-badge" onclick="copyURL('${record.url}')" title="Clique para copiar">
                                    ${record.url}
                                </code>
                            </td>
                            <td class="text-end">
                                <button class="btn btn-icon btn-bg-light btn-active-color-warning btn-sm me-1" onclick="editDNS(${record.id}, '${record.title}', '${record.url}')" title="Editar">
                                    <i class="ki-outline ki-pencil fs-3"></i>
                                </button>
                                <button class="btn btn-icon btn-bg-light btn-active-color-danger btn-sm" onclick="deleteDNS(${record.id})" title="Excluir">
                                    <i class="ki-outline ki-trash fs-3"></i>
                                </button>
                            </td>
                        </tr>
                    `;
                });

                if (dataTable) {
                    dataTable.destroy();
                }

                dataTable = $('#kt_customers_table').DataTable({
                    searching: true,
                    paging: true,
                    ordering: true,
                    info: true,
                    responsive: false,
                    language: {
                        emptyTable: "Nenhum DNS encontrado"
                    }
                });
            }
        })
        .catch((error) => console.error("Error loading DNS table:", error));
}

// Função Nova: Clique para Copiar
function copyURL(url) {
    navigator.clipboard.writeText(url);
    Swal.fire({
        text: "URL copiada para a área de transferência!",
        icon: "success",
        buttonsStyling: false,
        confirmButtonText: "Ok",
        customClass: { confirmButton: "btn btn-primary" },
        timer: 1500
    });
}

document.getElementById("search_dns").addEventListener("input", function () {
    if (dataTable) {
        dataTable.search(this.value).draw();
    }
});

function openAddModal() {
    document.getElementById("modal_title").textContent = "Add 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, title, url) {
    document.getElementById("modal_title").textContent = "Edit DNS";
    document.getElementById("dns_id").value = id;
    document.getElementById("dns_title").value = title;
    document.getElementById("dns_url").value = 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();

    if (!title || !url) {
        Swal.fire("Error", "Both Title and URL are required!", "error");
        return;
    }

    const action = id ? "edit" : "add";

    fetch("actions/dns_actions.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action, id, title, url }),
    })
        .then((response) => response.json())
        .then((data) => {
            if (data.success) {
                Swal.fire("Success", data.message, "success");
                const modal = bootstrap.Modal.getInstance(document.getElementById("rainbow_dns"));
                modal.hide();
                loadDNSTable(); // Recarrega a tabela para atualizar tudo visualmente
            } else {
                Swal.fire("Error", data.message, "error");
            }
        })
        .catch((error) => console.error("Error saving DNS:", error));
}


function deleteDNS(id) {
    Swal.fire({
        title: "Are you sure?",
        text: "This will delete the DNS record!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Yes, delete it!",
    }).then((result) => {
        if (result.isConfirmed) {
            fetch("actions/dns_actions.php", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ action: "delete", id }),
            })
                .then((response) => response.json())
                .then((data) => {
                    if (data.success) {
                        Swal.fire("Deleted!", data.message, "success");
                        loadDNSTable();
                    } else {
                        Swal.fire("Error", data.message, "error");
                    }
                })
                .catch((error) => console.error("Error deleting DNS:", error));
        }
    });
}

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