<?php

///////////////////////////////////////////////////
// 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/runDailyReportNew.php?PUTDAY=20250612
//
///////////////////////////////////////////////////

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] ?? "";
	$getYesterday = $argv[3] ?? date('Ymd', strtotime('-1 days'));

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

    $ROWCNT = $_GET['ROWCNT'] ?? "";
    $LIMITCNT = $_GET['LIMITCNT'] ?? "";
    if (!empty($_GET['PUTDAY'])) {
        $getYesterday = $_GET['PUTDAY'];
    } else {
        $getYesterday = date('Ymd', strtotime('-1 days'));
    }

    $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();

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



//////////////////////////////////
// 월 단위 배치
//////////////////////////////////

/*
// 월단위 루프 시작
$yyear = 2026;	// 2025는 1~5까지만

for($ii=1; $ii<= 12; $ii++) {
		$mmon = sprintf("%02d", $ii);

		if ($ii == 4) break;
		
		for($jj=1; $jj<= 31; $jj++) {
			$dday = sprintf("%02d", $jj);
			
			if ($jj == 17) break;
			
			if (checkdate((int)$mmon, (int)$dday, (int)$yyear)) {
								echo "<br><br>####[OO][".$yyear.$mmon.$dday."]<br>";
					
								$getYesterday = $yyear.$mmon.$dday;
			
			///////////////////////
			///////////////////////
			///////////////////////					

// 월단위 루프 끝
*/






											// Get Driver Info
											//$qry_driver = "SELECT * FROM tbl_driver WHERE dr_status = 'A' ORDER by dr_uid ASC ";
											$qry_driver = "SELECT * FROM tbl_driver WHERE dr_status != '' ORDER by dr_uid ASC ";
											$rt_driver = $jdb->nQuery($qry_driver, "list error"); 

											while($lt_driver=mysqli_fetch_array($rt_driver, MYSQLI_ASSOC)) {
														//$driverArrayTmp = array($lt_driver['m_uid'] => $lt_driver['m_initial']);	
														//$driverArray += $driverArrayTmp;
														//$titleSTR .= "<th class='td-80' style='text-align:center;'>".$lt_driver['m_initial']."</th>";
														
														//total record
														$qry_row = "SELECT COUNT(d_uid) 
																				FROM tbl_daily 
																				WHERE d_druid = '".$lt_driver['dr_uid']."' AND d_orderdate = '".$getYesterday."' AND d_status = 'F' ";
														$row_cnt=$jdb->rQuery($qry_row, "record query error");


														if ($row_cnt >= 1) {

																$qry_qty = "SELECT d_druid, 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_druid = '".$lt_driver['dr_uid']."' AND d_orderdate = '".$getYesterday."' AND d_status = 'F' ";
																$rt_qry = $jdb->fQuery($qry_qty, "list error");
																echo $ENT."[$qry_qty]$ENT";
																
																$rdd_quantity = $rt_qry['totquantity'];
																$rdd_call = $rt_qry['callno'];
																$rdd_visit = $rt_qry['visitno'];
																
														}
														else {
																$rdd_quantity = 0.00;
																$rdd_call = 0;
																$rdd_visit = 0;
														}

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

														$columns[] = "rdd_orderdate";
														$columns[] = "rdd_druid";
														$columns[] = "rdd_drinitial";
														$columns[] = "rdd_quantity";
														$columns[] = "rdd_call";
														$columns[] = "rdd_visit";
														$columns[] = "rdd_date";

														$values[] = $getYesterday;
														$values[] = $lt_driver['dr_uid'];
														$values[] = trim($lt_driver['dr_initial']);
														$values[] = $rdd_quantity;
														$values[] = $rdd_call;
														$values[] = $rdd_visit;
														$values[] = date("YmdHis");

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

														$qry_rd = "SELECT rdd_druid	FROM tbl_report_daily_driver
																		WHERE rdd_orderdate = '".$getYesterday."' AND rdd_druid = '".$lt_driver['dr_uid']."' " ;
														$rt_rd = $jdb->fQuery($qry_rd, "query error");

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

														if ($rt_rd['rdd_druid'] != "") {
																$jdb->uQuery("tbl_report_daily_driver", $columns, $values, " 
																							WHERE rdd_orderdate = '".$getYesterday."' AND rdd_druid = '".$rt_rd['rdd_druid']."' ");
																$max_id = $rt_rd['rdd_druid'];
																echo "[UPDATE ".$rt_rd['rdd_druid']."]$ENT$ENT";
														}
														else {
																$jdb->iQuery("tbl_report_daily_driver", $columns, $values);
															
																$qry_max = "SELECT max(rdd_druid) FROM tbl_report_daily_driver ";
																$max_id = $jdb->rQuery($qry_max, "max query error");
																echo "[INSERT]$ENT$ENT";
														}
														
														/*
														// 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 = '".$lt_driver['m_uid']."' 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";
														$rt_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 = '".$lt_driver['m_uid']."' 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";
														$rt_CORSIA = $jdb->fQuery($qry_CORSIA, "query error");
															
														//$qry_up = "UPDATE tbl_report_daily 
														//						SET rd_quantity_iscc = '".$rt_ISCC['ISCC']."' WHERE rd_uid = '".$max_id."' ";

														//$qry_up = "UPDATE tbl_report_daily 
														//						SET rd_quantity_corsia = '".$rt_CORSIA['CORSIA']."' WHERE rd_uid = '".$max_id."' ";
														
														$qry_up = "UPDATE tbl_report_daily 
																				SET rd_quantity_iscc = '".$rt_ISCC['ISCC']."' , rd_quantity_corsia = '".$rt_CORSIA['CORSIA']."'
																				WHERE rd_uid = '".$max_id."' ";																				
														
														echo "[".$qry_up."]".$ENT;
														$jdb->nQuery($qry_up, "update error");
														
														echo "[DATE=".$getYesterday."][DRIVER=".$lt_driver['m_uid']."][QTY=".$rd_quantity."][ISCC=".$rt_ISCC['ISCC']."][CORSIA=".$rt_CORSIA['CORSIA']."]".$ENT.$ENT;
														*/
											}	


/*
// 월단위 루프 시작

			}
			else {
					echo "<br><br>####[XX][".$yyear.$mmon.$dday."]<br>";
			}

		}

}

// 월단위 루프 끝
*/


// For service monitoring
$logName =  $GETDIR."/lib/access.log";
$funcMsg = "ACTION[Cron - Finished - Daily Driver 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;    
    }
    

}

?>
