let allData = [];
//let filteredData = [];

document.addEventListener("DOMContentLoaded", function () {

    fetch("/TradeFlow/GetTradeFlow")
        .then(res => res.json())
        .then(data => {

            allData = data;
          //filteredData = data;

            renderTable(allData);

        });

});


function renderTable(filteredData) {

    let tbody = document.getElementById("tradeFlowBody");

    tbody.innerHTML = "";

    filteredData.forEach(item => {

        let row = `
        <tr>
            <td>${item.trade_Flow_No ?? ""}</td>
            <td>${item.desk_Id ?? ""}</td>
            <td>${item.vessel ?? ""}</td>
            <td>${item.added_By ?? ""}</td>
            <td>${formatDate(item.added_DateTime)}</td>
            <td>${item.remarks ?? ""}</td>
        </tr>
        `;

        tbody.innerHTML += row;

    });

}


function filterTable(columnIndex, value) {

    value = value.toLowerCase();

    let filteredData = allData.filter(item => {

        let fields = [
            item.trade_Flow_No,
            item.desk_Id,
            item.vessel,
            item.added_By,
            formatDate(item.added_DateTime),
            item.remarks
        ];

        let field = fields[columnIndex];

        if (field == null) return false;

        return field.toString().toLowerCase().includes(value);

    });

    renderTable(filteredData);

}


function formatDate(dateString) {

    if (!dateString) return "";

    let d = new Date(dateString);

    return d.toLocaleDateString("en-GB");

}