<?

//////////////
// http://goi.ifreshy.com/lib/update_column.php?mode=insert&upfilename=20240405_customer_code.csv&upfield=c_driveruid
//////////////

include getenv("DOCUMENT_ROOT")."/include/session_include.php";

$time_start = microtime(true);

// Level 1 이하만 사용 가능
$func->checkLevelModal(1);

// Result Log
$GETDIR = getenv("DOCUMENT_ROOT");
$setDIRNAME = $GETDIR."/lib/log/".date('Ym');
$setFILENAME = $setDIRNAME."/".date("YmdHis").".log";

if (!is_dir($setDIRNAME)) {
    mkdir($setDIRNAME, 0755, true);
}

$addCronLog = file_get_contents($setFILENAME);

$addCronLog .= "[upfilename=$upfilename][upfield=$upfield]\n";

// c_is_transfer
$updated = false;
// ################# 차후 uptype 에 따른 if 구분이 필요함
// echo "[action=$action]";
// log file upload
if ($mode == "insert" && $upfilename != "" && $upfield != "") {
	
	$uploaddir = getenv("DOCUMENT_ROOT").'/upload/'; 	
	
	$existFlag = file_exists($uploaddir.$upfilename);
	
	if (!file_exists($uploaddir.$upfilename)) {
		echo "The file ".$uploaddir.$upfilename." does not exist";
	}

	//$rt = chmod ($uploaddir.$upfilename, 0755);

	$lineCnt = 1;
	$successRowCnt = 0;
		
	if (($handle = fopen($uploaddir.$upfilename, "r")) !== FALSE) {
	    while (($getCSV = fgetcsv($handle, 2000, ",")) !== FALSE) {
								
						if ($lineCnt >= 2) {
									// Get customer Info
									
									//$d_accountnotmp = str_replace(" ", "", trim($getCSV[0])); // d_accountno
									$d_accountno = preg_replace('/[^A-Za-z0-9\-]/', '', trim($getCSV[0]));
									
									//$d_name = str_replace("\\", "", trim($getCSV[1])); // d_name
									$updateTMPtmp = str_replace("'", "''", trim($getCSV[1])); // update field
									$updateTMP = preg_replace('/[^A-Za-z0-9\-]/', '', $updateTMPtmp);
									
									$qry_customer = "SELECT * FROM tbl_customer WHERE c_accountno = '".$d_accountno."' ";
									$rt_customer = $jdb->fQuery($qry_customer, "query error");
									//echo "[$qry_customer]<br>";
									
									if ($rt_customer[0]) $fontColor = "black";
									else $fontColor = "red";

									if ($rt_customer[0]) {

										if ($upfield == "c_status") {
											$qry = "UPDATE tbl_customer SET c_status='".$updateTMP."' WHERE c_accountno = '".$d_accountno."'";
											$updated = true;
										} else if ($upfield == "c_payableto") {
											$qry = "UPDATE tbl_customer SET c_payableto='".$updateTMP."' WHERE c_accountno = '".$d_accountno."'";
											$updated = true;
										} else if ($upfield == "c_paymenttype") {
											$updateTMP = strtoupper($updateTMP);
											$qry = "UPDATE tbl_customer SET c_paymenttype='".$updateTMP."' WHERE c_accountno = '".$d_accountno."'";
											$updated = true;
										} else if ($upfield == "c_paymentcycle") {
											$qry = "UPDATE tbl_customer SET c_paymentcycle='".$updateTMP."' WHERE c_accountno = '".$d_accountno."'";
											$updated = true;
										} else if ($upfield == "c_rate") {
											$qry = "UPDATE tbl_customer SET c_rate='".$updateTMP."' WHERE c_accountno = '".$d_accountno."'";
										} else if ($upfield == "c_sludge") {
											// 2025-12-09 history 안건드리기
											// $qry1 = "UPDATE tbl_daily SET d_sludge='".$updateTMP."' WHERE d_accountno = '".$d_accountno."'";
											// $jdb->nQuery($qry1, "Update error");
											
											$qry = "UPDATE tbl_customer SET c_sludge='".$updateTMP."' WHERE c_accountno = '".$d_accountno."'";
											$updated = true;
										} else if ($upfield == "c_mainvolume") {
											$qry = "UPDATE tbl_customer SET c_mainvolume='".$updateTMP."' WHERE c_accountno = '".$d_accountno."'";
											$updated = true;
										} else if ($upfield == "c_driveruid") {
											//$qry1 = "UPDATE tbl_daily SET d_driveruid='".$updateTMP."' WHERE d_accountno = '".$d_accountno."'";
											//$jdb->nQuery($qry1, "Update error");
											
											$qry = "UPDATE tbl_customer SET c_driveruid='".$updateTMP."' WHERE c_accountno = '".$d_accountno."'";
											$updated = true;
										} else if ($upfield == "c_hstno") {
											//$qry1 = "UPDATE tbl_daily SET d_driveruid='".$updateTMP."' WHERE d_accountno = '".$d_accountno."'";
											//$jdb->nQuery($qry1, "Update error");
											
											$qry = "UPDATE tbl_customer SET c_hstno='".$updateTMP."' WHERE c_accountno = '".$d_accountno."'";
											$updated = true;
										}
										
										$jdb->nQuery($qry, "Update error");
										//echo "[$qry]<br>";

										// ERP 전송 전 transfer flag setting
										if ($updated) {
											$q = "UPDATE tbl_customer SET c_is_transfer='N' WHERE c_accountno='".$d_accountno."'";
											$jdb->nQuery($q, "Update error: c_is_transfer");
										}

										$qry_customera = "SELECT * FROM tbl_customer WHERE c_accountno = '".$d_accountno."' ";
										$rt_customera = $jdb->fQuery($qry_customera, "query error");

									}
									
									if ($updateTMP != $rt_customera[$upfield]) $fontColor = "#00DD37";

									// ==================== 
									// Integration to ERP 
									// ====================
									$columns = array();
									$values = array();
									$columns[] = $upfield;
									$columns[] = "c_accountno";
									$values[] = $updateTMP;
									$values[] = $d_accountno;
									
									$erp = new ErpApi();

									try {
										// ERP로 전송 (payload 내부에서 자동 매핑)
										$erp->updateCustomerFromMis($columns, $values, $lguserid);

										// 성공 시 플래그 & 로그
										$jdb->uQuery("tbl_customer", ["c_is_transfer"], ["Y"], " WHERE c_accountno = '$d_accountno'");

									} catch (Exception $e) {
										// 여기서는 아무것도 안함
									}

									//
									echo "<font color=$fontColor>[cnt=$lineCnt][ACCOUNTNO=$d_accountno][RNAME FILE/DB =".$d_name." / ".$rt_customer['c_name']."][".$upfield." FILE/DB/AFTER=".$updateTMP." / ".$rt_customer[$upfield]." / ".$rt_customera[$upfield]."]</font><br>";
									$addCronLog .= "[cnt=$lineCnt][ACCOUNTNO=$d_accountno][RNAME FILE/DB =".$d_name." / ".$rt_customer['c_name']."][".$upfield." FILE/DB/AFTER=".$updateTMP." / ".$rt_customer[$upfield]." / ".$rt_customera[$upfield]."]\n";
						}					
						
						//if ($lineCnt == 1000) break;
		
						$lineCnt++;

	    }
	    fclose($handle);
	}
	
}

file_put_contents($setFILENAME, $addCronLog, FILE_APPEND);

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

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