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

/* 상태별 건수를 커서로 순회하여 정산완료(S) 건수만 추출. */
long acdb_status_settled_count(const char *bizdate)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_st[8];
    long h_cnt, settled = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE psc CURSOR FOR
        SELECT status, count(*) FROM purchase WHERE biz_date = :h_bizdate GROUP BY status;
    EXEC SQL OPEN psc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH psc INTO :h_st, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE psc; return -1; }
        if (h_st[0] == 'S') settled = h_cnt;
    }
    EXEC SQL CLOSE psc;
    return settled;
}

/* 미완결(A/H/M) 건수 - IN 집합 필터. */
long acdb_status_open_count(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 count(*) INTO :h_v FROM purchase
        WHERE biz_date = :h_bizdate AND status IN ('A', 'H', 'M');
    if (sqlca.sqlcode < 0) return -1;
    return h_v;
}
