const WhmcsApi = require('whmcs-node').default
const { config } = require("../config/whmcsApi");
const db = require("../models/index");

const moment = require("moment")
// require('moment/locale/id');

// moment.locale('id');

const getInvoice = async (inv_id, name, phoneNumber, address, company) => {
    const whmcs = new WhmcsApi(config);
    const parameters = {
        invoiceid: inv_id
    };
    const invoice = await whmcs.billing.getInvoice(parameters)
    const client = await getClientProfile(invoice.userid)
    const data = {
        client_name     : name || client.fullname,
        client_phone    : phoneNumber || client.phonenumber,
        client_address  : address || client.address1,
        inv_id          : invoice.invoiceid,
        inv_status      : invoice.status,
        inv_date        : moment(invoice.date).format('dddd, DD MMMM YYYY'),
        inv_duedate     : moment(invoice.duedate).format('dddd, DD MMMM YYYY'),
        sub_total       : convertToRupiah(invoice.subtotal),
        total           : convertToRupiah(invoice.total),
        ppn             : convertToRupiah(invoice.tax),
        credit          : convertToRupiah(invoice.credit),
        balance         : convertToRupiah(invoice.balance),
        company         : client.companyname,
        items           : (invoice.items.item).map((item) => {
            return {
                id          : item.id,
                description : item.description,
                amount      : convertToRupiah(item.amount)
            }
        }),
        transaction : []
    }
    if(invoice.transactions) {
        data.transaction = (invoice.transactions.transaction).map((transaction) => {
            return {
                id          : transaction.id,
                gateway     : transaction.gateway,
                date        : moment(transaction.date).format('dddd, DD MMMM YYYY'),
                description : transaction.description,
                amount      : convertToRupiah(transaction.amountin),
            }
        }) 
    }
    return data
}
function convertToRupiah(number) {
    const numberValue = parseFloat(number);
    return numberValue.toLocaleString('id-ID', { style: 'currency', currency: 'IDR' });
}

const getClientProfile = async (clientid) => {
    const whmcs = new WhmcsApi(config);
    const parameters = {
        clientid: clientid
    };
    const client = await whmcs.client.getClientsDetails(parameters)
    return client
}

module.exports = { getInvoice }