<?php

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

//$func->checkAdmin("index.php");

//echo "[$mode]";exit();


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

if($mode == "update" && $d_uid == "") {
			echo 0;
			exit();
}

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

$columns[] = "d_orderdate";
$columns[] = "d_driveruid";
$columns[] = "d_inputdate";
$columns[] = "d_modifydate";
$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));
$values[] = $d_visitdate;	// d_orderdate
$values[] = $d_driveruid;
$values[] = date("YmdHis");  // d_inputdate
$values[] = date("YmdHis");  // d_modifydate
$values[] = $d_quantity;
$values[] = $d_sludge;
$values[] = $d_paystatus;
$values[] = $d_payamount;
$values[] = "Y";
$values[] = $d_visitdate."000000";  // d_visitdate
$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;
	
}



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

$jdb->uQuery("tbl_daily", $columns, $values, " where d_uid = '$d_uid' ");

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

// ==================== 
// Integration to ERP 
// ====================
$lguserid = $_SESSION['ss_UID'];
$columns[] = "d_accountno";    
$columns[] = "d_pickupnote";
$values[] = $_POST['d_customerno'];  // c_accountno
$values[] = str_replace("\\", "", trim($d_note));
try {
	$erp = new ErpApi();
	// ERP로 전송 (payload 내부에서 자동 매핑)
	$erp->updateDailyOrderFromMis($columns, $values, $lguserid);

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


////////////////////////////////////////////////////////////////////////////
// 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 c_lastpickupdate FROM tbl_customer WHERE c_uid = '$d_customeruid' ";
$rt_a=$jdb->fQuery($qry_a, "record query error");

$c_lastpickupdate = $rt_a['c_lastpickupdate'];

if ($d_visitdate >= $c_lastpickupdate) {
	$addQry_a = " c_lastpickupdate = '".$d_visitdate."', c_lastpickupquantity = '".$d_quantity."',";
	
	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");

addLog ("add", "ORDER PICKUP - ORDER", "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");
//}
			

////////////////////////////////////////////////////////////////////////////
// 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 의 c_schedulebasic 에 다음 일자 계산해서 저장
////////////////////////////////////////////////////////////////////////////

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;	

			$qry_note = "SELECT * FROM tbl_note WHERE n_dailyuid = '$d_uid' ";
			$rt_note=$jdb->fQuery($qry_note, "fetch query error");
		
			if ($rt_note[0] == "") $jdb->iQuery("tbl_note", $columns, $values);
			else $jdb->uQuery("tbl_note", $columns, $values, " where n_dailyuid = '$d_uid' ");
}

echo 1;
exit();


?>