<?php

///////////////////////////////////////////////////
// CRON (매월 2시 1분)
///////////////////////////////////////////////////
//
// /usr/local/bin/php -q /home/goiintra/public_html/lib/runMonthlyReport.php "0" "2000"
// /usr/local/bin/php -q /home2/ifreshy/public_html/goi/lib/runMonthlyReport.php "0" "2000"
// /usr/local/bin/php -q /home2/ifreshy/public_html/goi/lib/runMonthlyReport.php 
//         >> /home2/ifreshy/public_html/goi/lib/cronlog/`date +\%Y\%m\%d\%H\%M\%S`-cron-mr.log 2>&1
// ifreshy 는 cron 22시면 실제 23시에 동작
//
///////////////////////////////////////////////////


date_default_timezone_set('America/Toronto');

$time_start = microtime(true);

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

if ($mode == "SHELL") {
    $GETDIR = "/var/www/html";

    $ROWCNT = $argv[1] ?? "";
    $LIMITCNT = $argv[2] ?? "";

    $ENT = "\n";
} else {
    $GETDIR = getenv("DOCUMENT_ROOT");

    $ROWCNT = $_GET['ROWCNT'] ?? "";
    $LIMITCNT = $_GET['LIMITCNT'] ?? "";

    $ENT = "<br>";
}

if ($ROWCNT != "" && $LIMITCNT != "") $add_qry = " LIMIT $ROWCNT, $LIMITCNT";
else $add_qry = "";

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

// For Web (/home2/ifreshy/public_html/goi)

include_once $GETDIR . "/include/function_class.php";
include_once $GETDIR . "/include/arrayinfo.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');


//echo "[$getForecastDay][".$_SERVER["REMOTE_ADDR"]."]";exit;


// For service monitoring
$logName =  $GETDIR."/lib/access.log";
$funcMsg = "ACTION[Cron - Start - Account Report]";
$func -> PwriteLog($logName, $funcMsg);


////////////////////////////
// 월별 드라이버별 New Account
////////////////////////////

$qry_new = "SELECT SUBSTRING(c_createddate, 1, 6) AS runmonth, c_driveruid, COUNT(c_uid) AS accountnew
						FROM tbl_customer
						WHERE (c_status = 'A' OR c_status = 'I') AND SUBSTRING(c_createddate, 1, 6) = '".$getLastMonth."'
						GROUP BY SUBSTRING(c_createddate, 1, 6) , c_driveruid
						ORDER BY SUBSTRING(c_createddate, 1, 6) DESC, c_driveruid+0 DESC " ;
$rt_new = $jdb->nQuery($qry_new, "list error");
echo "[NEW][$qry_new]$ENT";

$columns = array();
$values = array();
			
while($list=mysqli_fetch_array($rt_new, MYSQLI_ASSOC)) {

			unset ($columns);
			unset ($values);

			$columns[] = "ra_month";
			$columns[] = "ra_driveruid";
			//$columns[] = "ra_account";
			$columns[] = "ra_accountnew";
			//$columns[] = "ra_accountia";
			$columns[] = "ra_date";

			$values[] = $list['runmonth'];
			$values[] = $list['c_driveruid'];
			$values[] = $list['accountnew'];;
			$values[] = date("YmdHis");

			//for ($i=0; $i < count($columns); $i++)
			//echo "IN[$columns[$i]][$values[$i]]<br>";
			//exit;	

			$qry_ra = "SELECT ra_uid	FROM tbl_report_account
							WHERE ra_month = '".$list['runmonth']."' AND ra_driveruid = '".$list['c_driveruid']."' " ;
			$rt_ra = $jdb->fQuery($qry_ra, "query error");

			//echo "####[".$rt_rd['rd_uid']."][$qry_rd]####<br>";

			if ($rt_ra['ra_uid'] != "") $jdb->uQuery("tbl_report_account", $columns, $values, " where ra_uid = '".$rt_ra['ra_uid']."' ");
			else $jdb->iQuery("tbl_report_account", $columns, $values);

}



////////////////////////////
// 월별 드라이버별 Inactive Account
////////////////////////////

$qry_ia = "SELECT SUBSTRING(c_inactivedate, 1, 6) AS runmonth, c_driveruid, COUNT(c_uid) AS accountia
						FROM tbl_customer
						WHERE (c_status = 'I') AND SUBSTRING(c_inactivedate, 1, 6) = '".$getLastMonth."'
						GROUP BY SUBSTRING(c_inactivedate, 1, 6) , c_driveruid
						ORDER BY SUBSTRING(c_inactivedate, 1, 6) DESC, c_driveruid+0 DESC " ;
$rt_ia = $jdb->nQuery($qry_ia, "list error");
echo "[INACTIVE][$qry_ia]$ENT";

			
while($list=mysqli_fetch_array($rt_ia, MYSQLI_ASSOC)) {

			unset ($columns);
			unset ($values);

			$columns[] = "ra_month";
			$columns[] = "ra_driveruid";
			//$columns[] = "ra_account";
			//$columns[] = "ra_accountnew";
			$columns[] = "ra_accountia";
			$columns[] = "ra_date";

			$values[] = $list['runmonth'];
			$values[] = $list['c_driveruid'];
			$values[] = $list['accountia'];;
			$values[] = date("YmdHis");

			//for ($i=0; $i < count($columns); $i++)
			//echo "IN[$columns[$i]][$values[$i]]<br>";
			//exit;	

			$qry_ra = "SELECT ra_uid	FROM tbl_report_account
							WHERE ra_month = '".$list['runmonth']."' AND ra_driveruid = '".$list['c_driveruid']."' " ;
			$rt_ra = $jdb->fQuery($qry_ra, "query error");

			//echo "####[".$rt_rd['rd_uid']."][$qry_rd]####<br>";

			if ($rt_ra['ra_uid'] != "") $jdb->uQuery("tbl_report_account", $columns, $values, " where ra_uid = '".$rt_ra['ra_uid']."' ");
			else $jdb->iQuery("tbl_report_account", $columns, $values);

}


////////////////////////////
// 월별 드라이버별 Total Account
////////////////////////////

$qry_total = "SELECT c_driveruid, COUNT(c_uid) AS accountall
							FROM tbl_customer
							WHERE (c_status = 'A')
							GROUP BY c_driveruid
							ORDER BY c_driveruid+0 DESC " ;
$rt_total = $jdb->nQuery($qry_total, "list error");
echo "[TOTAL][$qry_total]$ENT";

			
while($list=mysqli_fetch_array($rt_total, MYSQLI_ASSOC)) {

			unset ($columns);
			unset ($values);

			$columns[] = "ra_month";
			$columns[] = "ra_driveruid";
			$columns[] = "ra_account";
			//$columns[] = "ra_accountnew";
			//$columns[] = "ra_accountia";
			$columns[] = "ra_date";

			$values[] = $getLastMonth;
			$values[] = $list['c_driveruid'];
			$values[] = $list['accountall'];;
			$values[] = date("YmdHis");

			//for ($i=0; $i < count($columns); $i++)
			//echo "IN[$columns[$i]][$values[$i]]<br>";
			//exit;	

			$qry_ra = "SELECT ra_uid	FROM tbl_report_account
							WHERE ra_month = '".$getLastMonth."' AND ra_driveruid = '".$list['c_driveruid']."' " ;
			$rt_ra = $jdb->fQuery($qry_ra, "query error");

			//echo "####[".$rt_rd['rd_uid']."][$qry_rd]####<br>";

			if ($rt_ra['ra_uid'] != "") $jdb->uQuery("tbl_report_account", $columns, $values, " where ra_uid = '".$rt_ra['ra_uid']."' ");
			else $jdb->iQuery("tbl_report_account", $columns, $values);

}



$logName =  $GETDIR."/lib/access.log";
$funcMsg = "ACTION[Cron - Finished - Account Report]\n";
$func -> PwriteLog($logName, $funcMsg);

$time_end = microtime(true);
$timeStr = "Running Time: ".($time_end - $time_start);

echo "####[END][$timeStr]####";

?>




<?php

class JDB { 
    VAR $HostName = "";                //server
    VAR $UserName = "";                //User ID
    VAR $UserPass = "";                //User Password
    VAR $DBName = "";                //Database Name
    VAR $DBConn="";                    //Database Handler

/*
** Function  : Constructor
** Input     : Database Connection Information
** Output    : None
*/
    function __construct() {

		$DB_HOST = "mis-mysql";
		$DB_NAME = "goiintra_db";
		$DB_USER = "goiintra_root";
		$DB_PASSWORD = "L0C2CKN5GHHY";
	
		$this->HostName=$DB_HOST;
		$this->UserName=$DB_USER;
		$this->UserPass=$DB_PASSWORD;
		$this->DBName=$DB_NAME;
		
		
		$this->CONNECT();

    }

/*
** Function : Connect
** Input    : None
** Output   : None
*/
    function CONNECT() {
        $this->DBConn=mysqli_connect($this->HostName, $this->UserName, $this->UserPass, $this->DBName);
        if (!$this->DBConn)            //연결실패
            $this->errMsg("Database Connection Error !!!", "");
        else                        //연결성공
            if (!(mysqli_select_db($this->DBConn, $this->DBName)))    //Database 선택 실패
                $this->errMsg("Database Select Error !!!", "");
                
        mysqli_query($this->DBConn, "SET NAMES UTF8");
        //mysqli_query($this->DBConn, "SET NAMES latin1");
        //mysqli_query($this->DBConn, "SET NAMES EUC-KR");
    }

/*
** Function  : nQuery
** Input     : Query String, Error Message
** Output    : Recordset
** Descript  : mysql_query()
*/
    function nQuery($query, $msg) {
        if (!($rlt=mysqli_query($this->DBConn, $query))) 
            $this->errMsg($msg, $query);
        return $rlt;
    }

/*
** Function : rQuery
** Input    : Query string, Error message
** Output   : Record
** Descript : mysql_result()
** 이부분은 mysql_fetch_arrary와 비슷하지만 가끔씩 쓰일때가 많아서요..넣었습니다.
*/
		function mysqli_result($res,$row=0,$col=0){ 
		    $numrows = mysqli_num_rows($res); 
		    if ($numrows && $row <= ($numrows-1) && $row >=0){
		        mysqli_data_seek($res,$row);
		        $resrow = (is_numeric($col)) ? mysqli_fetch_row($res) : mysqli_fetch_assoc($res);
		        if (isset($resrow[$col])){
		            return $resrow[$col];
		        }
		    }
		    return false;
		}


    function rQuery($query, $msg) {
        if (!($rlt=mysqli_query($this->DBConn, $query))) 
            $this->errMsg($msg, $query);

        return $this->mysqli_result($rlt, 0, 0);
    }

/*
** Function : fQuery
** Input    : Query string, Error message
** Output   : Fetched array 
** Descript : mysql_fetch_array()
** 레코드셋에서 맨 첫번째 레코드를 array로 리턴해줍니다.
** 하나의 레코드셋에서 이함수를 여러번 적용한다면..
** 자동으로 다음 레코드로 넘어가겠죠 ???
*/
    function fQuery($query, $msg) {
        if (!($rlt=mysqli_query($this->DBConn, $query))) $this->errMsg($msg, $query);
        return mysqli_fetch_array($rlt);
    }

/*
** Function : numQuery
** Input    : Query string, Error message
** Output   : The number of rows 
** Descript : mysql_num_rows()
*/
	function numQuery($query, $msg) {
		if(!($rlt=mysqli_query($this->DBConn, $query))) $this->errMsg($msg, $query);
		return mysqli_num_rows($rlt);
	}



/*
** Function : iQuery
** Input    : Table name, arrayed fields, arrayed values
** Output   : None
** Descript : Input arrayed data
*/
    function iQuery($table, $fields, $values) {
        $fields_count=count($fields);    // fileds 배열의 갯수 추출
        $values_count=count($values);    // values 배열의 갯수 추출

        // fields와 values 갯수가 맞지않을 경우 0을 return
        // 혹 프로그래밍 상에서 실수가 발생했을 경우 사용하기 위해
        if($fields_count != $values_count) 
            $this->errMsg("Input Data Error.", "Fields # : $fields_count, Value # : $values_count");

        for ($i=0; $i < $fields_count; $i++) {    // 입력된 fields와 values를 이용 퀴리 생성
            if (0 < $i) {                        // fields와 values가 2개 이상일 경우 , 자동 입력
                $fields_que.=",";
                $values_que.=",";
            }

            $fields_que.=$fields[$i];                        // fields에 해당하는 쿼리
            $values_que.="'".addslashes($values[$i])."'";    // values에 해당하는 쿼리
        }
        $this->nQuery("insert into $table ($fields_que) values ($values_que)", "[ <i>$table</i> ] Table Input Error");
    } 

/*
** Function : uQuery
** Input    : Table name, arrayed fields, arrayed values, where
** Output   : None
** Descript : update arrayed data
*/
    function uQuery($table, $fields, $values, $where="")    {
        if(is_array($fields) & is_array($values)) {                // fields와 values가 배열일 경우
            $fields_count=count($fields);                        // fileds 배열의 갯수 추출
            $values_count=count($values);                        // values 배열의 갯수 추출

            // fields와 values 갯수가 맞지않을 경우 0을 return
            // 혹 프로그래밍 상에서 실수가 발생했을 경우 사용하기 위해
            if ($fields_count != $values_count) 
                $this->errMsg("Input Data Error.", "Fields # : $fields_count, Value # : $values_count");

            for ($i=0; $i < $fields_count; $i++) {
                // insert와 달리 sub쿼리를 이용
                if (0 < $i)
                    $sub_que.=",";
                $sub_que.=$fields[$i]."='".addslashes($values[$i])."'";    // 서브 쿼리 생성
            }
        } 
        else if (!is_array($fields) & !is_array($values))     // fields와 values가 배열이 아닐 경우
            $sub_que=" ".$fields."='".addslashes($values)."' ";
        else 
            $this->errMsg("Input Data Error.", "Fields # : $fields_count, Value # : $values_count");
            
        if($where) $sub_que.=" ".$where;    // where 쿼리가 존재할 경우 입력
        $this->nQuery("update $table set $sub_que", "[ <i>$table</i> ] Table Input Error");
    }

/*
** Function : CLOSE
** Input    : None
** Output   : None
** Descript : mysql_close()
*/
    function CLOSE() {    
        mysqli_close($this->DBConn);    
        $this->DELETE();    
    }

/*
** Function : DELETE
** Input    : None
** Output   : None
** Descript : Member variable unset
*/
    function DELETE() {
        unset($this->DBConn);         unset($this->UserName); 
        unset($this->UserPass);     unset($this->HostName); 
        unset($this->DBName); 
    }

    //Print Error Message and Exit
    function errMsg($msg, $query) {    
        echo("<b>JDB Error Message !!</b><p>");
        $msg=mysqli_errno($this->DBConn)." : ".mysqli_error($this->DBConn)."<p><b>User Message</b> :<br> ".$msg."<p><b>Query String</b> :<br> ".$query;

        echo ("$msg");
        exit;    
    }
    

}

?>
