import { Grid } from "gridjs/dist/gridjs.umd.js";
import "gridjs/dist/gridjs.umd.js";
import gridjs from "gridjs/dist/gridjs.umd.js";
import GlobalConfig, { addThousandSeparators } from "../global-config.js";

class ReportPaymentRecaps {
    constructor() {
        this.table = null;
        this.initTableReportPaymentRecaps();
    }
    initTableReportPaymentRecaps() {
        let tableContainer = document.getElementById(
            "table-report-payment-recaps"
        );

        this.table = new Grid({
            columns: [
                { name: "Kecamatan" },
                {
                    name: "Total",
                    formatter: (cell) => addThousandSeparators(cell),
                },
            ],
            pagination: {
                limit: 10,
                server: {
                    url: (prev, page) =>
                        `${prev}${prev.includes("?") ? "&" : "?"}page=${
                            page + 1
                        }`,
                },
            },
            sort: true,
            server: {
                url: `${GlobalConfig.apiHost}/api/report-payment-recaps`,
                headers: {
                    Authorization: `Bearer ${document
                        .querySelector('meta[name="api-token"]')
                        .getAttribute("content")}`,
                    "Content-Type": "application/json",
                },
                then: (response) => {
                    console.log("API Response:", response); // Debugging

                    // Pastikan response memiliki data
                    if (
                        !response ||
                        !response.data ||
                        !Array.isArray(response.data.data)
                    ) {
                        console.error("Error: Data is not an array", response);
                        return [];
                    }

                    return response.data.data.map((item) => [
                        item.kecamatan || "Unknown",
                        item.total,
                    ]);
                },
                total: (response) => response.data.total || 0, // Ambil total dari API pagination
            },
            width: "auto",
            fixedHeader: true,
        }).render(tableContainer);
    }
}
document.addEventListener("DOMContentLoaded", function (e) {
    new ReportPaymentRecaps();
});
