<?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="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="Search DNS" />
            </div>
        </div>
        <div class="card-toolbar">
            <div class="d-flex justify-content-end">
                <button type="button" class="btn btn-primary" onclick="openAddModal()">Add 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-125px">ID</th>
                    <th class="min-w-125px">Title</th>
                    <th class="min-w-125px">URL</th>
                    <th class="min-w-125px">Actions</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>
';

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 = "";

                data.data.forEach((record) => {
                    tableBody.innerHTML += `
                        <tr id="row_${record.id}">
                            <td>${record.id}</td>
                            <td>${record.title}</td>
                            <td>${record.url}</td>
                            <td class="">
                                <button class="btn btn-sm btn-warning" onclick="editDNS(${record.id}, '${record.title}', '${record.url}')">Edit</button>
                                <button class="btn btn-sm btn-danger" onclick="deleteDNS(${record.id})">Delete</button>
                            </td>
                        </tr>
                    `;
                });

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

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

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();

                if (action === "add") {
                    const newRow = dataTable.row.add([
                        data.new_id,
                        title,
                        url,
                        `
                        <button class="btn btn-sm btn-warning" onclick="editDNS(${data.new_id}, '${title}', '${url}')">Edit</button>
                        <button class="btn btn-sm btn-danger" onclick="deleteDNS(${data.new_id})">Delete</button>
                        `
                    ]).draw(false).node();

                    $(newRow).attr('id', `row_${data.new_id}`);
                } else {
                    const row = dataTable.row(`#row_${id}`);
                    if (row.node()) {
                        row.data([
                            id,
                            title,
                            url,
                            `
                            <button class="btn btn-sm btn-warning" onclick="editDNS(${id}, '${title}', '${url}')">Edit</button>
                            <button class="btn btn-sm btn-danger" onclick="deleteDNS(${id})">Delete</button>
                            `
                        ]).draw(false);
                    } else {
                        console.error("Row not found for update: ID=", id);
                    }
                }
            } 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");

                        const row = dataTable.row(`#row_${id}`);
                        if (row.node()) {
                            row.remove().draw(false);
                        } else {
                            console.error("Row not found for deletion: ID=", id);
                        }
                    } else {
                        Swal.fire("Error", data.message, "error");
                    }
                })
                .catch((error) => console.error("Error deleting DNS:", error));
        }
    });
}





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