<?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";
require_once getenv("DOCUMENT_ROOT")."/assets/conf.inc.php";
require_once getenv("DOCUMENT_ROOT")."/assets/dbCon.php";
include_once getenv("DOCUMENT_ROOT")."/assets/api/daily.php";
$dailyApi = new DailyService();

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

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

if ($actionStr == "PICKUPORDERCUSTOMER") {

    try {

        if ($c_uid == "") {
            throw new Exception("Invalid c_uid");
        }

        // customer 조회
        $qry = "SELECT c_uid, c_accountno, c_driveruid FROM tbl_customer WHERE c_uid = '$c_uid'";
        $cus = $jdb->fQuery($qry, "query error");

        if (!$cus) {
            throw new Exception("Customer not found");
        }

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

        $dailyApi = new DailyService();

        // payload만 구성
        $payload = [
            'd_orderdate'    => $d_visitdate,
            'd_accountno'    => $cus['c_accountno'],
            'd_customeruid'  => $c_uid,
            'd_driveruid'    => $d_driveruid,
            'd_ordertype'    => 'N',
            'd_ruid'         => '',
            'd_quantity'     => $d_quantity,
            'd_sludge'       => $d_sludge,
            'd_paystatus'    => $d_paystatus,
            'd_payamount'    => number_format(floatval($d_payamount), 2, '.', ','),
            'd_visit'        => 'Y',
            'd_visitdate'    => $d_visitdateSTR,
            'd_status'       => 'F',
            'd_druid'        => $d_druid,
            'd_payeename'    => $d_payeename,
            'd_note'         => str_replace("\\", "", trim($d_note)),
            'd_createruid'   => $_SESSION['ss_UID'],
            'd_inputdate'    => date("YmdHis"),
			'd_jobtype'      => $d_jobtype ?? 'UCO',
        ];

        // 기존 record update 대응
        if (!empty($d_uid)) {
            $opt = [
				'match_uid' => $d_uid,
    			'allow_update' => true
			];
        } else {
            $opt = [];
        }

        $dailyApi->saveDaily($payload, $opt);

        // signature 처리만 별도 유지
        if ($signednew == 1 || ($d_payeesign == "" && $_POST['signed'] != "")) {

            $folderPath = getenv("DOCUMENT_ROOT")."/upload_sign/".$c_uid;
            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();

            $filename = substr($d_visitdate,0,8). "_". $uniquevalue . '.'.$image_type;
            $file = $folderPath ."/". $filename;

            file_put_contents($file, $image_base64);

            // saveDaily로 update 한번 더
            $dailyApi->saveDaily([
				'd_orderdate' => $d_visitdate,
				'd_accountno' => $cus['c_accountno'],
				'd_payeesign' => $filename,
				'd_jobtype'   => $d_jobtype ?? 'UCO',
			], [
				'match_uid' => $d_uid,
				'allow_update' => true
			]);
        }

        $msg = "Saved Successfully.";
        $urlSTR = "/index_intranet.php?view=customer_list&".$goStr;

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

    } catch (Exception $e) {

        $func->modalMsg($e->getMessage(), "");
    }

    exit();
}

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

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

    // 권한 체크
    $permit = array("1", "5", "9");
    if (!in_array($_SESSION['ss_LEVEL'], $permit)) {
        $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();
    }

    // daily 정보 조회
    $sqDaily = $jdb->fQuery("
        SELECT d_orderdate, d_accountno, d_jobtype
        FROM tbl_daily
        WHERE d_uid = '{$d_uid}'
        LIMIT 1
    ", "fetch error");

    if (!$sqDaily) {
        $msg = "Daily record not found.";
        $func->modalMsg($msg, "");
        exit();
    }

    // deleteDaily 호출
    $dailyApi->deleteDaily(
        $sqDaily['d_orderdate'],
        $sqDaily['d_accountno'],
		$sqDaily['d_jobtype']
    );

    // 메시지 및 리다이렉트
    $msg = "Deleted successfully.";

    $urlSTR = "/index_intranet.php?view=order_driver&".$goSTRSTR."&".$goStr;
    $func->modalMsg($msg, $urlSTR);
    exit();
}

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

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

    try {

        if ($orderdate == "") {
            throw new Exception("Invalid order date");
        }

        if (count($selectaccountno) == 0) {
            throw new Exception("No selected data");
        }

        rsort($selectaccountno);

        $dailyApi = new DailyService();

        foreach ($selectaccountno as $value) {

            $valueSTR = explode("|", $value);

            $accountno = $valueSTR[1];

            // customer uid 조회
            $qry = "SELECT c_uid, c_driveruid 
                    FROM tbl_customer 
                    WHERE c_accountno = '$accountno'";
            $cus = $jdb->fQuery($qry, "query error");

            if (!$cus) {
                throw new Exception("Customer not found");
            }

            // payload만 구성
            $payload = [
                'd_orderdate'    => $orderdate,
                'd_accountno'    => $accountno,
                'd_customeruid'  => $cus['c_uid'],
                'd_driveruid'    => $cus['c_driveruid'],
                'd_ordertype'    => $valueSTR[0],
                'd_ruid'         => $valueSTR[2],
                'd_createruid'   => $_SESSION['ss_UID'],
                'd_createddate'  => date("YmdHis"),
                'd_status'       => 'A',
				'd_jobtype'      => 'UCO'
            ];

            // saveDaily 호출 (중복 skip 포함)
			$result = $dailyApi->saveDaily($payload, [
				'allow_update' => false
			]);

			if ($result === null) {
				continue; // duplicate skip
			}
        }

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

    } catch (Exception $e) {

        $func->modalMsg($e->getMessage(), "/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();
}



//////////////////////////////////////////////
// DELETE DRIVER INFO (dr_status 만 D 로 변경)
//////////////////////////////////////////////

if ($actionStr == "DRIVERINFO" && $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($dr_uid == "") {
				$msg = "Invalid data. Please try again.";
				$func -> modalMsg ($msg, "");
				exit();
			}
			
			
			$jdb->nQuery("UPDATE tbl_driver SET dr_status='D' WHERE dr_uid = '$dr_uid'", "delete error");
			$jdb->CLOSE();
			
			$msg = "Deleted successfully.";
			$urlSTR = "/index_intranet.php?view=driver_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") {
	$singleTypes = ['install', 'container', 'install_order'];

	$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 (in_array($i_type, $singleTypes)) {
        $qry_update = "
            UPDATE tbl_customer_image
            SET i_status = 'I'
            WHERE i_customeruid = '$i_customeruid'
			AND i_type = '$i_type'
              AND i_status = 'A'
        ";
        $jdb->nQuery($qry_update, "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 = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
		$allowedExt = ['jpg', 'jpeg', 'png', 'webp'];
        if (!in_array($ext, $allowedExt)) continue;

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

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

        // 이미지 압축 + 리사이즈 저장
        if (!compressAndResizeImage($fileTmp, $savePath, $ext, 1200, 75)) {
            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",
		"i_sourceuid"
    );

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

    $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 = strtolower(pathinfo($_FILES['upload_file']['name'][$i], PATHINFO_EXTENSION));

			$allowedExt = ['jpg', 'jpeg', 'png', 'webp'];
			if (!in_array($ext, $allowedExt)) continue;

			// 파일명 jpg로 통일
			$newName = "IMG_".$i_customeruid."_".time().rand(1000,9999)."_".$i.".jpg";

			$savePath = $upload_folder . $newName;

			// 압축 + 리사이즈
			if (compressAndResizeImage($_FILES['upload_file']['tmp_name'][$i], $savePath, $ext, 1200, 75)) {
				$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") {

    try {

        $func->checkLevelModal(9);

        if ($r_customeruid == "" || $r_memberuid == "") {
            throw new Exception("Invalid data");
        }

        $r_requestdateSTR = str_replace("-", "", trim($r_requestdate));

        // 중복 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) {
            throw new Exception("Duplicated request");
        }

        // 미래 daily 존재 체크
        $qry_cntd = "SELECT d_orderdate FROM tbl_daily
                     WHERE d_customeruid = '$r_customeruid' 
                     	AND d_orderdate >= '".date("Ymd")."' 
						AND d_jobtype = 'UCO'
                     LIMIT 1";

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

        if ($rt_d['d_orderdate'] != "") {
            throw new Exception("Order already exists");
        }

        // =========================
        // 1. REQUEST 저장
        // =========================

        $qry = "SELECT c_accountno, c_name FROM tbl_customer WHERE c_uid = '$r_customeruid'";
        $cus = $jdb->fQuery($qry, "query error");

        if (!$cus) {
            throw new Exception("Customer not found");
        }

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

        $values = [
            $r_memberuid,
            $r_requestdateSTR,
            $r_customeruid,
            $cus['c_accountno'],
            $cus['c_name'],
            $r_driveruid,
            $r_druid,
            date("YmdHis"),
            str_replace("\\", "", trim($r_note))
        ];

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

        // r_uid 가져오기
        $rt_max = $jdb->fQuery("SELECT max(r_uid) FROM tbl_request", "error");
        $r_uidMAX = $rt_max[0];

        // =========================
        // 2. DAILY 생성
        // =========================

        if ($r_requestdateSTR >= date("Ymd")) {

            $dailyApi = new DailyService();

            $payload = [
                'd_orderdate'    => $r_requestdateSTR,
                'd_accountno'    => $cus['c_accountno'],
                'd_customeruid'  => $r_customeruid,
                'd_driveruid'    => $r_driveruid,
                'd_ordertype'    => 'R',
                'd_ruid'         => $r_uidMAX,
                'd_druid'        => $r_druid,
                'd_createruid'   => $_SESSION['ss_UID'],
                'd_createddate'  => date("YmdHis"),
                'd_status'       => 'A',
				'd_jobtype'      => 'UCO'
            ];

            $dailyApi->saveDaily($payload);
        }

        $msg = "Created successfully.";
        $urlSTR = "/index_intranet.php?view=customer_detail&mode=update&c_uid=$r_customeruid&$goStr";

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

    } catch (Exception $e) {

        $func->modalMsg($e->getMessage(), "");
    }

    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_druid == "" || $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";
					$columns[] = "h_druid";

					// 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));
					$values[] = $h_druid;



					//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();
}

function compressAndResizeImage($srcPath, $destPath, $ext, $maxWidth = 1200, $quality = 75) {
    list($width, $height, $imageType) = getimagesize($srcPath);

    if (!$width || !$height) return false;

    switch ($imageType) {
        case IMAGETYPE_JPEG:
            $srcImg = imagecreatefromjpeg($srcPath);
            break;
        case IMAGETYPE_PNG:
            $srcImg = imagecreatefrompng($srcPath);
            break;
        case IMAGETYPE_WEBP:
            if (!function_exists('imagecreatefromwebp')) return false;
            $srcImg = imagecreatefromwebp($srcPath);
            break;
        default:
            return false;
    }

    if (!$srcImg) return false;

    if ($width > $maxWidth) {
        $newWidth = $maxWidth;
        $newHeight = intval(($height / $width) * $newWidth);
    } else {
        $newWidth = $width;
        $newHeight = $height;
    }

    $dstImg = imagecreatetruecolor($newWidth, $newHeight);

    if ($imageType == IMAGETYPE_PNG || $imageType == IMAGETYPE_WEBP) {
        imagealphablending($dstImg, false);
        imagesavealpha($dstImg, true);
        $transparent = imagecolorallocatealpha($dstImg, 0, 0, 0, 127);
        imagefilledrectangle($dstImg, 0, 0, $newWidth, $newHeight, $transparent);
    }

    imagecopyresampled(
        $dstImg, $srcImg,
        0, 0, 0, 0,
        $newWidth, $newHeight,
        $width, $height
    );

    $result = imagejpeg($dstImg, $destPath, $quality);

    imagedestroy($srcImg);
    imagedestroy($dstImg);

    return $result;
}


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