<?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 = '
<div class="card">
    <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 flex-wrap gap-2">
                <button type="button" class="btn btn-primary text-white" onclick="exportToCSV()">
                    <i class="ki-outline ki-file-down fs-2 text-white"></i> Exportar
                </button>
                <button type="button" class="btn btn-light-info" onclick="openBulkEditModal()">Trocar DNS (Massa)</button>
                <button type="button" class="btn btn-light-warning" onclick="deleteSelectedDNS()">Apagar Selecionados</button>
                <button type="button" class="btn btn-light-danger" onclick="deleteAllDNS()">Apagar Todos</button>
                <button type="button" class="btn btn-primary" onclick="openAddModal()">
                    <i class="ki-outline ki-plus fs-2"></i>Add DNS
                </button>
            </div>
        </div>
    </div>
    <div class="card-body pt-0 table-responsive">
        <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="w-10px pe-2">
                        <div class="form-check form-check-sm form-check-custom form-check-solid">
                            <input class="form-check-input" type="checkbox" id="checkAll" onclick="toggleAllCheckboxes(this)" />
                        </div>
                    </th>
                    <th class="min-w-50px">ID</th>
                    <th class="min-w-125px">Título</th>
                    <th class="min-w-125px">URL</th>
                    <th class="text-end min-w-125px">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">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-7">
                    <label class="fs-6 fw-semibold mb-2">Título</label>
                    <input type="text" class="form-control form-control-solid" id="dns_title" placeholder="Ex: DNS Principal">
                </div>
                <div class="mb-7">
                    <label class="fs-6 fw-semibold mb-2">URL</label>
                    <input type="url" class="form-control form-control-solid" id="dns_url" placeholder="http://exemplo.com">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancelar</button>
                <button type="button" class="btn btn-primary" id="btn_save_dns" onclick="saveDNS()">
                    <span class="indicator-label">Guardar</span>
                    <span class="indicator-progress">Processando... <span class="spinner-border spinner-border-sm align-middle ms-2"></span></span>
                </button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modal_bulk_edit" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered mw-650px">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="fw-bold">Trocar DNS em Massa</h2>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-7 bg-light p-4 rounded border border-secondary border-dashed">
                    <label class="fs-6 fw-bold mb-2 text-primary">1. Selecionar URLs Antigas na Tabela (Opcional)</label>
                    <select id="bulk_old_url_selector" class="form-select form-select-solid" onchange="selectByUrl(this.value)">
                        <option value="">Carregando URLs...</option>
                    </select>
                    <div class="text-muted fs-7 mt-2">Isso marca automaticamente as caixinhas de todos os registros que têm essa DNS.</div>
                </div>
                
                <div class="mb-7">
                    <label class="fs-6 fw-semibold mb-2">2. Novo Título (Opcional)</label>
                    <input type="text" class="form-control form-control-solid" id="bulk_dns_title" placeholder="Deixe em branco para manter o atual">
                </div>
                <div class="mb-7">
                    <label class="fs-6 fw-semibold mb-2">3. Nova URL (Opcional)</label>
                    <input type="url" class="form-control form-control-solid" id="bulk_dns_url" placeholder="Deixe em branco para manter a atual">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancelar</button>
                <button type="button" class="btn btn-primary" id="btn_save_bulk_dns" onclick="saveBulkDNS()">
                    <span class="indicator-label">Substituir Selecionados</span>
                    <span class="indicator-progress">Processando... <span class="spinner-border spinner-border-sm align-middle ms-2"></span></span>
                </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) {
            const tableBody = document.getElementById("dns_table_body");
            tableBody.innerHTML = data.data.map(record => {
                const isFirstDNS = record.id == 1;
                return `
                    <tr id="row_${record.id}">
                        <td>
                            <div class="form-check form-check-sm form-check-custom form-check-solid">
                                <input class="form-check-input row-checkbox" type="checkbox" value="${record.id}" ${isFirstDNS ? 'disabled' : ''} />
                            </div>
                        </td>
                        <td>${record.id}</td>
                        <td class="text-nowrap">
                            <div class="d-flex align-items-center">
                                <span class="text-gray-800 fw-bold text-truncate" style="max-width: 150px;" title="${record.title}">${record.title}</span>
                                ${isFirstDNS ? '<span class="badge badge-light-primary ms-2">Principal</span>' : ''}
                            </div>
                        </td>
                        <td class="text-nowrap">
                            <a href="${record.url}" target="_blank" class="text-muted text-hover-primary text-truncate d-inline-block" style="max-width: 200px; vertical-align: middle;" title="${record.url}">${record.url}</a>
                        </td>
                        <td class="text-end text-nowrap">
                            <button class="btn btn-icon btn-bg-light btn-active-color-info btn-sm me-1" onclick="copyToClipboard('${record.url}')" title="Copiar URL">
                                <i class="ki-outline ki-copy fs-3"></i>
                            </button>
                            <button class="btn btn-icon btn-bg-light btn-active-color-primary btn-sm me-1" onclick="editDNS(${record.id})" 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})" ${isFirstDNS ? 'disabled' : ''} title="Apagar">
                                <i class="ki-outline ki-trash fs-3"></i>
                            </button>
                        </td>
                    </tr>`;
            }).join('');

            if ($.fn.DataTable.isDataTable('#kt_customers_table')) {
                $('#kt_customers_table').DataTable().destroy();
            }

            dataTable = $('#kt_customers_table').DataTable({
                info: false,
                order: [[1, 'asc']],
                pageLength: 10,
                columnDefs: [{ orderable: false, targets: [0, 4] }]
            });
            document.getElementById('checkAll').checked = false;
        }
    });
}

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

function exportToCSV() {
    let csv = [];
    let rows = document.querySelectorAll("#kt_customers_table tr");
    
    for (let i = 0; i < rows.length; i++) {
        let row = [], cols = rows[i].querySelectorAll("td, th");
        for (let j = 1; j < cols.length - 1; j++) {
            let data = cols[j].innerText.replace(/(\r\n|\n|\r)/gm, " ").trim();
            row.push('"' + data + '"');
        }
        if(row.length > 0) csv.push(row.join(","));
    }
    
    let csvFile = new Blob([csv.join("\n")], {type: "text/csv"});
    let downloadLink = document.createElement("a");
    downloadLink.download = "dns_backup_" + new Date().toISOString().slice(0,10) + ".csv";
    downloadLink.href = window.URL.createObjectURL(csvFile);
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);
    downloadLink.click();
    toastr.success("Download iniciado!");
}

function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        toastr.info("URL copiada com sucesso!");
    }).catch(err => {
        toastr.error("Falha ao copiar a URL.");
    });
}

function deleteDNS(id) {
    if (id == 1) return toastr.error("O DNS Principal não pode ser removido.");

    Swal.fire({
        title: "Tem certeza?",
        text: "O registro será removido imediatamente.",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Sim, apagar!",
        customClass: { confirmButton: "btn btn-danger", cancelButton: "btn btn-light" }
    }).then((result) => {
        if (result.isConfirmed) {
            const row = document.getElementById(`row_${id}`);
            row.style.transition = "opacity 0.4s";
            row.style.opacity = "0";

            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) {
                    dataTable.row($(`#row_${id}`)).remove().draw(false);
                    toastr.success("DNS removido com sucesso!");
                } else {
                    row.style.opacity = "1";
                    Swal.fire("Erro", data.message, "error");
                }
            });
        }
    });
}

function saveDNS() {
    const btn = document.getElementById('btn_save_dns');
    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) {
        return toastr.warning("Preencha título e URL.");
    }

    btn.setAttribute('data-kt-indicator', 'on');
    btn.disabled = true;

    fetch("actions/dns_actions.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: id ? "edit" : "add", id, title, url }),
    })
    .then(res => res.json())
    .then(data => {
        btn.removeAttribute('data-kt-indicator');
        btn.disabled = false;

        if (data.success) {
            const modalEl = document.getElementById("rainbow_dns");
            const modalInstance = bootstrap.Modal.getInstance(modalEl) || bootstrap.Modal.getOrCreateInstance(modalEl);
            modalInstance.hide();

            document.querySelectorAll('.modal-backdrop').forEach(el => el.remove());
            document.body.classList.remove('modal-open');
            document.body.style.overflow = '';
            document.body.style.paddingRight = '';

            toastr.success(data.message);

            if ($.fn.DataTable.isDataTable('#kt_customers_table')) {
                $('#kt_customers_table').DataTable().destroy();
            }

            setTimeout(() => {
                loadDNSTable(); 
            }, 300);
            
        } else {
            Swal.fire("Erro", data.message, "error");
        }
    }).catch(() => {
        btn.removeAttribute('data-kt-indicator');
        btn.disabled = false;
    });
}

function openBulkEditModal() {
    const urls = new Set();
    document.querySelectorAll('#dns_table_body tr').forEach(row => {
        const urlEl = row.querySelector('td:nth-child(4) a');
        if(urlEl) urls.add(urlEl.innerText.trim());
    });
    
    const selectEl = document.getElementById("bulk_old_url_selector");
    selectEl.innerHTML = '<option value="">Selecione uma URL antiga para marcar...</option>';
    urls.forEach(url => {
        selectEl.innerHTML += `<option value="${url}">${url}</option>`;
    });

    document.getElementById("bulk_dns_title").value = "";
    document.getElementById("bulk_dns_url").value = "";
    new bootstrap.Modal(document.getElementById("modal_bulk_edit")).show();
}

function selectByUrl(urlToFind) {
    if (!urlToFind) return;
    let count = 0;
    document.querySelectorAll('#dns_table_body tr').forEach(row => {
        const urlEl = row.querySelector('td:nth-child(4) a');
        const cb = row.querySelector('.row-checkbox:not([disabled])');
        if(urlEl && cb) {
            if(urlEl.innerText.trim() === urlToFind) {
                cb.checked = true;
                count++;
            }
        }
    });
    if(count > 0) toastr.info(`${count} registros selecionados automaticamente!`);
}

function saveBulkDNS() {
    const selected = document.querySelectorAll('.row-checkbox:checked');
    if (selected.length === 0) {
        return toastr.warning("Selecione pelo menos um registro ou use o seletor de URL antiga.");
    }
    
    const newTitle = document.getElementById("bulk_dns_title").value.trim();
    const newUrl = document.getElementById("bulk_dns_url").value.trim();

    if (!newTitle && !newUrl) {
        return toastr.warning("Preencha ao menos um campo para substituir.");
    }

    const btn = document.getElementById('btn_save_bulk_dns');
    btn.setAttribute('data-kt-indicator', 'on');
    btn.disabled = true;

    let processedCount = 0;
    const totalToProcess = selected.length;

    selected.forEach(cb => {
        const id = cb.value;
        const row = document.getElementById(`row_${id}`);
        
        const currentTitle = row.querySelector('td:nth-child(3) span.text-gray-800').innerText;
        const currentUrl = row.querySelector('td:nth-child(4) a').innerText;

        const finalTitle = newTitle ? newTitle : currentTitle;
        const finalUrl = newUrl ? newUrl : currentUrl;

        fetch("actions/dns_actions.php", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ action: "edit", id: id, title: finalTitle, url: finalUrl }),
        }).then(() => {
            processedCount++;
            if (processedCount === totalToProcess) {
                btn.removeAttribute('data-kt-indicator');
                btn.disabled = false;
                
                const modalEl = document.getElementById("modal_bulk_edit");
                const modalInstance = bootstrap.Modal.getInstance(modalEl);
                if(modalInstance) modalInstance.hide();
                
                document.querySelectorAll('.modal-backdrop').forEach(el => el.remove());
                document.body.classList.remove('modal-open');
                document.body.style.overflow = '';
                document.body.style.paddingRight = '';

                toastr.success(`${totalToProcess} registros atualizados!`);
                document.getElementById('checkAll').checked = false;
                
                if ($.fn.DataTable.isDataTable('#kt_customers_table')) {
                    $('#kt_customers_table').DataTable().destroy();
                }
                setTimeout(() => loadDNSTable(), 300);
            }
        }).catch(() => {
            processedCount++;
            if (processedCount === totalToProcess) {
                btn.removeAttribute('data-kt-indicator');
                btn.disabled = false;
                setTimeout(() => loadDNSTable(), 300);
            }
        });
    });
}

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 => {
        const dns = data.data.find(d => d.id == id);
        if (dns) {
            document.getElementById("dns_id").value = dns.id;
            document.getElementById("dns_title").value = dns.title;
            document.getElementById("dns_url").value = dns.url;
            document.getElementById("modal_title").textContent = "Editar DNS";
            bootstrap.Modal.getOrCreateInstance(document.getElementById("rainbow_dns")).show();
        }
    });
}

function deleteSelectedDNS() {
    const selected = document.querySelectorAll('.row-checkbox:checked');
    if (selected.length === 0) return toastr.info("Selecione um registro.");

    Swal.fire({
        title: `Apagar ${selected.length} registros?`,
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Sim, apagar selecionados"
    }).then((result) => {
        if (result.isConfirmed) {
            selected.forEach(cb => {
                const id = cb.value;
                document.getElementById(`row_${id}`).style.opacity = "0.3";
                fetch("actions/dns_actions.php", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ action: "delete", id }),
                }).then(() => {
                    dataTable.row($(`#row_${id}`)).remove().draw(false);
                });
            });
            toastr.warning("Processamento concluído.");
        }
    });
}

function deleteAllDNS() {
    Swal.fire({
        title: "Apagar TODOS?",
        text: "Isso removerá tudo exceto o DNS Principal.",
        icon: "error",
        showCancelButton: true,
        confirmButtonText: "Sim, limpar tudo!"
    }).then((result) => {
        if (result.isConfirmed) {
            const rows = document.querySelectorAll('.row-checkbox:not([disabled])');
            rows.forEach(cb => {
                const id = cb.value;
                fetch("actions/dns_actions.php", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ action: "delete", id }),
                }).then(() => {
                    dataTable.row($(`#row_${id}`)).remove().draw(false);
                });
            });
            toastr.error("Limpeza concluída.");
        }
    });
}

function toggleAllCheckboxes(source) {
    document.querySelectorAll('.row-checkbox:not([disabled])').forEach(cb => cb.checked = source.checked);
}

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

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