import { formatCurrency, paginator } from "./common.js"
export let currentPage = 1;
export function showTable(api, ps, cp) {
    let token = localStorage.getItem("token");
    let tbody = document.getElementById("subscriptions-table").getElementsByTagName("tbody")[0];
    // reset tbody
    tbody.innerHTML = ``
    const body = {
        page_size: parseInt(ps, 10),
        page: parseInt(cp, 10),
    };
    const requestOptions = {
        method: 'post',
        headers: {
            'Accept': `application/json`,
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token,
        },
        body: JSON.stringify(body),
    };
    fetch(api + "/api/admin/all-subscriptions", requestOptions)
        .then(response => response.json())
        .then(function (data) {
            if (data.orders) {
                data.orders.forEach(function (i) {
                    let newRow = tbody.insertRow();
                    let newCell = newRow.insertCell();
                    newCell.innerHTML = `Order ${i.id}`;
                    newCell.addEventListener("click", function (evt) {
                        // put the current_page into sessionStorage
                        sessionStorage.setItem("cur-page", data.current_page);
                        // redirect
                        location.href = `/admin/subscriptions/${i.id}`;
                    });
                    newCell = newRow.insertCell();
                    let item = document.createTextNode(i.customer.last_name + ", " + i.customer.first_name);
                    newCell.appendChild(item)
                    newCell = newRow.insertCell();
                    item = document.createTextNode(i.widget.name);
                    newCell.appendChild(item)
                    let cur = formatCurrency(i.transaction.amount)
                    newCell = newRow.insertCell();
                    item = document.createTextNode(cur + "/month");
                    newCell.appendChild(item)
                    newCell = newRow.insertCell();
                    if (i.status_id != 1) {
                        newCell.innerHTML = `Cancelled`
                    } else {
                        newCell.innerHTML = `Charged`
                    }
                    paginator(api, data.last_page, data.current_page, showTable)
                });
            } else {
                let newRow = tbody.insertRow();
                let newCell = newRow.insertCell();
                newCell.setAttribute("colspan", "4");
                newCell.innerHTML = "No data available";
            }
        });
}