/*
 * CM_MONTHEND.pgc - cm 모듈 서비스 CM_MONTHEND (one service = one file).
 * Split out of the former inline cm_svr.pgc; runs on the caller's XA
 * branch (no EXEC SQL CONNECT). Advertised by cm_svr at tpsvrinit.
 */
#include "CM_MONTHEND.h"

/* ----- service-local pure helper(s) ----- */
static int cm_is_leap(int y) { return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0); }

static int cm_mdays(int y, int m)
{
    static const int d[] = {31,28,31,30,31,30,31,31,30,31,30,31};
    if (m < 1 || m > 12) return 30;
    if (m == 2 && cm_is_leap(y)) return 29;
    return d[m - 1];
}


/* 7. CM_MONTHEND - 월말일 계산 (순수 계산). */
void CM_MONTHEND(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char in[16], out[16];
    int y, m, d, last;
    gets_(b, T_STR1, in, sizeof(in));
    if (sscanf(in, "%d-%d-%d", &y, &m, &d) != 3) FAIL(b);
    last = cm_mdays(y, m);
    sprintf(out, "%04d-%02d-%02d", y, m, last);
    sets_(b, T_STR3, out);
    setl(b, T_ARG1, last);
    OK(b);
}
