/*
 * CM_ADDDAYS.pgc - cm 모듈 서비스 CM_ADDDAYS (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_ADDDAYS.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];
}


/* 5. CM_ADDDAYS - 달력일 N일 가산 (순수 계산). */
void CM_ADDDAYS(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char in[16], out[16];
    long n, i;
    int y, m, d;
    gets_(b, T_STR1, in, sizeof(in));
    n = getl(b, T_ARG1);
    if (sscanf(in, "%d-%d-%d", &y, &m, &d) != 3) FAIL(b);
    for (i = 0; i < n; i++) {
        d++;
        if (d > cm_mdays(y, m)) { d = 1; if (++m > 12) { m = 1; y++; } }
    }
    sprintf(out, "%04d-%02d-%02d", y, m, d);
    sets_(b, T_STR3, out);
    OK(b);
}
