<?php

///////////////////////////////////////////////////
// CRON (매월 1일 02:01 실행 예정)
///////////////////////////////////////////////////
//
// /usr/local/bin/php -q /home/goiintra/public_html/lib/runMonthlyCustomerReport.php
// /usr/local/bin/php -q /home2/ifreshy/public_html/goi/lib/runMonthlyCustomerReport.php 
//         >> /home2/ifreshy/public_html/goi/lib/cronlog/`date +\%Y\%m\%d\%H\%M\%S`-cron-customer.log 2>&1
//
///////////////////////////////////////////////////

date_default_timezone_set('America/Toronto');

$time_start = microtime(true);

$mode = (PHP_SAPI === 'cli') ? "SHELL" : "WEB";

if ($mode == "SHELL") {
    $GETDIR = "/var/www/html";
    $ENT = "\n";
} else {
    $GETDIR = getenv("DOCUMENT_ROOT");
    $ENT = "<br>";
}

echo "####[START Customer Report]####$ENT";

include_once $GETDIR . "/include/function_class.php";
include_once $GETDIR . "/include/arrayinfo.php";
require_once __DIR__ . '/../lib/runMonthlyReport.php';

$func = new Func();
$jdb = new JDB();

// 이전달 계산
$dt = new DateTime();
$day = $dt->format('j');
$dt->modify('first day of -1 month');
$dt->modify('+' . (min($day, $dt->format('t')) - 1) . ' days');
$getLastMonth = $dt->format('Ym');

$getToday = date('Ymd');

// 로그 시작
$logName = $GETDIR . "/lib/access.log";

$funcMsg = "ACTION[Cron - Start - Customer Report for {$getLastMonth}]";
$func->PwriteLog($logName, $funcMsg);

// 프로시저 실행
echo "[Info] Running sp_generate_customer_monthly_report('$getLastMonth') ...$ENT";

$qry_call = "CALL sp_generate_customer_monthly_report('$getLastMonth')";

$result = @mysqli_query($jdb->DBConn, $qry_call);

if (!$result) {
    $errMsg = "Procedure execution error | " . mysqli_error($jdb->DBConn);
    echo "[ERROR] $errMsg$ENT";
    $func->PwriteLog($logName, "ERROR[Customer Report Generation] " . $errMsg);
} else {
    echo "[SUCCESS] Procedure executed successfully for month {$getLastMonth}$ENT";
    $func->PwriteLog($logName, "SUCCESS[Customer Report Generation] Month={$getLastMonth}");
}

// 로그 완료
$funcMsg = "ACTION[Cron - Finished - Customer Report for {$getLastMonth}]\n";
$func->PwriteLog($logName, $funcMsg);

$time_end = microtime(true);
$timeStr = "Running Time: " . round(($time_end - $time_start), 2) . " sec";
echo "####[END][$timeStr]####$ENT";

?>
