document.addEventListener("DOMContentLoaded", function () {
    const links = document.querySelectorAll(".sidebar-menu a[data-url]");
    const content = document.getElementById("mainContent");

    if(!content) {
        console.error("mainContent div not found!");
        return;
    }

    // Fetch CSRF token from meta
    const tokenMeta = document.querySelector('meta[name="csrf-token"]');
    const csrfToken = tokenMeta ? tokenMeta.content : '';

    // Click event for sidebar links
    links.forEach(link => {
        link.addEventListener("click", function(e){
            e.preventDefault();
            const url = this.getAttribute("data-url");
            if(url) loadContent(url);
        });
    });

    // Form AJAX submit
    document.addEventListener('submit', function(e){
        if(e.target.id === 'blogForm'){
            e.preventDefault();
            const form = e.target;
            const method = form.querySelector('input[name="_method"]')?.value || form.method;
            const action = form.action;
            const formData = new FormData(form);

            fetch(action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRF-TOKEN': csrfToken,
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(res => res.json())
            .then(data => {
                if(data.success){
                    alert(data.success);
                    loadContent('/admin/admin/blog-content'); // always load dashboard
                } else if(data.errors){
                    let errorHtml = '<ul style="color:red">';
                    for(let field in data.errors){
                        data.errors[field].forEach(msg => errorHtml += `<li>${msg}</li>`);
                    }
                    errorHtml += '</ul>';
                    content.innerHTML = errorHtml;
                }
            })
            .catch(err => {
                content.innerHTML = "<p style='color:red'>Error submitting form!</p>";
                console.error(err);
            });
        }
    });
});

// Global loadContent function
function loadContent(url){
    const container = document.getElementById("mainContent");
    if(!container) return;

    fetch(url, { headers: { 'X-Requested-With':'XMLHttpRequest' } })
        .then(res => res.text())
        .then(html => {
            container.innerHTML = html;

            // Summernote ko re-init karo agar textarea mila
            if(document.getElementById("summernote")){
                $('#summernote').summernote({
                    placeholder: 'Write your blog content here...',
                    tabsize: 2,
                    height: 300,
                    toolbar: [
                        ['style', ['style']],
                        ['font', ['bold', 'italic', 'underline', 'clear']],
                        ['fontname', ['fontname']],
                        ['color', ['color']],
                        ['para', ['ul', 'ol', 'paragraph']],
                        ['insert', ['link', 'picture', 'video']],
                        ['view', ['fullscreen', 'codeview', 'help']]
                    ]
                });
            }
        })
        .catch(err => {
            container.innerHTML = "<p style='color:red'>Error loading content!</p>";
            console.error(err);
        });
}


// Delete blog via AJAX
function deleteBlog(id){
    if(!confirm("Are you sure?")) return;

    const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

    fetch(`/admin/admin/blogs/${id}`, {
        method: "DELETE",
        headers: {
            "X-CSRF-TOKEN": token,
            "Content-Type": "application/json",
            "Accept": "application/json"
        }
    })
    .then(response => {
        if (!response.ok) {
            throw new Error("Network response was not ok " + response.status);
        }
        return response.json();
    })
    .then(data => {
        if(data.success){
            alert(data.success);
            loadContent('/admin/admin/blog-content');
        }
    })
    .catch(error => {
        console.error("Delete failed:", error);
        alert("Error deleting blog!");
    });
}


