document.addEventListener("DOMContentLoaded", function () {
   
    const modal = document.createElement("div");
    modal.classList.add("modal");
    modal.innerHTML = `
        <div class="modal-content">
            <span class="close-btn">&times;</span>
            <div class="modal-body"></div>
            <button class="save-modal-btn">Save</button>
        </div>
    `;
    document.body.appendChild(modal);

    let currentRow = null;
    let isEditing = false;

   
    function getCSRFToken() {
        let csrfToken = document.querySelector("[name=csrfmiddlewaretoken]");
        return csrfToken ? csrfToken.value : getCookie("csrftoken");
    }

    function getCookie(name) {
        let cookies = document.cookie.split(';');
        for (let cookie of cookies) {
            cookie = cookie.trim();
            if (cookie.startsWith(name + '=')) {
                return decodeURIComponent(cookie.substring(name.length + 1));
            }
        }
        return null;
    }

    // Event Delegation for View, Edit, and Delete buttons
    document.addEventListener("click", function (e) {
        let button = e.target;
        let row = button.closest("tr");
    
        if (!row) return;
    
        let saveButton = document.querySelector(".save-modal-btn");
    
        // View Record Details
        if (button.classList.contains("view-btn")) {
            let details = "";
            row.querySelectorAll("td").forEach((td, index) => {
                // Exclude last column (actions) and the document column containing <a> tag
                if (index !== row.cells.length - 1 && !td.querySelector("a")) {
                    details += `<p><strong>${document.querySelector("thead").rows[0].cells[index].textContent}:</strong> ${td.textContent}</p>`;
                }
            });
        
            let documentCell = row.querySelector("td a"); // Find any <a> inside the row
            let documentUrl = documentCell ? documentCell.href : null;
        
            if (documentUrl && documentUrl.trim() !== "") {
                details += `<label>Document:</label> 
                <a href="${documentUrl}" target="_blank">View Document</a>`;
            } else {
                details += `<label>Document:</label> No Document`;
            }
        
            document.querySelector(".modal-body").innerHTML = details;
            
            if (saveButton) saveButton.style.display = "none";
            document.querySelector(".modal").style.display = "flex";
        
            isEditing = false;
        }
        
    
        // Edit Record
        if (button.classList.contains("edit-btn")) {
            let formFields = "";
            row.querySelectorAll("td").forEach((td, index) => {
                if (index !== row.cells.length - 1 && !td.querySelector("a")) {
                    let value = td.textContent.trim();
                    formFields += `<label>${document.querySelector("thead").rows[0].cells[index].textContent}:</label>
                                   <input type='text' value='${value}' class='edit-field' data-index='${index}'/>`;
                }
            });
        
            // Fetch current document URL
            let documentCell = row.querySelector(".document-cell a");
            let documentUrl = documentCell ? documentCell.href : null;
        
            // Add document section in the edit modal
            formFields += `
                <label>Upload New Document:</label> 
                <input type="file" id="documentUpload" accept="application/pdf">
            `;
        
            document.querySelector(".modal-body").innerHTML = formFields;
        
            if (saveButton) saveButton.style.display = "block";
            document.querySelector(".modal").style.display = "flex";
        
            currentRow = row;
            isEditing = true;
        }
        

        if (button.classList.contains("delete-btn")) {
            let recordId = row.cells[0].textContent;
            if (confirm("Are you sure you want to delete this record?")) {
                fetch(`/delete-record/${recordId}/`, {
                    method: "POST",
                    headers: {
                        "X-CSRFToken": getCSRFToken(),
                        "Content-Type": "application/json"
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        row.remove();
                    } else {
                        alert("Failed to delete record.");
                    }
                })
                .catch(error => console.error("Error:", error));
            }
        }
    });

   
    // Save Modal Button
    document.querySelector(".save-modal-btn").addEventListener("click", function () {
        if (isEditing && currentRow) {
            let recordId = currentRow.cells[0].textContent;
            let fileInput = document.getElementById("documentUpload");
            let formData = new FormData();
            formData.append("record_id", recordId);
    
            document.querySelectorAll(".edit-field").forEach(input => {
                let index = input.getAttribute("data-index");
                let fieldName = document.querySelector("thead").rows[0].cells[index].textContent.toLowerCase().replace(/ /g, '_');
                formData.append(fieldName, input.value);
            });
    
            // Append file if selected
            if (fileInput.files.length > 0) {
                formData.append("document", fileInput.files[0]);
            }
    
            fetch(`/update-record/${recordId}/`, {
                method: "POST",
                headers: { "X-CSRFToken": getCSRFToken() }, // CSRF Token is needed
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Update text fields in table
                    document.querySelectorAll(".edit-field").forEach(input => {
                        let index = input.getAttribute("data-index");
                        currentRow.cells[index].textContent = input.value;
                    });
    
                    // Update document link dynamically
                    if (data.document_url) {
                        let documentCell = currentRow.querySelector(".document-cell");
                        if (documentCell) {
                            documentCell.innerHTML = `<a href="${data.document_url}" target="_blank">View Document</a>`;
                        }
                    }
    
                    document.querySelector(".modal").style.display = "none"; // Close modal after update
                } else {
                    alert("Failed to update record: " + (data.error || "Unknown error"));
                }
            })
            .catch(error => console.error("Error:", error));
        }
    });
    
    

    // Close modal when clicking the close button
    document.querySelector(".close-btn").addEventListener("click", function () {
        let modal = document.querySelector(".modal");
        modal.style.animation = "fadeOut 0.3s ease-in-out forwards";
        setTimeout(() => modal.style.display = "none", 300);
    });
    // Fix Logout Button 
    document.getElementById("logoutBtn").addEventListener("click", function () {
        document.getElementById("logoutForm").submit();
    });

    document.getElementById("getButton")?.addEventListener("click", function() {
        let fromDate = document.getElementById("fromDate").value;
        let toDate = document.getElementById("toDate").value;

        if (!fromDate || !toDate) {
            alert("Please select both From and To dates.");
            return;
        }

        window.location.href = `/travel_bill_report/?from_date=${fromDate}&to_date=${toDate}`;
    });
});


document.getElementById("downloadExcel").addEventListener("click", function () {
    let table = document.getElementById("travelBillTable");
    if (!table) {
        alert("Table not found!");
        return;
    }

    
    let clonedTable = table.cloneNode(true);

    
    let rows = clonedTable.rows;
    for (let i = 0; i < rows.length; i++) {
        rows[i].deleteCell(-1); 
    }

    let workbook = XLSX.utils.book_new();
    let worksheet = XLSX.utils.table_to_sheet(clonedTable);

    XLSX.utils.book_append_sheet(workbook, worksheet, "Travel Bill Report");

    // Download as Excel file
    XLSX.writeFile(workbook, "Travel_Bill_Report.xlsx");
});
