/*
 * ac_quarter_batch.pgc - ac 분기별 매입 집계 (단건 집계 배치, XA).
 * 영업일이 속한 연도의 분기별 매출 합계를 한 번의 집계로 산출한다.
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction, aggregate(s) run on the biz_date, then tpcommit drives XA 2PC.
 * Usage: ac_quarter_batch [YYYY-MM-DD]
 */
EXEC SQL INCLUDE ac_quarter_batch;

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_q1, h_q2, h_q3, h_q4;
    int h_yr;
    EXEC SQL END DECLARE SECTION;

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

    if (tpinit(NULL) < 0) { fprintf(stderr, "tpinit FAIL: %s\n", tpstrerror(tperrno)); return 1; }
    if (tpopen() < 0)     { fprintf(stderr, "tpopen FAIL: %s\n", tpstrerror(tperrno)); return 1; }
    if (tpbegin(60, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL SELECT coalesce(sum(amount) FILTER (WHERE extract(quarter from biz_date) = 1),0),
                    coalesce(sum(amount) FILTER (WHERE extract(quarter from biz_date) = 2),0),
                    coalesce(sum(amount) FILTER (WHERE extract(quarter from biz_date) = 3),0),
                    coalesce(sum(amount) FILTER (WHERE extract(quarter from biz_date) = 4),0)
        INTO :h_q1, :h_q2, :h_q3, :h_q4 FROM purchase WHERE extract(year from biz_date) = :h_yr;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "ac_quarter_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> ac_quarter_batch COMMIT: year=%d q1=%ld q2=%ld q3=%ld q4=%ld\n", h_yr, h_q1, h_q2, h_q3, h_q4);

    tpclose(); tpterm();
    return 0;
}
