<?php

include getenv("DOCUMENT_ROOT")."/include/session_include.php";
@include getenv("DOCUMENT_ROOT")."/config/config_shopInfo.php";
include_once getenv("DOCUMENT_ROOT") . "/lib/erp_api.php";

if ($goStr == "")	$goStr = "switched=$switched&page=$page&key_word=$key_word&column=$column&sorting_type=$sorting_type&switch=$switch";
$lguserid = $_SESSION['ss_UID'];

/*
for($i=0; $i<sizeof($_POST); $i++) {
	list($key, $value) = each($_POST);
	$$key = $value;

	if(is_array($value))
	{
		$count = 10;
		for($i = 0; $i < $count; $i ++) {
			if ($value[$i]) echo "ARRAY[$key][$value[$i]]<br>";
		}
	}
	else 	echo "[$key][$value]<br>";
	//print_r($_POST);
}

//exit;
*/


//////////////////////////////////////////////
// PICKUP ORDER from Customer Detail Page
//////////////////////////////////////////////

if ($actionStr == "PICKUPORDERCUSTOMER") {

			if($c_uid == "") {
				$msg = "Invalid data. Please try again. [Err - c_uid / PICKUPORDERCUSTOMER]";
				$func -> modalMsg ($msg, "");
				exit();
			}

			$qry = "SELECT * FROM tbl_customer WHERE c_uid = '$c_uid'";
			$rt = $jdb->fQuery($qry, "query error");

			//echo "[$rowCnt][$qry]<br>";
			if ($rt[0] =="") {
				$msg = "Invalid data. Please try again. [Err - customer data]";
				//$urlSTR = "/index_intranet.php?view=customer_detail&mode=update&c_uid=$c_uid&".$goStr;
				$urlSTR = "/index_intranet.php?view=customer_list&".$goStr;
				//$func -> alertBack($msg);
				$func -> modalMsg ($msg, $urlSTR);				
				exit();
			}
			
			for($i=0; $i<sizeof($rt); $i++) {
				//list($key, $value) = each($result);
				foreach ( (Array) $rt as $key => $value )		
				$$key = $value;
			}

			// 데이터가 여러번 저장되는 문제 수정 (2024.08.30)
			// tbl_daily 에서 d_orderdate 에 해당하는 d_customeruid 가 존재하면 update, 없으면 create
			// driver의 경우 d_visitdate 를 변경할수 없으므로 해당 일자의 데이터를 업데이트하게 됨
			// 하지만 운영자가 d_visitdate 를 변경해서 저장하는 경우 변경된 d_visitdate 에 data가 존재하는 경우 Alert 처리
			
			//if($d_mode == "") $d_mode = "create";
			$qry_daily = "SELECT * FROM tbl_daily WHERE d_customeruid = '$c_uid' AND d_orderdate = '".str_replace("-", "", trim($d_visitdate))."' ";
			$rt_daily = $jdb->fQuery($qry_daily, "query error");
			
			//echo "[".$rt_daily['d_uid']."][$qry_daily]<br>";exit;
			
			
			if ($rt_daily['d_uid'] == "") {		// data가 존재하지 않음
				
					// customer_datail 에서 이미 data가 있으므로 update 처리
					if($d_mode == "update" && $d_uid != "") $d_mode = "update";	
					else $d_mode = "create";
			}
			else {		// data 가 존재
				
					$d_mode = "update";
					$d_uid = $rt_daily['d_uid'];
					$d_driveruid = $rt_daily['d_driveruid'];

					// d_visitdate가 오늘 일자가 아닌 경우, order date을 변경하려는 것임. 
					// 하지만 변경하려는 일자에 data가 존재하므로 alert 처리후 종료
					if(date("Y-m-d") != trim($d_visitdate)) {		
							$msg = "Data exists on that date, Please delete it first. <br>[Err - dup_date_data / PICKUPORDERCUSTOMER]";
							$func -> modalMsg ($msg, "");
							exit();
					}
								
			}

									
			$columns = array();
			$values = array();

			if($d_mode == "create") {
					$columns[] = "d_ordertype";
					$columns[] = "d_ruid";
					$columns[] = "d_driveruid";
					$columns[] = "d_customeruid";
					//$columns[] = "d_accountno";
					$columns[] = "d_name";
					$columns[] = "d_paymenttype";
					$columns[] = "d_cycle";
					$columns[] = "d_rate";
					$columns[] = "d_form_eu";
					$columns[] = "d_form_corsia";
					$columns[] = "d_maincontainer";
					$columns[] = "d_container";
					$columns[] = "d_location";
					$columns[] = "d_address";
					$columns[] = "d_city";
					$columns[] = "d_postal";
					$columns[] = "d_oil_2y";
					$columns[] = "d_oil_1y";
					$columns[] = "d_oil_0y";

					$columns[] = "d_fullcycle";
					$columns[] = "d_fullcycleforced";
					$columns[] = "d_fullcycleflag";
									
					$columns[] = "d_lastpickupdate";
					$columns[] = "d_lastpickupquantity";
					
					$columns[] = "d_lastpaiddate";
					$columns[] = "d_estquantity";

					$columns[] = "d_createruid";
					$columns[] = "d_createddate";
					
					//$columns[] = "d_inputdate";
														
			}
			else {
					$columns[] = "d_modifydate";
			}
			$columns[] = "d_accountno";
			$columns[] = "d_orderdate";
			$columns[] = "d_inputdate";

			$columns[] = "d_quantity";
			$columns[] = "d_sludge";
			$columns[] = "d_paystatus";
			$columns[] = "d_payamount";
			$columns[] = "d_visit";
			$columns[] = "d_visitdate";
			$columns[] = "d_status";

			$columns[] = "d_payeename";
			$columns[] = "d_is_transfer"; // Integration to ERP

			////////////	
			// data
			////////////	

			$d_visitdate = str_replace("-", "", trim($d_visitdate));
			if (strlen($d_visitdate) == 8) $d_visitdateSTR = $d_visitdate."000000";

			if($d_mode == "create") {
					$values[] = "N";  // d_ordertype
					$values[] = "";  // d_ruid
					$values[] = $d_driveruid;
					$values[] = $c_uid;
					//$values[] = $c_accountno;
					$values[] = $c_name;  
					$values[] = $c_paymenttype;  
					$values[] = $c_paymentcycle;
							
					$values[] = $c_rate;  // d_rate
					$values[] = $c_form_eu;  // d_form_eu
					$values[] = $c_form_corsia;  // d_form_corsia
					$values[] = $c_maincontainer;  // d_maincontainer
					$values[] = $c_container;  // d_container
					$values[] = $c_location;  // d_location
					$values[] = $c_address;  // d_address
					$values[] = $c_city;  // d_city
					$values[] = $c_postal;  // d_postal
					$values[] = 0;  // d_oil_2y
					$values[] = 0;  // d_oil_1y
					$values[] = 0;  // d_oil_0y

					$values[] = $c_fullcycle;  // d_fullcycle
					$values[] = $c_fullcycleforced;  // d_fullcycleforced
					$values[] = $c_fullcycleflag;  // d_fullcycleflag		
											
					$values[] = $c_lastpickupdate;  // d_lastpickupdate
					$values[] = $c_lastpickupquantity;  // d_lastpickupquantity
					$values[] = $c_lastpaiddate;  // d_lastpaiddate
					$values[] = $c_fullquantity;  // d_estquantity

					$values[] = $_SESSION['ss_UID'];  // d_createruid
					$values[] = date("YmdHis");  // d_createddate
					
					//$values[] = date("YmdHis");  // d_inputdate
			}
			else {
					$values[] = date("YmdHis");  // d_modifydate				
				
			}
			$values[] = $c_accountno;						
			$values[] = $d_visitdate;
			$values[] = date("YmdHis"); // d_inputdate

			$values[] = $d_quantity;
			$values[] = $d_sludge;
			$values[] = $d_paystatus;
			$values[] = number_format(floatval($d_payamount), 2, '.', ',');
			$values[] = "Y";
			$values[] = $d_visitdateSTR;
			$values[] = "F";

			$values[] = $d_payeename;
			$values[] = "N"; // Integration to ERP

			// Signiture
			if ($signednew == 1) $putSignFlag = 1;
			else {
					if ($d_payeesign == "" && $_POST['signed'] != "") $putSignFlag = 1;
					else $putSignFlag = 0;
			}

			//echo "[$signednew][$putSignFlag]";

			if ($putSignFlag == 1) {

					$folderPath = getenv("DOCUMENT_ROOT")."/upload_sign/".$d_customeruid;
					if (!is_dir($folderPath))  mkdir($folderPath, 0755, true);

					$image_parts = explode(";base64,", $_POST['signed']); 
					$image_type_aux = explode("image/", $image_parts[0]);
					$image_type = $image_type_aux[1];
					$image_base64 = base64_decode($image_parts[1]);
					$uniquevalue = uniqid();
					$file = $folderPath ."/". substr($d_visitdate,0,8). "_". $uniquevalue . '.'.$image_type;
					file_put_contents($file, $image_base64);

					$columns[] = "d_payeesign";
					$values[] = substr($d_visitdate,0,8). "_". $uniquevalue . '.'.$image_type;
				
			}

			if($d_mode == "create") {
					$jdb->iQuery("tbl_daily", $columns, $values);

					$qry_max = "SELECT max(d_uid) FROM tbl_daily ";
					$rt_max = $jdb->fQuery($qry_max, "fetch query error");
					
					$d_uid = $rt_max[0];				

					$logSTR = "[d_uid=$d_uid][d_driveruid=$d_driveruid][d_quantity=$d_quantity][d_paystatus=$d_paystatus][d_payamount=".number_format(floatval($d_payamount), 2, '.', ',')."]";
					addLog ("add", "ORDER PICKUP - CUSTOMER", "PICKUP-INSERT", $lguserid, $logSTR, $d_uid);

					// ==================== 
					// Integration to ERP 
					// ====================
					$columns[] = "d_pickupnote";
					$values[] = str_replace("\\", "", trim($d_note));

					$erp = new ErpApi();

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

						// 성공 시 플래그 & 로그
						$jdb->uQuery("tbl_daily", ["d_is_transfer"], ["Y"], " WHERE d_uid = '$d_uid'");
					} catch (Exception $e) {
						// 여기서는 아무것도 안함
					}
									
			} else {
					$jdb->uQuery("tbl_daily", $columns, $values, " where d_uid = '$d_uid' ");
					// ==================== 
					// Integration to ERP 
					// ====================
					$columns[] = "d_pickupnote";
					$values[] = str_replace("\\", "", trim($d_note));

					$erp = new ErpApi();

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

						// 성공 시 플래그 & 로그
						$jdb->uQuery("tbl_daily", ["d_is_transfer"], ["Y"], " WHERE d_uid = '$d_uid'");
					} catch (Exception $e) {
						// 여기서는 아무것도 안함
					}
			
					$logSTR = "[d_uid=$d_uid][d_driveruid=$d_driveruid][d_quantity=$d_quantity][d_paystatus=$d_paystatus][d_payamount=".number_format(floatval($d_payamount), 2, '.', ',')."]";
					addLog ("add", "ORDER PICKUP - CUSTOMER", "PICKUP-UPDATE", $lguserid, $logSTR, $d_uid);		
			}




			////////////////////////////////////////////////////////////////////////////
			// tbl_customer 의 c_lastpickupdate, c_lastpickupquantity, c_lastpaiddate , 
			// c_orderdate = "", c_orderflag = 0, c_sludge 업데이트
			////////////////////////////////////////////////////////////////////////////

			// d_visitdate 가 c_lastpickupdate 보다 커야 tbl_customer 에 c_lastpickupdate, c_lastpickupquantity 저장
			$qry_a = "SELECT d_visitdate, d_quantity FROM tbl_daily WHERE d_uid = '$d_uid' ";
			$rt_a=$jdb->fQuery($qry_a, "record query error");
			
			$d_visitdateTmp = substr($rt_a['d_visitdate'],0,8);
			$d_quantityTmp = $rt_a['d_quantity'];
			
			//echo "[$qry_a][".$d_visitdateTmp."][$c_lastpickupdate]<br>";exit;

			if ($d_visitdateTmp >= $c_lastpickupdate) {
				$addQry_a = " c_lastpickupdate = '".$d_visitdateTmp."', c_lastpickupquantity = '".$d_quantityTmp."',";
			
				if (trim($d_sludge) != "") {
					$add_sludge = " c_sludge = '$d_sludge', ";
					
					// tbl_daily 의 sludge update - 2025-12-09 history 안건드리기
					// $qry_sludge = "UPDATE tbl_daily SET d_sludge='".$d_sludge."' WHERE d_customeruid = '".$d_customeruid."'";
					// $jdb->nQuery($qry_sludge, "Update error");
				}
				else $add_sludge = "";
			}
			else {
				$addQry_a = "";
			}


			if ($d_paymenttype == "CA" && $d_paystatus == "P") {
				$addQry = " c_lastpaiddate = '".$d_visitdate."', ";
				$addWhereQry = "AND (c_lastpaiddate < '".$d_visitdate."' OR c_lastpaiddate IS NULL) ";
			} else {
				$addQry = "";
				$addWhereQry = "";
			}

			//if (trim($d_sludge) != "") $add_sludge = " c_sludge = '$d_sludge', ";
			//else $add_sludge = "";

			$qry_customer = "UPDATE tbl_customer 
											SET 
												".$addQry_a."
												".$addQry."
												c_orderdate = '', 
												".$add_sludge."
												c_orderflag = 0
											WHERE c_uid = '$d_customeruid' ". $addWhereQry;

			//echo "[$qry_customer]<br>";

			$jdb->nQuery($qry_customer, "update error");
			// ==================== 
			// Integration to ERP 
			// ERP 에서는 Trigger로 처리
			// ====================

			addLog ("add", "ORDER PICKUP - CUSTOMER", "UPDATE", $lguserid, $qry_customer, $d_customeruid);


			// tbl_daily 의 sludge update
			//if (trim($d_sludge) != "") {
			//		$qry_sludge = "UPDATE tbl_daily SET d_sludge='".$d_sludge."' WHERE d_customeruid = '".$d_customeruid."'";
			//		$jdb->nQuery($qry_sludge, "Update error");
			//}
					
// Customer Detail Page 에서 Pickup Order 입력하는 경우 Request 인지 Scheduled 인지 확인불가해서
// 아래의 로직은 사용하지 않음

/*
			////////////////////////////////////////////////////////////////////////////
			// Scheduled Order 인 경우 Pickup 완료되면 
			// tbl_customer 의 c_schedulebasic 에 다음 일자 계산해서 저장
			////////////////////////////////////////////////////////////////////////////

			// Get Information
			$qry_s = "SELECT * FROM tbl_daily WHERE d_uid = '".$d_uid."' ";
			$rt_s=$jdb->fQuery($qry_s, "fetch query error");

			//echo"[$qry_s]";
						
			if ($rt_s['d_ordertype'] == "S") {
				
				$qry_ss = "SELECT * FROM tbl_customer 
										WHERE c_uid ='$d_customeruid' AND c_schedule > '1W' AND c_schedule <= '6W' ";
				//echo "Scheduled[$qry_s]<br>";
				$rt_ss=$jdb->fQuery($qry_ss, "fetch query error");

				if ($rt_ss[0] != "") {
					$c_schedule = $rt_ss['c_schedule'];
					$c_scheduleday =  explode("|", $rt_ss['c_scheduleday']);
					$c_schedulebasicSTR = "+".substr($c_schedule, 0,1)." week ".$c_scheduleday[0];
					$c_schedulebasic = date('Ymd', strtotime($c_schedulebasicSTR, strtotime($d_visitdate)));

					$qry_sch = "UPDATE tbl_customer 
													SET c_schedulebasic = '".$c_schedulebasic."'
													WHERE c_uid = '$d_customeruid'";

					//echo "[$qry_sch]<br>";

					$jdb->nQuery($qry_sch, "update error");
						
				}
				
			}

			////////////////////////////////////////////////////////////////////////////
			// Request Order 인 경우 Pickup 완료되면 
			// tbl_request 의 r_status 에 Finish 로 저장
			////////////////////////////////////////////////////////////////////////////

			else if ($rt_s['d_ordertype'] == "R") {
					$qry_sch = "UPDATE tbl_request 
													SET r_status = 'F'
													WHERE r_uid = '".$rt_s['d_ruid']."'";

					//echo "[$qry_sch]<br>";

					$jdb->nQuery($qry_sch, "update error");
			}
*/


			//////////////////////////////////////////////
			// ADD NOTE
			//////////////////////////////////////////////

			if (strlen($d_note) > 1) {

						$columns = array();
						$values = array();
						

						$columns[] = "n_memberuid";
						$columns[] = "n_customeruid";
						$columns[] = "n_dailyuid";
						$columns[] = "n_type";
						$columns[] = "n_level";
						
						$columns[] = "n_view";
						$columns[] = "n_note";
						$columns[] = "n_createddate";


						////////////	
						// data
						////////////	
						
						$values[] = $d_driveruid;
						$values[] = $d_customeruid;
						$values[] = $d_uid;

						/*if ($_SESSION['ss_LEVEL'] == "1") $n_type = "S";
						else if ($_SESSION['ss_LEVEL'] == "5") $n_type = "S";
						else if ($_SESSION['ss_LEVEL'] == "6") $n_type = "B";
						else if ($_SESSION['ss_LEVEL'] == "7") $n_type = "A";
						else if ($_SESSION['ss_LEVEL'] == "9") $n_type = "D";*/
						
						// Pickup Order 는 Driver가 하므로 n_type: D, n_level: 9
						$values[] = "D"; // $n_type;
						$values[] = 9; // $_SESSION['ss_LEVEL'];
						
						$values[] = 1;
						$values[] = str_replace("\\", "", trim($d_note));
						$values[] = date("YmdHis");

						//for ($i=0; $i < count($columns); $i++)
						//echo "NOTE[$columns[$i]][$values[$i]]<br>";
						//echo "[UID=$uid][ID=$userid][MAXUID=$maxuid]";
						//exit;	

						if($d_mode == "create") {
								$jdb->iQuery("tbl_note", $columns, $values);		
						} else {
								$jdb->uQuery("tbl_note", $columns, $values, " where n_dailyuid = '$d_uid' ");
						}
			
			}

			$msg = "Saved Successfully.";			
			//$urlSTR = "/index_intranet.php?view=customer_detail&mode=update&c_uid=$c_uid&".$goStr;
			$urlSTR = "/index_intranet.php?view=customer_list&".$goStr;
			//$func -> alertBack($msg);
			$func -> modalMsg ($msg, $urlSTR);
			exit();

}




//////////////////////////////////////////////
// DELETE ORDER (order_driver 에서 삭제시)
//////////////////////////////////////////////

if ($actionStr == "ORDERINFO" && $mode == "delete") {

			// Delete 기능 제한 (Admin : 1, Staff : 5, Driver : 9 만 가능)
			$permit = array("1", "5", "9");
			if (in_array($_SESSION['ss_LEVEL'], $permit)) {
			    $setTag = "";
			}
			else {
				$msg = "Sorry, You don't have permission. Please contact Administrator.";
				$func -> modalMsg ($msg, "");
				exit();
			}
	
			if($d_uid == "") {
				$msg = "Invalid data. Please try again. [Err - d_uid / ORDERINFO]";
				$func -> modalMsg ($msg, "");
				exit();
			}

			// orderdate 이 현재일 이후인 경우만 삭제 가능 (order_driver 에서 이미 체크함)
			// c_orderflag = 1 : 오더장이 만들어졌지만 아직 픽업전인 경우. 
			//                   일자가 지났어도 픽업하지 않은 경우(cron 에서 자동 0으로 변환)
			// 오더장 삭제 후 tbl_customer 의 c_orderdate = "", c_orderflag = 0 으로 셋팅
			// c_orderflag = 0 이 되어야 forecast 검색 가능함
			
			$qry_cnt = "SELECT COUNT(*) FROM tbl_customer WHERE c_accountno = '$d_accountno' AND c_orderflag = 1";
			$total_count=$jdb->rQuery($qry_cnt, "record query error");
			//echo "[$qry_cnt]";


			// orderdate 이 현재보다 이전인 경우는 c_orderflag 체크하지 않고 삭제. (2023.09.06 요청받음)
			// 이미 cron에서 처리 됨
			// last pickupdate, sludge, last paiddate 는 꼬일수 있음
			 if (date("Ymd") > $d_orderdate) {
			 		$qry_order = "DELETE FROM tbl_daily WHERE d_uid = '$d_uid' ";
					$jdb->nQuery($qry_order, "delete error");

					addLog ("add", "ORDER DELETE", "DELETE", $lguserid, $qry_order, $d_uid);
					
					// 이미 동일한 account에 동일한 일자로 request 가 존재하는 경우 삭제
					$qry_cntr = "SELECT COUNT(r_uid) FROM tbl_request
										WHERE r_accountno = '$d_accountno' 
										AND r_requestdate = '".$d_orderdate."' ";

					$totcntr=$jdb->rQuery($qry_cntr, "fetch query error");

					if($totcntr >= 1) {
							$qry_request = "DELETE FROM tbl_request WHERE r_accountno = '$d_accountno' AND r_requestdate = '$d_orderdate' ";
							$jdb->nQuery($qry_request, "delete error");
							addLog ("add", "REQUEST DELETE", "DELETE", $lguserid, $qry_request, $d_accountno);
					}
			
					$msg = "Deleted successfully.";
			}
			
			// total_count 와 상관없이 오더장 삭제 & tbl_customer 의 c_orderdate = "", c_orderflag = 0 으로 셋팅 (2023.09.11 요청)
			else {
				
					$qry_order = "DELETE FROM tbl_daily WHERE d_uid = '$d_uid'";
					$jdb->nQuery($qry_order, "delete error");
					addLog ("add", "ORDER DELETE", "DELETE", $lguserid, $qry_order, $d_uid);
					
					$qry_customer = "UPDATE tbl_customer SET c_orderdate='', c_orderflag = 0 WHERE c_accountno = '$d_accountno' ";
					$jdb->nQuery($qry_customer, "update error");
					addLog ("add", "ORDER DELETE", "UPDATE", $lguserid, $qry_customer, $d_accountno);
					//$jdb->CLOSE();

					// 이미 동일한 account에 동일한 일자로 request 가 존재하는 경우 삭제
					$qry_cntr = "SELECT COUNT(r_uid) FROM tbl_request
										WHERE r_accountno = '$d_accountno' 
										AND r_requestdate = '".$d_orderdate."' ";

					$totcntr=$jdb->rQuery($qry_cntr, "fetch query error");

					if($totcntr >= 1) {
							$qry_request = "DELETE FROM tbl_request WHERE r_accountno = '$d_accountno' AND r_requestdate = '$d_orderdate' ";
							$jdb->nQuery($qry_request, "delete error");
							addLog ("add", "REQUEST DELETE", "DELETE", $lguserid, $qry_request, $d_accountno);
					}
			
					$msg = "Deleted successfully.";
			}


			// 오더장 삭제시 오더장 먼저 삭제하고 last pickupdate, quantity, last paid date 를 tbl_daily 에서 찾아서 tbl_customer 에 업데이트 (2023.11.17)
			// sludge 는 어떻게 처리? customer detail 에서 수정할수도 있고, 오더장에 입력시 전체 업데이트 됨. 어디서 언제 입력했는지 확인 불가.
			$qry_r1 = "SELECT d_orderdate,d_visitdate,d_quantity,d_paymenttype,d_paystatus,d_sludge FROM tbl_daily 
										WHERE d_accountno = '".$d_accountno."' AND d_status = 'F' ORDER BY d_orderdate DESC LIMIT 1";
			$rt_r1 = $jdb->fQuery($qry_r1, "query error");

			$d_orderdateSTR = $rt_r1['d_orderdate'];
			$d_visitdateSTR = $rt_r1['d_visitdate'];
			$d_quantitySTR = $rt_r1['d_quantity'];
			$d_paymenttypeSTR = $rt_r1['d_paymenttype'];
			$d_paystatusSTR = $rt_r1['d_paystatus'];
			$d_sludgeSTR = $rt_r1['d_sludge'];


			// tbl_daily 의 마지막 데이터중 cash 이고 paid 면 c_lastpaiddate
			// 그렇지 않으면 다시 tbl_daily 에서 cash 이고 paid 인 마지막 데이터를 가져옴. 없으면 null 처리
			
			if ($d_paymenttypeSTR == "CA" && $d_paystatusSTR == "P") 	$addQry = ", c_lastpaiddate = '".$d_visitdateSTR."' ";
			else {
					$qry_r2 = "SELECT d_visitdate FROM tbl_daily 
										WHERE d_accountno = '".$d_accountno."' AND d_status = 'F' AND d_paymenttype = 'CA' AND d_paystatus = 'P'
										ORDER BY d_orderdate DESC LIMIT 1";
					$rt_r2 = $jdb->fQuery($qry_r2, "query error");

					if ($rt_r2['d_visitdate'] != "") $addQry = ", c_lastpaiddate = '".$rt_r2['d_visitdate']."' ";
					else $addQry = ", c_lastpaiddate = '' ";
			}
			
			$qry_customer = "UPDATE tbl_customer 
											SET c_lastpickupdate='".$rt_r1['d_orderdate']."', c_lastpickupquantity = '".$rt_r1['d_quantity']."' ". $addQry ." 
											WHERE c_accountno = '$d_accountno' ";
			$jdb->nQuery($qry_customer, "update error");
			addLog ("add", "ORDER DELETE", "UPDATE", $lguserid, $qry_customer, $d_accountno);

			// ==================== 
			// Integration to ERP 
			// 나머지는 trigger 처리
			// ====================
			$columns = array();
			$values = array();
			$columns[] = "d_accountno";
			$columns[] = "d_orderdate";
			$columns[] = "d_status";
			$values[] = $d_accountno;
			$values[] = $d_orderdate;
			$values[] = "D";
			
			$erp = new ErpApi();

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

				// 성공 시 플래그 & 로그 (지웠음)
				// $jdb->uQuery("tbl_daily", ["d_is_transfer"], ["Y"], " WHERE d_uid = '$d_uid'");

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


			//else {
			//		$msg = "Invalid data. Please try again. [Err - c_orderflag]";	
			//}
			
			$urlSTR = "/index_intranet.php?view=order_driver&".$goSTRSTR."&".$goStr;
			//$func -> alertBack($msg);
			$func -> modalMsg ($msg, $urlSTR);
			exit();
}



//////////////////////////////////////////////
// ADD ORDER  (From Forecast 오더장 생성)
//////////////////////////////////////////////

if ($actionStr == "ORDEROIL" && $mode == "insert") {

			if($orderdate == "") {
				$msg = "Invalid data. Please try again. [Err - order date]";
				$func -> modalMsg ($msg, "/index_intranet.php?view=forecast");
				exit();
			}

			if (count($selectaccountno) == 0) {
				$msg = "Invalid data. Please try again. [Err - select data]";
				$func -> modalMsg ($msg, "/index_intranet.php?view=forecast");
				exit();
			}
							
			$rowCnt = 1;
			
			// S -> R -> N 로 소팅됨.
			rsort($selectaccountno);

			// 날짜간 일수 계산
			$getPeriodOrderTmp  = new DateTime($orderdate);
			$getPeriodNowTmp  = new DateTime(date("Y-m-d"));
			
			$dDiffTmp = $getPeriodNowTmp->diff($getPeriodOrderTmp);
			$dDiff = $dDiffTmp->format('%r%a');
	
			// 이미 Forecast Batch 에서 내일일자로 c_fullquantitydaily 저장됨 (2024.01.16)
			$dDiff = $dDiff -1;

			foreach ($selectaccountno as $value) {

						$valueSTR = explode("|", $value);
						
						// 중복 체크 (존재하면 저장하지 않음)
						// tbl_daily 에는 orderdate 당 account no 가 1개만 존재해야함
						$qry_cnt = "SELECT COUNT(*) FROM tbl_daily WHERE d_accountno = '$valueSTR[1]' AND d_orderdate = '$orderdate'";
						$total_count=$jdb->rQuery($qry_cnt, "record query error");
						
						if ($total_count == 0) {
							
									$qry = "SELECT * FROM tbl_customer WHERE c_accountno = '$valueSTR[1]'";
									$rt = $jdb->fQuery($qry, "query error");

									//echo "[$rowCnt][$qry]<br>";
									if ($rt[0] =="") {
										$msg = "Invalid data. Please try again. [Err - customer data]";
										$func -> modalMsg ($msg, "/index_intranet.php?view=forecast");
										exit();
									}
									
									for($i=0; $i<sizeof($rt); $i++) {
										//list($key, $value) = each($result);
										foreach ( (Array) $rt as $key => $value )		
										$$key = $value;
									}

									$columns = array();
									$values = array();

									$columns[] = "d_orderdate";
									$columns[] = "d_ordertype";
									$columns[] = "d_ruid";
									$columns[] = "d_driveruid";
									$columns[] = "d_customeruid";
									$columns[] = "d_accountno";
									$columns[] = "d_name";
									$columns[] = "d_paymenttype";
									$columns[] = "d_cycle";
									$columns[] = "d_rate";
									$columns[] = "d_form_eu";
									$columns[] = "d_form_corsia";
									$columns[] = "d_maincontainer";
									$columns[] = "d_container";
									$columns[] = "d_location";
									$columns[] = "d_address";
									$columns[] = "d_city";
									$columns[] = "d_postal";
									$columns[] = "d_oil_2y";
									$columns[] = "d_oil_1y";
									$columns[] = "d_oil_0y";
									$columns[] = "d_fullcycle";
									$columns[] = "d_fullcycleforced";
									$columns[] = "d_fullcycleflag";
									$columns[] = "d_lastpickupdate";
									$columns[] = "d_lastpickupquantity";
									$columns[] = "d_lastpaiddate";
									$columns[] = "d_estquantity";
									//$columns[] = "d_sludge";
									//$columns[] = "d_paystatus";
									//$columns[] = "d_payamount";
									//$columns[] = "d_visit";
									//$columns[] = "d_visitdate";
									$columns[] = "d_createruid";
									$columns[] = "d_createddate";
									$columns[] = "d_status";

									//$columns[] = "d_inputdate";
									//$columns[] = "d_quantity";
									
									
									// Data															

									$values[] = $orderdate;
									$values[] = $valueSTR[0];  // d_ordertype
									$values[] = $valueSTR[2];  // d_ruid
									$values[] = $c_driveruid;
									$values[] = $c_uid;
									$values[] = $c_accountno;
									$values[] = $c_name;  
									$values[] = $c_paymenttype;  
									$values[] = $c_paymentcycle;
											
									$values[] = $c_rate;  // d_rate
									$values[] = $c_form_eu;  // d_form_eu
									$values[] = $c_form_corsia;  // d_form_corsia
									$values[] = $c_maincontainer;  // d_maincontainer
									$values[] = $c_container;  // d_container
									$values[] = $c_location;  // d_location
									$values[] = $c_address;  // d_address
									$values[] = $c_city;  // d_city
									$values[] = $c_postal;  // d_postal
									//$values[] = $rt_customer['c_area'];  // d_area
									$values[] = 0;  // d_oil_2y
									$values[] = 0;  // d_oil_1y
									$values[] = 0;  // d_oil_0y

									$values[] = $c_fullcycle;  // d_fullcycle
									$values[] = $c_fullcycleforced;
									$values[] = $c_fullcycleflag;
									
									$values[] = $c_lastpickupdate;  // d_lastpickupdate
									$values[] = $c_lastpickupquantity;  // d_lastpickupquantity
									$values[] = $c_lastpaiddate;  // d_lastpaiddate
									
									$values[] = round(floatval($c_fullquantity + (($dDiff) * $c_fullquantitydaily)));  // d_estquantity
									//$values[] = $d_sludge;  // d_sludge
												
									//$values[] = "";  // d_paystatus
									//$values[] = "";  // d_payamount
									//$values[] = "";  // d_visit
									//$values[] = "";   // d_visitdate

									$values[] = $_SESSION['ss_UID'];  // d_createruid
									$values[] = date("YmdHis");  // d_createddate
									$values[] = "A";  // d_status

									//$values[] = "";  // d_inputdate
									//$values[] = $d_quantity;  // d_quantity


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

									$rtvalue = $jdb->iQuery("tbl_daily", $columns, $values);

									// get d_uid
									$qry_max = "SELECT max(d_uid) FROM tbl_daily ";
									$rt_max = $jdb->fQuery($qry_max, "fetch query error");
									
									$d_uid = $rt_max[0];
									// ==================== 
									// Integration to ERP 
									// ====================
									$erp = new ErpApi();
									try {
										// ERP로 전송 (payload 내부에서 자동 매핑)
										$erp->createDailyOrderFromMis($columns, $values, $lguserid);

										// 성공 시 플래그 & 로그
										$jdb->uQuery("tbl_daily", ["d_is_transfer"], ["Y"], " WHERE d_uid = '$d_uid'");
									} catch (Exception $e) {
										// 여기서는 아무것도 안함
									}

									//
									$qry_customer = "UPDATE tbl_customer 
																	SET c_orderdate='$orderdate', c_orderflag = 1
																	WHERE c_uid = '$c_uid'";
									
									$jdb->nQuery($qry_customer, "update error");
			
									unset ($columns);
									unset ($values);
									
									$rowCnt++;
							
						}
			

			}

			$msg = "Saved Successfully.";
						
			//$func -> alertBack($msg);
			$func -> modalMsg ($msg, "/index_intranet.php?view=forecast");
			exit();
}



//////////////////////////////////////////////
// DELETE CUSTOMER INFO (c_status 만 D 로 변경)
//////////////////////////////////////////////

if ($actionStr == "CUSTOMERINFO" && $mode == "delete") {

			// Delete 기능 제한 (Admin : 1, Manager : 3, Staff : 5 만 가능)
			$permit = array("1", "3", "5");
			if (in_array($_SESSION['ss_LEVEL'], $permit)) {
			    $setTag = "";
			}
			else {
				$msg = "Sorry, You don't have permission. Please contact Administrator.";
				$func -> modalMsg ($msg, "");
				exit();
			}
	
			if($c_uid == "") {
				$msg = "Invalid data. Please try again.";
				$func -> modalMsg ($msg, "");
				exit();
			}
			
			$qry_delete = "UPDATE tbl_customer SET c_status='D' WHERE c_uid = '$c_uid' ";
			
			$jdb->nQuery($qry_delete, "delete error");
			$jdb->CLOSE();
			
			addLog ("add", "CUSTOMER DELETE", "DELETE", $lguserid, $qry_delete, $c_uid);

			// ====================
			// Integration to ERP
			// ====================
			// 화면에서 기능이 없음
			
			$msg = "Deleted successfully.";
			$urlSTR = "/index_intranet.php?view=customer_list&$goStr";
			//$func -> alertBack($msg);
			$func -> modalMsg ($msg, $urlSTR);
			exit();
}



//////////////////////////////////////////////
// DELETE MEMBER INFO (m_status 만 D 로 변경)
//////////////////////////////////////////////

if ($actionStr == "MEMBERINFO" && $mode == "delete") {

			// Delete 기능 제한 (Admin : 1, Manager : 3, Staff : 5 만 가능)
			$permit = array("1", "3", "5");
			if (in_array($_SESSION['ss_LEVEL'], $permit)) {
			    $setTag = "";
			}
			else {
				$msg = "Sorry, You don't have permission. Please contact Administrator.";
				$func -> modalMsg ($msg, "");
				exit();
			}
	
			if($m_uid == "") {
				$msg = "Invalid data. Please try again.";
				$func -> modalMsg ($msg, "");
				exit();
			}
			
			
			$jdb->nQuery("UPDATE tbl_member SET m_status='D' WHERE m_uid = '$m_uid'", "delete error");
			$jdb->CLOSE();
			
			$msg = "Deleted successfully.";
			$urlSTR = "/index_intranet.php?view=member_list&$goStr";
			//$func -> alertBack($msg);
			$func -> modalMsg ($msg, $urlSTR);
			exit();
}



//////////////////////////////////////////////
// ADD NOTE
//////////////////////////////////////////////

if ($actionStr == "ADDNOTE" && $mode == "create") {

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

			if($n_customeruid == "" || $n_memberuid == "") {
						$msg = "Invalid data(n_customeruid, n_memberuid). Please try again.";
						$func -> modalMsg ($msg, "");
						exit();
			}

			$columns = array();
			$values = array();
			

			$columns[] = "n_memberuid";
			$columns[] = "n_customeruid";
			$columns[] = "n_dailyuid";
			$columns[] = "n_type";
			$columns[] = "n_level";
			
			$columns[] = "n_view";
			$columns[] = "n_note";
			$columns[] = "n_createddate";


			////////////	
			// data
			////////////	
			
			$values[] = $n_memberuid;
			$values[] = $n_customeruid;
			$values[] = $n_dailyuid;
			
			if ($_SESSION['ss_LEVEL'] == "1") $n_type = "S";
			else if ($_SESSION['ss_LEVEL'] == "5") $n_type = "S";
			else if ($_SESSION['ss_LEVEL'] == "6") $n_type = "B";
			else if ($_SESSION['ss_LEVEL'] == "7") $n_type = "A";
			else if ($_SESSION['ss_LEVEL'] == "9") $n_type = "D";
			$values[] = $n_type;
			
			$values[] = $_SESSION['ss_LEVEL'];
			
			$values[] = 1;
			$values[] = str_replace("\\", "", trim($n_note));
			$values[] = date("YmdHis");

			//for ($i=0; $i < count($columns); $i++)
			//echo "[$columns[$i]][$values[$i]]<br>";
			//echo "[UID=$uid][ID=$userid][MAXUID=$maxuid]";
			//exit;	

			$jdb->iQuery("tbl_note", $columns, $values);
			$msg = "Created successfully.";
						
			$urlSTR = "/index_intranet.php?view=customer_detail&mode=update&c_uid=$n_customeruid&$goStr";
			//$func -> alertBack($msg);
			$func -> modalMsg ($msg, $urlSTR);
			exit();
}




//////////////////////////////////////////////
// DELETE NOTE (n_status 만 D 로 변경)
//////////////////////////////////////////////

if ($actionStr == "DELETENOTE" && $mode == "delete") {

			// Delete 기능 제한 (Admin : 1, Manager : 3, Staff : 5 만 가능)
			$permit = array("1");
			if (in_array($_SESSION['ss_LEVEL'], $permit)) {
			    $setTag = "";
			}
			else {
				$msg = "Sorry, You don't have permission. Please contact Administrator.";
				$func -> modalMsg ($msg, "");
				exit();
			}
	
			if($n_uid == "") {
				$msg = "Invalid data. Please try again.";
				$func -> modalMsg ($msg, "");
				exit();
			}
			
			
			$jdb->nQuery("UPDATE tbl_note SET n_status='D' WHERE n_uid = '$n_uid'", "update error");
			$jdb->CLOSE();
			
			$msg = "Deleted successfully.";
			$urlSTR = "/index_intranet.php?view=customer_detail&mode=update&c_uid=$c_uid&$goStr";
			//$func -> alertBack($msg);
			$func -> modalMsg ($msg, $urlSTR);
			exit();
}


//////////////////////////////////////////////
// ADD IMAGE (Customer Detail - Image Upload)
//////////////////////////////////////////////
if ($actionStr == "ADDIMAGE") {

	$i_note = isset($_POST['i_note']) ? trim($_POST['i_note']) : "";
	$i_createddate = date("YmdHis");

    if ($i_customeruid == "" || $i_memberuid == "") {
        $msg = "Invalid data. Please try again. [Err - i_customeruid, i_memberuid]";
        $func->modalMsg($msg, "");
        exit();
    }

    // 기존 이미지 비활성화
    if ($i_type == "install") {
        $qry_update = "
            UPDATE tbl_customer_image
            SET i_status = 'I'
            WHERE i_customeruid = '$i_customeruid'
              AND i_type = 'install'
              AND i_status = 'A'
        ";
        $jdb->nQuery($qry_update, "update error");
    }

	if ($i_type == "container") {
		$qry_update2 = "
			UPDATE tbl_customer_image
			SET i_status = 'I'
			WHERE i_customeruid = '$i_customeruid'
			AND i_type = 'container'
			AND i_status = 'A'
		";
		$jdb->nQuery($qry_update2, "update error");
	}

	// 이미지 최대 6개 제한 체크
	if ($i_type == "container") {
		// 기존 이미지 수 조회
		$qry_cnt = "
			SELECT i_filename 
			FROM tbl_customer_image 
			WHERE i_customeruid = '$i_customeruid'
			AND i_type = 'container'
			AND i_status = 'A'
			ORDER BY i_uid DESC LIMIT 1
		";
		$rt_cnt = $jdb->fQuery($qry_cnt, "error");

		$existingCount = 0;
		if (!empty($rt_cnt['i_filename'])) {
			$existingFiles = explode(",", $rt_cnt['i_filename']);
			$existingCount = count($existingFiles);
		}

		// 이번에 업로드할 파일 개수
		$newCount = is_array($_FILES['upload_file']['name'])
					? count($_FILES['upload_file']['name'])
					: 1;

		if ($existingCount + $newCount > 6) {
			$msg = "Container 이미지는 최대 6개까지 업로드할 수 있습니다.";
			$func->modalMsg($msg, "/index_intranet.php?view=customer_detail&mode=update&c_uid=$i_customeruid&$goStr");
			exit();
		}
	}

    // 업로드 파일 체크
    if (!isset($_FILES['upload_file'])) {
        $msg = "Upload failed. Please try again.";
        $func->modalMsg($msg, "/index_intranet.php?view=customer_detail&mode=update&c_uid=$i_customeruid&$goStr");
        exit();
    }

    // 저장 폴더 생성
    $upload_folder = getenv("DOCUMENT_ROOT")."/upload/customer_image/".$i_customeruid;
    if (!is_dir($upload_folder)) {
        mkdir($upload_folder, 0777, true);
    }

    // 파일 개수
    $fileCount = is_array($_FILES['upload_file']['name'])
                ? count($_FILES['upload_file']['name'])
                : 1;

    $uploadedFileNames = array(); // 콤마로 합쳐서 넣을 리스트

    for ($i = 0; $i < $fileCount; $i++) {

        $fileTmp  = is_array($_FILES['upload_file']['tmp_name'])
                    ? $_FILES['upload_file']['tmp_name'][$i]
                    : $_FILES['upload_file']['tmp_name'];

        $fileName = is_array($_FILES['upload_file']['name'])
                    ? $_FILES['upload_file']['name'][$i]
                    : $_FILES['upload_file']['name'];

        $fileError = is_array($_FILES['upload_file']['error'])
                     ? $_FILES['upload_file']['error'][$i]
                     : $_FILES['upload_file']['error'];

        if ($fileError != 0) continue;

        // 확장자
        $ext = pathinfo($fileName, PATHINFO_EXTENSION);

        // 새 파일명 생성
        $newFileName = "IMG_".$i_customeruid."_".time().rand(1000,9999)."_".$i.".".$ext;

        // 저장 경로
        $savePath = $upload_folder . "/" . $newFileName;

        if (!move_uploaded_file($fileTmp, $savePath)) {
            continue;
        }

        // 업로드된 파일명 저장 (DB에 콤마로 넣을 배열)
        $uploadedFileNames[] = $newFileName;
    }

    // 한 개도 업로드되지 않으면 종료
    if (count($uploadedFileNames) == 0) {
        $msg = "No files uploaded.";
        $func->modalMsg($msg, "/index_intranet.php?view=customer_detail&mode=update&c_uid=$i_customeruid&$goStr");
        exit();
    }

    $fileNameString = implode(",", $uploadedFileNames);
    $dbFilePath = "/upload/customer_image/".$i_customeruid."/";

    // DB INSERT
    $columns = array(
        "i_customeruid",
        "i_memberuid",
        "i_createdby",
        "i_createddate",
        "i_type",
        "i_filename",
        "i_filepath",
        "i_status",
        "i_note"
    );

    $values  = array(
        $i_customeruid,
        $i_memberuid,
        $i_createdby,
        $i_createddate,
        $i_type,
        $fileNameString,
        $dbFilePath,
        "A",
        $i_note
    );

    $jdb->iQuery("tbl_customer_image", $columns, $values);

    // 완료 후 이동
    // $msg = "Image uploaded successfully.";
    // $urlSTR = "/index_intranet.php?view=customer_detail&mode=update&c_uid=$i_customeruid&$goStr";
    // $func->modalMsg($msg, $urlSTR);
	echo "
	<script>
		alert('Image uploaded successfully!');
		if (window.opener) {
			window.opener.location.reload();
		}
		window.close();
	</script>
	";
    exit();
}


//////////////////////////////////////////////
// UPDATE IMAGE
//////////////////////////////////////////////
if ($actionStr == "UPDATEIMAGEFULL") {

    $i_uid = $_POST['i_uid'] ?? "";
    $i_customeruid = $_POST['i_customeruid'] ?? "";
    $i_note = trim($_POST['i_note'] ?? "");
    $goStr = $_POST['goStr'] ?? "";

    if ($i_uid == "" || $i_customeruid == "") {
        $msg = "Invalid data.";
        $func->modalMsg($msg, "");
        exit();
    }

	// 이미지 최대 6개 제한 체크
	if ($i_type == "container") {
		// 기존 이미지 수 조회
		$qry_cnt = "
			SELECT i_filename 
			FROM tbl_customer_image 
			WHERE i_customeruid = '$i_customeruid'
			AND i_type = 'container'
			AND i_status = 'A'
			ORDER BY i_uid DESC LIMIT 1
		";
		$rt_cnt = $jdb->fQuery($qry_cnt, "error");

		$existingCount = 0;
		if (!empty($rt_cnt['i_filename'])) {
			$existingFiles = explode(",", $rt_cnt['i_filename']);
			$existingCount = count($existingFiles);
		}

		// 이번에 업로드할 파일 개수
		$newCount = is_array($_FILES['upload_file']['name'])
					? count($_FILES['upload_file']['name'])
					: 1;

		if ($existingCount + $newCount > 6) {
			$msg = "Container 이미지는 최대 6개까지 업로드할 수 있습니다.";
			$func->modalMsg($msg, "/index_intranet.php?view=customer_detail&mode=update&c_uid=$i_customeruid&$goStr");
			exit();
		}
	}

    // 기존 데이터 가져오기
    $qry = "SELECT * FROM tbl_customer_image WHERE i_uid = '$i_uid'";
    $rt = $jdb->fQuery($qry, "Image read error");

    $oldFiles = explode(",", $rt['i_filename']);
    $filepath = $rt['i_filepath'];

    // 이미지 삭제 처리
    $deleteFiles = $_POST['delete_files'] ?? [];
    $newList = [];

    foreach ($oldFiles as $f) {
        $f = trim($f);
        if (in_array($f, $deleteFiles)) {
            $full = getenv("DOCUMENT_ROOT") . $filepath . $f;
            if (file_exists($full)) unlink($full);
        } else {
            $newList[] = $f; // 삭제되지 않은 파일 유지
        }
    }

    // 새 이미지 업로드 처리
    if (isset($_FILES['upload_file'])) {

        $upload_folder = getenv("DOCUMENT_ROOT") . $filepath;

        if (!is_dir($upload_folder)) mkdir($upload_folder, 0777, true);

        $fileCount = count($_FILES['upload_file']['name']);

        for ($i = 0; $i < $fileCount; $i++) {

            if ($_FILES['upload_file']['error'][$i] != 0) continue;

            $ext = pathinfo($_FILES['upload_file']['name'][$i], PATHINFO_EXTENSION);
            $newName = "IMG_".$i_customeruid."_".time().rand(1000,9999)."_".$i.".".$ext;

            $savePath = $upload_folder . $newName;

            if (move_uploaded_file($_FILES['upload_file']['tmp_name'][$i], $savePath)) {
                $newList[] = $newName;
            }
        }
    }

    // 콤마 문자열 재정리
    $finalFiles = implode(",", $newList);

    // DB 업데이트
    $columns = ["i_filename", "i_note"];
    $values = [$finalFiles, $i_note];

    $jdb->uQuery("tbl_customer_image", $columns, $values, "WHERE i_uid = '$i_uid'");

    $msg = "Updated successfully.";
    $url = "/index_intranet.php?view=customer_detail&mode=update&c_uid=$i_customeruid&$goStr";

    $func->modalMsg($msg, $url);
    exit();
}


//////////////////////////////////////////////
// DELETE IMAGE (i_status = 'I')
//////////////////////////////////////////////
if ($actionStr == "DELETEIMAGE") {

    $i_uid = $_POST['i_uid'] ?? "";
    $i_customeruid = $_POST['i_customeruid'] ?? "";

    if ($i_uid == "" || $i_customeruid == "") {
        $msg = "Invalid image data.";
        $func->modalMsg($msg, "");
        exit();
    }

    $columns = array("i_status");
    $values  = array("I");
    $where = "WHERE i_uid = '$i_uid'";

    $jdb->uQuery("tbl_customer_image", $columns, $values, $where);

    // 완료 후 이동
    $msg = "Image deleted successfully.";
    $urlSTR = "/index_intranet.php?view=customer_detail&mode=update&c_uid=$i_customeruid&$goStr";

    $func->modalMsg($msg, $urlSTR);
    exit();
}


//////////////////////////////////////////////
// ADD REQUEST (Customer Detail 에서 REQUEST 클릭시)
//////////////////////////////////////////////

if ($actionStr == "ADDREQUEST" && $mode == "create") {

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

			if($r_customeruid == "" || $r_memberuid == "") {
						$msg = "Invalid data. Please try again. [Err - r_customeruid, r_memberuid]";
						$func -> modalMsg ($msg, "");
						exit();
			}

			$r_requestdateSTR = str_replace("-", "", trim($r_requestdate));
			
			// 이미 동일한 account에 동일한 일자로 request 가 된 경우 중복 에러메세지 처리 후 종료
			$qry_cntr = "SELECT COUNT(r_uid) FROM tbl_request
								WHERE r_customeruid = '$r_customeruid' 
								AND r_requestdate = '".$r_requestdateSTR."' ";

			$totcntr=$jdb->rQuery($qry_cntr, "record query error");

			if($totcntr >= 1) {
						$msg = "Invalid data. Please try again. [Err - duplicated request data]";
						$func -> modalMsg ($msg, "");
						exit();
			}

			// 현재일자 이후로 tbl_daily 에 동일한 account로 오더장이 있으면 에러발생
			$qry_cntd = "SELECT d_orderdate FROM tbl_daily
								WHERE d_customeruid = '$r_customeruid' 
								AND d_orderdate >= '".date("Ymd")."' ORDER BY d_orderdate DESC LIMIT 1";

			$rt_d=$jdb->fQuery($qry_cntd, "record query error");

			if($rt_d['d_orderdate'] != "") {
						$d_orderdateTMP = $func -> convertFormat ($rt_d['d_orderdate'], 3);
						$msg = "Invalid data. Please try again. [Err - duplicated order data]<br>
										Please delete the order sheet (".$d_orderdateTMP.") first and request again.";
						$func -> modalMsg ($msg, "");
						exit();
			}
			
			$columns = array();
			$values = array();
			

			$columns[] = "r_memberuid";
			$columns[] = "r_requestdate";
			$columns[] = "r_customeruid";
			$columns[] = "r_accountno";
			$columns[] = "r_name";
			
			$columns[] = "r_driveruid";
			$columns[] = "r_createddate";
			$columns[] = "r_note";


			////////////	
			// data
			////////////	
			
			$values[] = $r_memberuid;
			$values[] = $r_requestdateSTR;
			$values[] = $r_customeruid;

						
			$query = "SELECT * FROM tbl_customer WHERE c_uid = '$r_customeruid'";
			$result = $jdb->fQuery($query, "query error");
			
			// No data
			if ($result[0] =="") {
				$msg = "Invalid data. Please try again. [Err - r_customeruid]";
				$urlSTR = "/index_intranet.php?view=customer_detail&mode=update&c_uid=$r_customeruid&$goStr";
				$func -> modalMsg ($msg, $urlSTR);
				exit();
			}
	
			$values[] = $result['c_accountno'];		
			$values[] = $result['c_name'];
			
			$values[] = $r_driveruid;
			$values[] = date("YmdHis");			
			$values[] = str_replace("\\", "", trim($r_note));

			$logSTR = "tbl_request[".$result['c_accountno']."][".$r_driveruid."][".date("YmdHis")."]";
			addLog ("add", "REQUEST", "ADD", $lguserid, $logSTR, $lgno);	

			$jdb->iQuery("tbl_request", $columns, $values);
			$msg = "Created successfully.";

						$qry_max = "SELECT max(r_uid) FROM tbl_request ";
						$rt_max = $jdb->fQuery($qry_max, "fetch query error");
						
						$r_uidMAX = $rt_max[0];

			// 날짜간 일수 계산
			$getPeriodOrderTmp  = new DateTime($r_requestdateSTR);
			$getPeriodNowTmp  = new DateTime(date("Y-m-d"));
			
			$dDiffTmp = $getPeriodNowTmp->diff($getPeriodOrderTmp);
			$dDiff = $dDiffTmp->format('%r%a');
			
			// Request Date 가 현재일이면 바로 오더장에 추가
			if ($r_requestdateSTR >= date("Ymd")) {
				
						$qry = "SELECT * FROM tbl_customer WHERE c_uid = '$r_customeruid'";
						$rt = $jdb->fQuery($qry, "query error");

						//echo "[$rowCnt][$qry]<br>";
						if ($rt[0] =="") {
							$msg = "Invalid data. Please try again. [Err - customer data]";
							$func -> modalMsg ($msg, "/index_intranet.php?view=forecast");
							exit();
						}
						
						for($i=0; $i<sizeof($rt); $i++) {
							//list($key, $value) = each($result);
							foreach ( (Array) $rt as $key => $value )		
							$$key = $value;
						}

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

						$columns[] = "d_orderdate";
						$columns[] = "d_ordertype";
						$columns[] = "d_ruid";
						$columns[] = "d_driveruid";
						$columns[] = "d_customeruid";
						$columns[] = "d_accountno";
						$columns[] = "d_name";
						$columns[] = "d_paymenttype";
						$columns[] = "d_cycle";
						$columns[] = "d_rate";
						$columns[] = "d_form_eu";
						$columns[] = "d_form_corsia";
						$columns[] = "d_maincontainer";
						$columns[] = "d_container";
						$columns[] = "d_location";
						$columns[] = "d_address";
						$columns[] = "d_city";
						$columns[] = "d_postal";
						$columns[] = "d_oil_2y";
						$columns[] = "d_oil_1y";
						$columns[] = "d_oil_0y";
						$columns[] = "d_fullcycle";
						$columns[] = "d_fullcycleforced";
						$columns[] = "d_fullcycleflag";						
						$columns[] = "d_lastpickupdate";
						$columns[] = "d_lastpickupquantity";
						$columns[] = "d_lastpaiddate";
						$columns[] = "d_estquantity";
						$columns[] = "d_createruid";
						$columns[] = "d_createddate";
						$columns[] = "d_status";
						
						// Data		
						$values[] = $r_requestdateSTR;
						$values[] = "R";  // d_ordertype
						$values[] = $r_uidMAX;
						$values[] = $r_driveruid;
						$values[] = $c_uid;
						$values[] = $c_accountno;
						$values[] = $c_name;  
						$values[] = $c_paymenttype;  
						$values[] = $c_paymentcycle;
						$values[] = $c_rate;  // d_rate
						$values[] = $c_form_eu;  // d_form_eu
						$values[] = $c_form_corsia;  // d_form_corsia
						$values[] = $c_maincontainer;  // d_maincontainer
						$values[] = $c_container;  // d_container
						$values[] = $c_location;  // d_location
						$values[] = $c_address;  // d_address
						$values[] = $c_city;  // d_city
						$values[] = $c_postal;  // d_postal
						$values[] = 0;  // d_oil_2y
						$values[] = 0;  // d_oil_1y
						$values[] = 0;  // d_oil_0y
						$values[] = $c_fullcycle;  // d_fullcycle
						$values[] = $c_fullcycleforced;  // d_fullcycleforced
						$values[] = $c_fullcycleflag;  // d_fullcycleflag
						$values[] = $c_lastpickupdate;  // d_lastpickupdate
						$values[] = $c_lastpickupquantity;  // d_lastpickupquantity
						$values[] = $c_lastpaiddate;  // d_lastpaiddate
						// 이미 내일일자의 예상오일량이 저장되어 있으므로 -1 해줌 (2023.11.13)
						$values[] = round(floatval($c_fullquantity + (($dDiff-1) * $c_fullquantitydaily)));  // d_estquantity
						$values[] = $_SESSION['ss_UID'];  // d_createruid
						$values[] = date("YmdHis");  // d_createddate
						$values[] = "A";  // d_status
						//
						$rtvalue = $jdb->iQuery("tbl_daily", $columns, $values);

						// get d_uid
						$qry_max = "SELECT max(d_uid) FROM tbl_daily ";
						$rt_max = $jdb->fQuery($qry_max, "fetch query error");
						
						$d_uid = $rt_max[0];

						// ==================== 
						// Integration to ERP 
						// ====================
						$erp = new ErpApi();

						try {
							$columns[] = "d_requestnote";
							$values[] = str_replace("\\", "", trim($r_note));

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

							// 성공 시 플래그 & 로그
							$jdb->uQuery("tbl_daily", ["d_is_transfer"], ["Y"], " WHERE d_uid = '$d_uid'");
						} catch (Exception $e) {
							// 여기서는 아무것도 안함
						}

						$qry_customer = "UPDATE tbl_customer 
														SET c_orderdate='$r_requestdateSTR', c_orderflag = 1
														WHERE c_uid = '$r_customeruid'";
						
						$jdb->nQuery($qry_customer, "update error");

						//
						$logSTR = "tbl_daily[".$c_accountno."][r_driveruid=".$r_driveruid."][c_driveruid=".$c_driveruid."][".date("YmdHis")."]";
						addLog ("add", "REQUEST", "ADD", $lguserid, $logSTR, $lgno);	
		
			}
			
			
			$urlSTR = "/index_intranet.php?view=customer_detail&mode=update&c_uid=$r_customeruid&$goStr";
			//$func -> alertBack($msg);
			$func -> modalMsg ($msg, $urlSTR);
			exit();
}





/////////////////////////
// UPDATE PERSON INFO
/////////////////////////

if ($actionStr == "PERSONINFO") {

			if($mode == "update") {
						if($m_uid == "") {
							$msg = "Invalid data. Please try again.";
							$func -> modalMsg ($msg, "");
							exit();
						}
			}

			$columns = array();
			$values = array();
			
			if($mode == "create") {
						$columns[] = "m_userid";
						$columns[] = "m_signupdate";
			}

			$columns[] = "m_pwd";
			$columns[] = "m_firstname";
			$columns[] = "m_lastname";
			$columns[] = "m_cell";
			
			if ($actionPage == "ADMINUSERINFO") {
						$columns[] = "m_initial";				
						$columns[] = "m_status";
						$columns[] = "m_level";
						$columns[] = "m_comment";
			}
		
			////////////	
			// data
			////////////	
			if($mode == "create") {
						$values[] = trim($m_userid);
						$values[] = date("YmdHis");
			}
			
			$pwdSize = 50;
			$feed = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
			for ($i=0; $i < $pwdSize; $i++)
				$rand_str .= substr($feed, rand(0, strlen($feed)-1), 1); 
			
			$CRYPT_WORD = md5($rand_str);
			
			$hash = crypt($m_pwd,$CRYPT_WORD);
			//echo"[$rand_str]<br>[$CRYPT_WORD]<br>[$hash]";exit;
			
			$values[] = $hash;
			$values[] = str_replace("\\", "", trim($m_firstname));
			$values[] = str_replace("\\", "", trim($m_lastname));
			$values[] = str_replace("-", "", trim($m_cell));

			// password 입력없으면 password update 안함
			/*
			if ($user_password != "" && $user_password_chk != "") {
							if ($_SERVER["REMOTE_ADDR"] != "127.0.0.1") $user_passwordSTR = password_hash($user_password, PASSWORD_DEFAULT);
						else $user_passwordSTR = $user_password;
						
						$values[] = $user_passwordSTR;
			}
			*/

			if ($actionPage == "ADMINUSERINFO") {
						$values[] = $m_initial;
						$values[] = $m_status;
						$values[] = $m_level;		// Admin : 1, Manager : 3, Staff : 5, Accounting : 6, Sales : 7, Driver : 9
						$values[] = str_replace("\\", "", trim($m_comment));
			}


			for ($i=0; $i < count($columns); $i++)
			//echo "[$columns[$i]][$values[$i]]<br>";
			//echo "[UID=$uid][ID=$userid][MAXUID=$maxuid]";
			//exit;	
			
			if($mode == "create") {
						$jdb->iQuery("tbl_member", $columns, $values);
						$msg = "Created successfully.";

						$func -> modalMsg ($msg, "/index_intranet.php?view=view&$goStr");
						exit();
			}
			
			else if($mode == "update") {
						$jdb->uQuery("tbl_member", $columns, $values, " where m_uid = '$m_uid' ");
						$msg = "Updated successfully.";
						$func -> modalMsg ($msg, "/index_intranet.php?view=$view&$goStr");
						exit();
						
			}
			else {
						$msg = "Invalid data. Please try again.";
						$func -> modalMsg ($msg, "/index_intranet.php?view=$view&$goStr");
						exit();
			}		
			
			
			exit();

}


						

//////////////////////////////////////////////
// DAILY RECORD
//////////////////////////////////////////////

if ($actionStr == "DAILYRECORD") {

			if($h_driveruid == "" || $h_date == "" || $mode == "" ) {
					$msg = "Invaild data. Please try again. [Err - h_driveruid,h_date,mode / DAILYRECORD]";
					$urlSTR = "/index_intranet.php?view=order_list&".$goStr;
					$func -> modalMsg ($msg, $urlSTR);
					exit();
			} else {


					$columns = array();
					$values = array();

					$columns[] = "h_driveruid";
					$columns[] = "h_date";
					$columns[] = "h_departuretime";
					$columns[] = "h_arrivaltime";
					$columns[] = "h_mileage_s";
					$columns[] = "h_mileage_f";
					$columns[] = "h_balance_o";
					$columns[] = "h_balance_in";
					$columns[] = "h_balance_out";
					$columns[] = "h_balance_r";
					$columns[] = "h_balance_g";
					$columns[] = "h_balance_e";
					$columns[] = "h_balance_t";
					$columns[] = "h_createddate";
					$columns[] = "h_comment";

					// Data															

					$values[] = $h_driveruid;
					$values[] = $h_date;  
					$values[] = $h_departuretime;  
					$values[] = $h_arrivaltime;
					$values[] = $h_mileage_s;
					$values[] = $h_mileage_f;
					$values[] = $h_balance_o;  
					$values[] = $h_balance_in;  
					$values[] = $h_balance_out;
					$values[] = $h_balance_r;
					$values[] = $h_balance_g;
					$values[] = $h_balance_e;
					
					$h_balance_t = floatval($h_balance_o) + floatval($h_balance_in) - floatval($h_balance_r) - floatval($h_balance_out);
					$values[] = $h_balance_t;
					$values[] = date("YmdHis");;
					$values[] = str_replace("\\", "", trim($h_comment));



					//for ($i=0; $i < count($columns); $i++)
					//echo "[$columns[$i]][$values[$i]]<br>";
					//exit;	
					
					if($mode == "create") {
								$jdb->iQuery("tbl_memberhis", $columns, $values);
								$msg = "Saved successfully.";
								
								$urlSTR = "/index_intranet.php?view=order_list&".$goStr;
								$func -> modalMsg ($msg, $urlSTR);
								exit();
					}
					
					else if($mode == "update") {
								$jdb->uQuery("tbl_memberhis", $columns, $values, " where h_uid = '$h_uid' ORDER BY h_uid DESC LIMIT 1 ");
								$msg = "Updated successfully.";
								$urlSTR = "/index_intranet.php?view=order_list&".$goStr;
								$func -> modalMsg ($msg, $urlSTR);
								exit();
								
					}
					else {
								$msg = "Invalid data. Please try again.";
								$urlSTR = "/index_intranet.php?view=order_list&".$goStr;
								$func -> modalMsg ($msg, $urlSTR);
								exit();
					}		

					exit();
			
			}

			exit();
}



/////////////////////////
// xxx CHANGE PASSWORD
/////////////////////////

if ($actionStr == "USERINFO" && $actionPage == "ADMINUSERINFO" && $mode == "resetpassword") {
			if($uid == "") {
				$msg = "Invalid data. Please try again.";
				$func -> modalMsg ($msg, "");
				exit();
			}
			
			$hash = crypt(trim($reuserpwd),$CRYPT_WORD);
			
			$jdb->nQuery("UPDATE tbl_members SET userpwd='$hash' WHERE uid = '$uid'", "delete error");
			$jdb->CLOSE();
			
			$msg = "Updated successfully.";
			//$func -> alertBack($msg);
			$func -> modalMsg ($msg, "");
			exit();
}



/////////////////////////
// xxx DELETE - History
/////////////////////////

if ($actionStr == "USERHISFAV" && $mode == "delete") {
			if($fa_id == "") {
				$msg = "Invalid data. Please try again.";
				$func -> modalMsg ($msg, "");
				exit();
			}
//echo "[$fa_id]";exit;

			$jdb->nQuery("DELETE FROM tbl_favorite WHERE fa_id = '$fa_id'", "delete error");
			$jdb->CLOSE();
			$msg = "Deleted successfully.";	
			
			if ($actionFlag == "HIS") $urlSTR = "/index.php?view=myhistory&$goStr";
			else  $urlSTR = "/index.php?view=myfavorites&$goStr";
			
			$func -> modalMsg ($msg, $urlSTR);
			exit();
}


if ($actionStr == "SIGNATURE") {

			if($customeruid == "" || $orderdate == "") {
							$msg = "Invalid data. Please try again.";
							$func -> modalMsg ($msg, "");
							exit();
			}

			// Signiture
			if ($signednew == 1) $putSignFlag = 1;
			else {
					if ($d_payeesign == "" && $_POST['signed'] != "") $putSignFlag = 1;
					else $putSignFlag = 0;
			}

			//echo "[$signednew][$putSignFlag]";

			if ($putSignFlag == 1) {

					$folderPath = getenv("DOCUMENT_ROOT")."/upload_sign/".$customeruid;
					if (!is_dir($folderPath))  mkdir($folderPath, 0755, true);

					$image_parts = explode(";base64,", $_POST['signed']); 
					$image_type_aux = explode("image/", $image_parts[0]);
					$image_type = $image_type_aux[1];
					$image_base64 = base64_decode($image_parts[1]);
					$uniquevalue = uniqid();

					$qry_cnt = "SELECT COUNT(*) FROM tbl_daily WHERE d_uid = '".$uid."' ";
					$total_count=$jdb->rQuery($qry_cnt, "record query error");
										
					if ($total_count > 0) {
						$file = $folderPath ."/". $orderdate. "_". $uniquevalue . '.'.$image_type;
						$d_payeesignSTR = $orderdate. "_". $uniquevalue . '.'.$image_type;
						$qry_customer = "UPDATE tbl_daily 
														SET d_payeesign='$d_payeesignSTR', d_is_transfer='N'
														WHERE d_uid = '$uid'";
						
						$jdb->nQuery($qry_customer, "update error");

						// ==================== 
						// Integration to ERP 
						// ====================
						$columns = array();
						$values = array();
						$columns[] = "d_accountno";
						$columns[] = "d_orderdate";
						$columns[] = "d_payeesign";
						
						$values[] = $customerno;
						$values[] = $orderdate;
						$values[] = $d_payeesignSTR;
						
						$erp = new ErpApi();

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

							// 성공 시 플래그 & 로그
							$jdb->uQuery("tbl_daily", ["d_is_transfer"], ["Y"], " WHERE d_uid = '$d_uid'");
						} catch (Exception $e) {
							// 여기서는 아무것도 안함
						}
					}
					else {
						$file = $folderPath ."/". "T_". $orderdate. "_". $uniquevalue . '.'.$image_type;
						$d_payeesignSTR = "T_".$orderdate. "_". $uniquevalue . '.'.$image_type;
					}

					file_put_contents($file, $image_base64);
											
			}

			$msg = "Saved successfully.";	
			//$func -> modalMsg ($msg, "");
			echo "
				<script language=javascript>
				alert(\"".$msg."\");
				window.close();
				</script>";	
			exit();
}


$msg = "Invalid data. Please try again.";
$func -> modalMsg ($msg, "/index_intranet.php");
exit();
			
?>