function calculateTotalKms() {
    let openingKms = parseFloat(document.getElementById("opening_kms").value) || 0;
    let closingKms = parseFloat(document.getElementById("closing_kms").value) || 0;
    document.getElementById("total_kms").value = closingKms >= openingKms ? closingKms - openingKms : 0;
}

function calculateNightCharges() {
    let fromDate = new Date(document.querySelector("input[name='from_date_time']").value);
    let toDate = new Date(document.querySelector("input[name='to_date_time']").value);

    if (isNaN(fromDate.getTime()) || isNaN(toDate.getTime())) {
        document.getElementById("night").value = 0;
        return;
    }

    let diffInDays = Math.floor((toDate - fromDate) / (1000 * 60 * 60 * 24));
    document.getElementById("night").value = diffInDays >= 1 ? diffInDays * 300 : 0;
    calculateTotalAmount();
}

function calculateTotalAmount() {
    let amount = parseFloat(document.querySelector("input[name='amt']").value) || 0;
    let nightCharges = parseFloat(document.getElementById("night").value) || 0;
    let toll = parseFloat(document.querySelector("input[name='toll']").value) || 0;
    document.getElementById("total_amount").value = amount + nightCharges + toll;
}

document.addEventListener("DOMContentLoaded", function () {
    const form = document.getElementById("welcomeForm");
    const loadingOverlay = document.getElementById("loadingOverlay");

    form.addEventListener("submit", function (event) {
        event.preventDefault(); 

        
        loadingOverlay.style.display = "flex";

        var formData = new FormData(this);
        var fileInput = document.querySelector("input[type='file']");
        var file = fileInput.files[0];

      
        if (file && file.size > 1048576) { 
            showMessage("File size exceeds 1MB. Please upload a smaller file.", "error");
            loadingOverlay.style.display = "none";
            return;
        }

        // Append required values to formData
        formData.set("amt", document.querySelector("input[name='amt']").value);
        formData.set("night", document.getElementById("night").value);
        formData.set("toll", document.querySelector("input[name='toll']").value);
        formData.set("total_amount", document.getElementById("total_amount").value);
        formData.set("total_kms", document.getElementById("total_kms").value);

        fetch(this.action, {
            method: "POST",
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showMessage("Bill successfully saved!", "success");
                setTimeout(() => {
                    location.reload(); 
                }, 2500); 
            } else {
                showMessage("Error: " + data.message, "error");
            }
        })
        .catch(error => {
            console.error("Error:", error);
            showMessage("Something went wrong. Please try again.", "error");
        })
        .finally(() => {
          
            loadingOverlay.style.display = "none";
        });
    });

    function showMessage(message, type) {
        const messageBox = document.createElement("div");
        messageBox.innerText = message;
        messageBox.style.position = "fixed";
        messageBox.style.top = "20px";
        messageBox.style.left = "50%";
        messageBox.style.transform = "translateX(-50%)";
        messageBox.style.padding = "10px 20px";
        messageBox.style.color = "#fff";
        messageBox.style.borderRadius = "5px";
        messageBox.style.zIndex = "9999";
        messageBox.style.backgroundColor = type === "success" ? "green" : "red";

        document.body.appendChild(messageBox);
        
        setTimeout(() => {
            messageBox.remove(); 
        }, 3000);
    }

    
  
    document.getElementById("opening_kms").addEventListener("input", calculateTotalKms);
    document.getElementById("closing_kms").addEventListener("input", calculateTotalKms);
    document.querySelector("input[name='from_date_time']").addEventListener("change", calculateNightCharges);
    document.querySelector("input[name='to_date_time']").addEventListener("change", calculateNightCharges);
    document.querySelector("input[name='amt']").addEventListener("input", calculateTotalAmount);
    document.getElementById("night").addEventListener("input", calculateTotalAmount);
    document.querySelector("input[name='toll']").addEventListener("input", calculateTotalAmount);

    
    document.getElementById("logoutBtn").addEventListener("click", function () {
        document.getElementById("logoutForm").submit();
    });

    
    calculateTotalKms();
    calculateNightCharges();
    calculateTotalAmount();
});
