<?

///////////////////////////////////////////////////
// CRON (매일 2시 3분)
///////////////////////////////////////////////////
//
// /usr/local/bin/php -q /home/goiintra/public_html/lib/runDailyReport.php "0" "2000"
// /usr/local/bin/php -q /home2/ifreshy/public_html/goi/lib/runDailyReport.php "0" "2000"
// /usr/local/bin/php -q /home2/ifreshy/public_html/goi/lib/runDailyReport.php 
//         >> /home2/ifreshy/public_html/goi/lib/cronlog/`date +\%Y\%m\%d\%H\%M\%S`-cron-dr.log 2>&1
// ifreshy 는 cron 22시면 실제 23시에 동작
// 
///////////////////////////////////////////////////
//
// 웹에서 일자별 수작업 (PUTDAY 에 원하는 일자 입력)
//
// - 25라인 막고 26라인 오픈
// - 70라인 막을것. $getYesterday 항목
// - ISCC, CORSIA 만 업데이트 할거면 123,127라인 막을것
//
// https://goi.ifreshy.com/lib/runDailyReport.php?PUTDAY=20250612
//
///////////////////////////////////////////////////

date_default_timezone_set('America/Toronto');

$time_start = microtime(true);

$mode = "SHELL";
//$mode = "WEB";

if ($mode == "SHELL") {
	if(stristr(gethostname(), 'goiintranet.com') === FALSE) $GETDIR = "/home2/ifreshy/public_html/goi";
	else $GETDIR = "/home/goiintra/public_html";
	
	//$GETDIR = "/home/goiintra/public_html";
	
	if ($argv[1] != "") $ROWCNT = trim($argv[1]);
	if ($argv[2] != "") $LIMITCNT = trim($argv[2]);

	$ENT = "\n";
}
else {
	$GETDIR = getenv("DOCUMENT_ROOT");
	
	$ROWCNT = $_GET['ROWCNT'];
	$LIMITCNT = $_GET['LIMITCNT'];
	
	$getYesterday = $_GET['PUTDAY'];
	
	$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();


$getYesterday = date('Ymd', strtotime('-1 days')); // 어제일자
//$getToday = date('Ymd');

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

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


$qry = "SELECT d_driveruid, SUM(d_quantity) AS totquantity, 
				COUNT(IF(d_ordertype='R',d_ordertype,NULL)) AS callno, COUNT(d_uid) AS visitno
				FROM tbl_daily
				WHERE d_status = 'F' AND d_orderdate = '".$getYesterday."'
				GROUP BY d_driveruid, d_orderdate
				ORDER by d_orderdate asc, d_driveruid asc" ;
$result = $jdb->nQuery($qry, "list error");
echo "[$qry]$ENT";

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

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

			$columns[] = "rd_orderdate";
			$columns[] = "rd_driveruid";
			$columns[] = "rd_quantity";
			$columns[] = "rd_call";
			$columns[] = "rd_visit";
			$columns[] = "rd_date";

			$values[] = $getYesterday;
			$values[] = $list['d_driveruid'];
			$values[] = $list['totquantity'];
			$values[] = $list['callno'];
			$values[] = $list['visitno'];
			$values[] = date("YmdHis");

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

			$qry_rd = "SELECT rd_uid	FROM tbl_report_daily
							WHERE rd_orderdate = '".$getYesterday."' AND rd_driveruid = '".$list['d_driveruid']."' " ;
			$rt_rd = $jdb->fQuery($qry_rd, "query error");

			echo "[".$rt_rd['rd_uid']."][$qry_rd]$ENT";

			if ($rt_rd['rd_uid'] != "") {
					$jdb->uQuery("tbl_report_daily", $columns, $values, " where rd_uid = '".$rt_rd['rd_uid']."' ");
					$max_id = $rt_rd['rd_uid'];
			}
			else {
					$jdb->iQuery("tbl_report_daily", $columns, $values);
				
					$qry_max = "select max(rd_uid) from tbl_report_daily ";
					$max_id = $jdb->rQuery($qry_max, "max query error");
			}


			// Update ISCC & CORSIA
			$qry_ISCC = "SELECT SUM(d_quantity) AS ISCC	FROM tbl_daily 
								WHERE d_customeruid != '' AND d_status = 'F' 
								AND (d_customeruid IN (SELECT c.c_uid FROM tbl_customer c WHERE c.c_driveruid = '".$list['d_driveruid']."' AND (c.c_status = 'A' OR c.c_status = 'I')))
								AND d_form_eu != '' AND d_form_eu <= d_orderdate AND d_orderdate = '".$getYesterday."' ";
			echo "[$qry_ISCC]$ENT";
			$qry_ISCC = $jdb->fQuery($qry_ISCC, "query error");

			$qry_CORSIA = "SELECT SUM(d_quantity) AS CORSIA	FROM tbl_daily 
								WHERE d_customeruid != '' AND d_status = 'F' 
								AND (d_customeruid IN (SELECT c.c_uid FROM tbl_customer c WHERE c.c_driveruid = '".$list['d_driveruid']."' AND (c.c_status = 'A' OR c.c_status = 'I')))
								AND d_form_corsia != '' AND d_form_corsia <= d_orderdate AND d_orderdate = '".$getYesterday."' ";
			echo "[$qry_CORSIA]$ENT";
			$qry_CORSIA = $jdb->fQuery($qry_CORSIA, "query error");
				
			$qry_up = "UPDATE tbl_report_daily 
									SET rd_quantity_iscc = '".$qry_ISCC['ISCC']."' , rd_quantity_corsia = '".$qry_CORSIA['CORSIA']."'
									WHERE rd_uid = '".$max_id."' ";
			echo "[$qry_up]$ENT";
			$jdb->nQuery($qry_up, "update error");
	
}



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

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

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

?>




<?

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() {

	
		if(stristr(gethostname(), 'goiintranet.com') === FALSE) {
			//echo $_SERVER['HTTP_HOST']."NOOOOOOOOOOOOO";
			// Test Server
			$DB_HOST = "localhost";
			$DB_NAME = "ifreshy_goi";
			$DB_USER = "ifreshy_goi";
			$DB_PASSWORD = "L0C2CKN5GHHY";	

		}
		else {

			//echo $_SERVER['HTTP_HOST']."YESSSSSSSSSSSSSSSS";
			// Service Server			
			$DB_HOST = "localhost";
			$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;    
    }
    

}

?>
