/*
 * ac_wht_query_dbio.pgc - ac 모듈 DB 접근 함수 세트 (ac_wht_query_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_wht_query_dbio.h"

/* 정산완료 매입에 대한 원천징수 세액 합계 (JOIN + 상태필터). */
long acdb_wht_settled_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(w.tax_amount),0) INTO :h_v
        FROM ac_wht w JOIN purchase p ON p.purchase_id = w.purchase_id
        WHERE w.biz_date = :h_bizdate AND p.status = 'S';
    if (sqlca.sqlcode < 0) return -1;
    return h_v;
}

/* 실효 원천세율(bps) = sum(tax)*10000 / sum(fee) over joined purchases. */
long acdb_wht_effective_bps(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_tax = 0, h_fee = 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(w.tax_amount),0), coalesce(sum(p.fee),0)
        INTO :h_tax, :h_fee FROM ac_wht w JOIN purchase p ON p.purchase_id = w.purchase_id
        WHERE w.biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) return -1;
    if (h_fee <= 0) return 0;
    return h_tax * 10000 / h_fee;
}
