function postDelete(url, id, confirmMessage) {
    if (!confirm(confirmMessage)) return;

    fetch(url, {
        method: "POST",
        credentials: "same-origin",
        cache: "no-store",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "X-Requested-With": "XMLHttpRequest"
        },
        body: "id=" + encodeURIComponent(id)
    })
        .then((res) => res.json().catch(() => ({})).then((data) => ({ ok: res.ok, data })))
        .then(({ ok, data }) => {
            if (!ok || data.status !== "success") {
                const message = data && data.message ? data.message : "Delete failed. Please login again and retry.";
                alert(message);
                return;
            }
            location.reload();
        })
        .catch(() => {
            alert("Delete failed due to a network error. Please retry.");
        });
}

function deleteProject(id) {
    postDelete("/firstchoice_admin/admin/pages/projects/delete_project.php", id, "Delete this project?");
}

function deleteService(id) {
    postDelete("/firstchoice_admin/admin/pages/services/delete_service.php", id, "Delete this service?");
}

function deleteTeam(id) {
    postDelete("/firstchoice_admin/admin/pages/team/delete_team.php", id, "Delete this team member?");
}

function deleteMessage(id) {
    postDelete("/firstchoice_admin/admin/pages/messages_delete.php", id, "Delete this message?");
}

function deleteCertification(id) {
    postDelete("/firstchoice_admin/admin/pages/certification/delete_certification.php", id, "Delete this certification?");
}

document.addEventListener("DOMContentLoaded", function() {
    const toggleBtn = document.querySelector(".sidebar-toggle");
    const sidebar = document.querySelector(".sidebar");

    if (toggleBtn && sidebar) {
        toggleBtn.addEventListener("click", function() {
            sidebar.classList.toggle("active");
        });

        // Close sidebar when clicking outside on mobile
        document.addEventListener("click", function(event) {
            if (window.innerWidth <= 768 && sidebar.classList.contains("active") && 
                !sidebar.contains(event.target) && !toggleBtn.contains(event.target)) {
                sidebar.classList.remove("active");
            }
        });
    }
});
