/*
 * ac_settle_dbio.pgc - ac 모듈 DB 접근 함수 세트 (ac_settle_dbio), archived into libacdbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "ac_settle_dbio.h"

long acdb_insert_settlement(long pid, const char *merch, long net, const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_id, h_pid = pid, h_net = net;
    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('settlement_seq') INTO :h_id;
    if (sqlca.sqlcode < 0) return -1;
    EXEC SQL INSERT INTO settlement (settlement_id, purchase_id, merchant_id, net, biz_date)
        VALUES (:h_id, :h_pid, :h_merch, :h_net, :h_bizdate);
    if (sqlca.sqlcode < 0) { userlog("acdb_insert_settlement FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); return -1; }
    return h_id;
}

long acdb_settle_net_sum(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_v = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL SELECT coalesce(sum(net),0) INTO :h_v FROM settlement WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { userlog("acdb_settle_net_sum FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); return -1; }
    return h_v;
}
