/*
 * ac_fee_dbio.pgc - fee-adjust / withholding / tax-invoice DB access (libacdbio.a).
 */
#include <string.h>
#include <userlog.h>
#include "ac_dbio.h"

long acdb_insert_fee_adj(long pid, long delta, const char *reason, const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_id, h_pid = pid, h_delta = delta;
    char h_reason[128], h_bizdate[16];
    EXEC SQL END DECLARE SECTION;

    strncpy(h_reason, reason, sizeof(h_reason) - 1);   h_reason[sizeof(h_reason)-1] = 0;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate) - 1); h_bizdate[sizeof(h_bizdate)-1] = 0;

    EXEC SQL SELECT nextval('ac_feeadj_seq') INTO :h_id;
    if (sqlca.sqlcode < 0) return -1;

    EXEC SQL INSERT INTO ac_fee_adj (adj_id, purchase_id, delta, reason, biz_date)
        VALUES (:h_id, :h_pid, :h_delta, :h_reason, :h_bizdate);
    if (sqlca.sqlcode < 0) {
        userlog("acdb_insert_fee_adj FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    return h_id;
}

long acdb_insert_wht(long pid, long tax, const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_id, h_pid = pid, h_tax = tax;
    char h_bizdate[16];
    EXEC SQL END DECLARE SECTION;

    strncpy(h_bizdate, bizdate, sizeof(h_bizdate) - 1); h_bizdate[sizeof(h_bizdate)-1] = 0;

    EXEC SQL SELECT nextval('ac_wht_seq') INTO :h_id;
    if (sqlca.sqlcode < 0) return -1;

    EXEC SQL INSERT INTO ac_wht (wht_id, purchase_id, tax_amount, biz_date)
        VALUES (:h_id, :h_pid, :h_tax, :h_bizdate);
    if (sqlca.sqlcode < 0) {
        userlog("acdb_insert_wht FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    return h_id;
}

long acdb_insert_tax_invoice(long pid, const char *merch, long supply, long vat,
                             const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_id, h_pid = pid, h_supply = supply, h_vat = vat;
    char h_merch[64], h_bizdate[16];
    EXEC SQL END DECLARE SECTION;

    strncpy(h_merch, merch, sizeof(h_merch) - 1);       h_merch[sizeof(h_merch)-1] = 0;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate) - 1); h_bizdate[sizeof(h_bizdate)-1] = 0;

    EXEC SQL SELECT nextval('ac_taxinv_seq') INTO :h_id;
    if (sqlca.sqlcode < 0) return -1;

    EXEC SQL INSERT INTO ac_tax_invoice (inv_id, purchase_id, merchant_id, supply, vat, biz_date)
        VALUES (:h_id, :h_pid, :h_merch, :h_supply, :h_vat, :h_bizdate);
    if (sqlca.sqlcode < 0) {
        userlog("acdb_insert_tax_invoice FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    return h_id;
}
