<?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";

$goStr = "switched=$switched&page=$page&key_word=$key_word&column=$column&sorting_type=$sorting_type&switch=$switch&cstatus=$cstatus";


/*
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;
*/


//////////////////////////////////////////////
// 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();
			}
			
			
			$jdb->nQuery("UPDATE tbl_customer SET c_status='D', c_is_transfer = 'N' WHERE c_uid = '$c_uid'", "delete error");

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





/////////////////////////
// INSERT / UPDATE
/////////////////////////

if ($actionStr == "CUSTOMERINFO") {

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

			$columns = array();
			$values = array();
			
			if($mode == "create") {
						//$columns[] = "c_uid";
						$columns[] = "c_createddate";
			}
			$columns[] = "c_accountno";
			//$columns[] = "c_gid";
			$columns[] = "c_form_us";
			$columns[] = "c_form_eu";
			$columns[] = "c_form_corsia";
			$columns[] = "c_form_new";
			$columns[] = "c_driveruid";
			$columns[] = "c_name";
			$columns[] = "c_paymenttype";
			$columns[] = "c_payableto";
			$columns[] = "c_paymentcycle";
			$columns[] = "c_mailingaddr";
			$columns[] = "c_rate";
			$columns[] = "c_mainvolume";
			$columns[] = "c_maincontainer";
			$columns[] = "c_container";
			$columns[] = "c_location";
			$columns[] = "c_phone";
			$columns[] = "c_phoneext";
			$columns[] = "c_cell";
			$columns[] = "c_email";
			$columns[] = "c_address";
			$columns[] = "c_city";
			$columns[] = "c_postal";
			//$columns[] = "c_area";
			$columns[] = "c_province";
			$columns[] = "c_contractdate";
			$columns[] = "c_contractby";
			$columns[] = "c_installdate";
			$columns[] = "c_schedule";
			$columns[] = "c_scheduleday";
			$columns[] = "c_schedulebasic";
			$columns[] = "c_fpickup";
			$columns[] = "c_salesperson";
			$columns[] = "c_salescommissiondate";
			$columns[] = "c_salesmethod";
			$columns[] = "c_status";

			$columns[] = "c_comment_ri";
			$columns[] = "c_comment_ci";
			$columns[] = "c_fullcycle";
			$columns[] = "c_fullcycleforced";
			$columns[] = "c_fullcycleflag";
			$columns[] = "c_forceddate";
			$columns[] = "c_sludge";
			
			$columns[] = "c_removaldate";
			$columns[] = "c_inactivedate";
			$columns[] = "c_exchangedate";
			$columns[] = "c_switchformdate";

			$columns[] = "c_expoilmonth";
			$columns[] = "c_hstno";
			$columns[] = "c_identcode";
			// integration flag
			$columns[] = "c_is_transfer";
			
			////////////	
			// data
			////////////	
			if($mode == "create") {
						//$values[] = $c_uid;
						$values[] = date("YmdHis");
			}
			$values[] = $c_accountno;
			//$values[] = $c_gid;
			$values[] = $c_form_us;
			$values[] = str_replace("-", "", trim($c_form_eu));
			$values[] = str_replace("-", "", trim($c_form_corsia));
			$values[] = $c_form_new;
			$values[] = $c_driveruid;
			$values[] = str_replace("\\", "", trim($c_name));
			$values[] = $c_paymenttype;
			$values[] = str_replace("\\", "", trim($c_payableto));
			$values[] = $c_paymentcycle;
			$values[] = str_replace("\\", "", trim($c_mailingaddr));
			$values[] = $c_rate;
			$values[] = $c_mainvolume;
			$values[] = str_replace("\\", "", trim($c_maincontainer));
			$values[] = str_replace("\\", "", trim($c_container));
			$values[] = str_replace("\\", "", trim($c_location));
			
			$c_phone = str_replace("-", "", trim($c_phone));
			
			$values[] = str_replace("\\", "", trim($c_phone));
			$values[] = str_replace("\\", "", trim($c_phoneext));
			$values[] = str_replace("\\", "", trim($c_cell));
			$values[] = str_replace("\\", "", trim($c_email));
			$values[] = str_replace("\\", "", trim($c_address));
			$values[] = str_replace("\\", "", trim($c_city));
			$values[] = str_replace("\\", "", trim($c_postal));
			//$values[] = $c_area;
			$values[] = "ON";
			$values[] = str_replace("-", "", trim($c_contractdate));
			$values[] = str_replace("\\", "", trim($c_contractby));
			$values[] = str_replace("-", "", trim($c_installdate));
			$values[] = $c_schedule;

			if(isset($_POST["c_scheduleday"])){
			    $c_scheduleday_vals ="";
			    foreach($_POST["c_scheduleday"] as $key => $text_field){
			        $c_scheduleday_vals .= $text_field ."|";
			    }
			}
			
			$values[] = $c_scheduleday_vals;
			$values[] = $c_schedulebasic;
			$values[] = str_replace("-", "", trim($c_fpickup));
			$values[] = str_replace("\\", "", trim($c_salesperson));
			$values[] = str_replace("-", "", trim($c_salescommissiondate));
			$values[] = str_replace("\\", "", trim($c_salesmethod));
			$values[] = $c_status;
			$values[] = str_replace("\\", "", trim($c_comment_ri));
			$values[] = str_replace("\\", "", trim($c_comment_ci));
			$values[] = $c_fullcycle;
			$values[] = $c_fullcycleforced;
			
			if ($c_fullcycleforced != "" && (float)$c_fullcycleforced != 0) $c_fullcycleflag = 1;
			else $c_fullcycleflag = 0;
			$values[] = $c_fullcycleflag;
			

			if ($mode == "update" && $c_fullcycleflag == 1) {
					$qry_n = "SELECT c_fullcycleforced FROM tbl_customer WHERE c_uid = '$c_uid' ";
					$rt_n = $jdb->fQuery($qry_n, "list error");
			}
			
			$values[] = $c_forceddate;
			
			$values[] = $c_sludge;

			$values[] = str_replace("-", "", trim($c_removaldate));
			$values[] = str_replace("-", "", trim($c_inactivedate));
			$values[] = str_replace("-", "", trim($c_exchangedate));
			$values[] = str_replace("-", "", trim($c_switchformdate));

			$values[] = $c_expoilmonth;
			$values[] = str_replace("\\", "", trim($c_hstno));
			$values[] = str_replace("\\", "", trim($c_identcode));
			// c_is_transfer
			$values[] = "N";

			//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_customer", $columns, $values);
						$msg = "Created successfully.";

						$query = "SELECT max(c_uid) FROM tbl_customer ";
						$rt=$jdb->fQuery($query, "fetch query error");
						
						$c_uid = $rt[0];

						addLog ("add", "CUSTOMER DETAIL", "CREATE", $lguserid, "", $c_uid);
						
						//$query = "select max(uid) from tbl_members ";
						//$user_id = $jdb->rQuery($query, "max query error");
			}
			
			else if($mode == "update") {
						
						$query = "SELECT c_uid, c_driveruid, c_address, c_postal, c_fullcycleforced FROM tbl_customer WHERE c_uid = '$c_uid' ";
						$rt=$jdb->fQuery($query, "fetch query error");
						
						$c_uid = $rt[0];
						$c_driveruid_old = $rt[1];
						
						if ($c_fullcycleflag == 1) {
								$c_fullcycleforcedSTR = "Org: ".$rt[4].", New: ".$c_fullcycleforced;
								addLog ("add", "FORCED CYCLE - CUSTOMER", "UPDATE", $lguserid, $c_fullcycleforcedSTR, $c_uid);
						}

						// c_address, c_postal 변경시 geo 값 초기화 (2024.06.05)
						if (str_replace("\\", "", trim($c_address)) != str_replace("\\", "", $rt['c_address']) || 
								str_replace("\\", "", trim($c_postal)) != str_replace("\\", "", $rt['c_postal'] )) {
									
									$qry_geo = "UPDATE tbl_customer SET c_geolat=NULL, c_geolon=NULL WHERE c_uid = '".$c_uid."'";
									$jdb->nQuery($qry_geo, "Update error");
									
									addLog ("add", "CUSTOMER DETAIL - GEO RESET", "UPDATE", $lguserid, $qry_geo, $c_uid);
						}



						$jdb->uQuery("tbl_customer", $columns, $values, " where c_uid = '$c_uid' ");
						$msg = "Updated successfully.";

						addLog ("add", "CUSTOMER DETAIL", "UPDATE", $lguserid, "", $c_uid);

			
						// Sludge, rate, paymentcycle Update - 오늘 이후 오더장에만 적용한다. by 이강 2025-12-09
						$today = date("Ymd");
						$qry_sludge = "UPDATE tbl_daily 
													SET 
													d_rate='".$c_rate."', 
													d_cycle='".$c_paymentcycle."', 
													d_paymenttype='".$c_paymenttype."' 
													WHERE d_customeruid = '".$c_uid."'
													and d_orderdate > '".$today."'
													";
						$jdb->nQuery($qry_sludge, "Update error");
				
						addLog ("add", "CUSTOMER DETAIL - SLUDGE, RATE, PAYMENTCYCLE, PAYMENTTYPE", "UPDATE", $lguserid, $qry_sludge, $c_uid);

						// 모든 테이블의 드라이버 정보 업데이트
						// customer page 에서 driver 정보 업데이트시 현재일을 포함한 그 이후의 오더장이 존재하는 경우 
						// 오더장의 driver를 변경된 driver로 업데이트. (2024.04.05)
   					// Request 도 현재일을 포함한 그 이후의 데이터가 존재하는 경우 변경된 driver 로 업데이트. (2024.04.05)
						if ($c_driveruid != $c_driveruid_old) {
							
								$addqry_daily = " AND d_orderdate >= '".date("Ymd")."'";
								
								$qry_driverd = "UPDATE tbl_daily SET d_driveruid='".$c_driveruid."' WHERE d_customeruid = '".$c_uid."'". $addqry_daily;
								$jdb->nQuery($qry_driverd, "Update error");

								addLog ("add", "CUSTOMER DETAIL - SLUDGE, RATE, PAYMENTCYCLE, PAYMENTTYPE", "UPDATE", $lguserid, $qry_driverd, $c_uid);
 	
 								$addqry_req = " AND r_requestdate >= '".date("Ymd")."'";
 								
								$qry_driverr = "UPDATE tbl_request SET r_driveruid='".$c_driveruid."' 
																WHERE r_driveruid = '".$c_driveruid_old."' AND r_customeruid = '".$c_uid."'". $addqry_req;								
								$jdb->nQuery($qry_driverr, "Update error");
								
								addLog ("add", "CUSTOMER DETAIL - SLUDGE, RATE, PAYMENTCYCLE, PAYMENTTYPE", "UPDATE", $lguserid, $qry_driverr, $c_uid);
								
						}
			}
			// ====================
			// Integration to ERP
			// ====================
			$erp = new ErpApi();

			try {

				if ($mode == "create") {
					// MIS → ERP CREATE (payload 매핑은 ErpApi 내부에서 자동 처리)
					$erp->createCustomerFromMis($columns, $values, $lguserid);
				}
				else if ($mode == "update") {
					// MIS → ERP UPDATE
					$erp->updateCustomerFromMis($columns, $values, $lguserid);
				}

				// 성공 시 c_is_transfer='Y'
				$jdb->uQuery("tbl_customer", ["c_is_transfer"], ["Y"], " WHERE c_uid = '$c_uid'");

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

			} catch (Exception $e) {
				$msg = "Check Integration Log.";
				$func->modalMsg($msg, "/index_intranet.php");
				exit();
			}

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

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



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