<?php
include_once('./_common.php');

if (!function_exists('apms_partner_detect_item_scope_for_update')) {
    function apms_partner_detect_item_scope_for_update($post)
    {
        $sales_type = isset($post['it_spec_sales_type']) ? trim((string)$post['it_spec_sales_type']) : '';
        $ca_id = isset($post['ca_id']) ? trim((string)$post['ca_id']) : '';

        if ($sales_type === 'vpn-mall') {
            return 'vpn';
        }
        if ($sales_type !== '' && stripos($sales_type, '원격제어컴퓨터') !== false) {
            return 'rpc';
        }

        if ($ca_id !== '') {
            if (preg_match('/^(30|40)/', $ca_id)) {
                return 'vpn';
            }
            if (preg_match('/^(10|20)/', $ca_id)) {
                return 'rpc';
            }
        }

        $it_id = isset($post['it_id']) ? trim((string)$post['it_id']) : '';
        if ($it_id !== '') {
            global $g5;
            $it_id_sql = preg_replace('/[^0-9A-Za-z_\-]/', '', $it_id);
            $row = sql_fetch(" select it_spec_sales_type, ca_id, it_name from {$g5['g5_shop_item_table']} where it_id = '{$it_id_sql}' ");
            if ($row) {
                if (trim((string)$row['it_spec_sales_type']) === 'vpn-mall') {
                    return 'vpn';
                }
                if (stripos(trim((string)$row['it_spec_sales_type']), '원격제어컴퓨터') !== false) {
                    return 'rpc';
                }
                if (preg_match('/^(30|40)/', trim((string)$row['ca_id']))) {
                    return 'vpn';
                }
                if (preg_match('/^(10|20)/', trim((string)$row['ca_id']))) {
                    return 'rpc';
                }
                if (stripos(trim((string)$row['it_name']), 'VPN-') === 0) {
                    return 'vpn';
                }
                if (stripos(trim((string)$row['it_name']), 'RPC-') === 0) {
                    return 'rpc';
                }
            }
        }

        return 'rpc';
    }
}

$__apms_item_scope = apms_partner_detect_item_scope_for_update($_POST);
if ($__apms_item_scope !== 'vpn') {
    include_once('./itemformupdate.php');
    return;
}

if($is_guest) {
	alert('판매자센터만 이용가능합니다.', APMS_PARTNER_URL.'/login.php');
}

$is_auth = ($is_admin == 'super') ? true : false;
$is_partner = (IS_SELLER) ? true : false;

if($is_auth || $is_partner) {
	; // 통과
} else {
	alert('판매자(셀러) 판매자센터만 이용가능합니다.', APMS_PARTNER_URL);
}

@mkdir(G5_DATA_PATH."/item", G5_DIR_PERMISSION);
@chmod(G5_DATA_PATH."/item", G5_DIR_PERMISSION);

// input vars 체크
check_input_vars();

if (!$_POST['pt_it'])
    alert("서비스종류를 선택해 주십시오.");

if(in_array($pt_it, $g5['apms_automation'])) {
	$it_sc_type = 0;
	$it_sc_method = 0;
	$it_sc_price = 0;
	$it_sc_minimum = 0;
	$it_sc_qty = 0;
}

$upload_max_filesize = number_format($default['pt_upload_size']) . ' Bytes';

//판매자센터 등록정보
$pt = array();
$pt = apms_partner($member['mb_id']);

    // VPN 상품 선택한 프로토콜(remoteProgram)값에 기반하여 ca_id(카테고리) 자동 매칭/설정 (JSLEE)
    $vpn_protocol_selected = isset($_POST['remoteProgram'][0]) ? strip_tags(clean_xss_attributes($_POST['remoteProgram'][0])) : '';

    if($vpn_protocol_selected) {
         // 3020 시리즈(Client)에서 해당 프로토콜 이름을 포함하는 카테고리 검색
         // 예: "IKEv2-Client"
         $sql_find_ca = " select ca_id from {$g5['g5_shop_category_table']} where ca_id like '3020%' and length(ca_id)=6 and ca_name = '{$vpn_protocol_selected}' order by ca_order, ca_id limit 1 ";
         $row_find_ca = sql_fetch($sql_find_ca);
         if($row_find_ca['ca_id']) {
             $ca_id = $row_find_ca['ca_id'];
         } else {
             // 매칭되는 카테고리가 없으면 기본 처리 (30 -> 302010 : IKEv2-Client)
             if($ca_id == '30') $ca_id = '302010';
         }
    } else {
         if($ca_id == '30') $ca_id = '302010';
    }

    $ca_id_tmp = $ca_id;
    $ca_id = substr($ca_id_tmp,0,2);
    $ca_id2 = substr($ca_id_tmp,0,4);
    $ca_id3 = $ca_id_tmp;

// 등록제한 체크
$is_regit = 0;
$new_upoint = 0;
if(!$is_auth && $w != "u") {

	$upoint_where = "";
	if($ca_id) {
		$upoint_where .= " ca_id = '{$ca_id}' ";
	}
	if($upoint_where && $ca_id2) {
		$upoint_where .= " or ";
	}
	if($ca_id2) {
		$upoint_where .= " ca_id = '{$ca_id2}' ";
	}
	if($upoint_where && $ca_id3) {
		$upoint_where .= " or ";
	}
	if($ca_id3) {
		$upoint_where .= " ca_id = '{$ca_id3}' ";
	}
	if($upoint_where) {
		$upoint_where = "and (".$upoint_where.")";
	}

	// 등록제한 체크 - 가장 작은 등록제한설정을 가져옴
	$row = sql_fetch("select ca_id, ca_name, pt_limit from {$g5['g5_shop_category_table']} where pt_limit > 0 $upoint_where order by pt_limit");
	$uplimit = ($pt['pt_limit']) ? (int)$pt['pt_limit'] : $row['pt_limit'];
	$uplimit_ca = $row['ca_id'];
	$uplimit_name = $row['ca_name'];

	if($uplimit) { // 제한값이 있으면...
		$row = sql_fetch(" select count(*) as cnt from {$g5['g5_shop_item_table']} where pt_id = '{$member['mb_id']}' and date_format(it_time, '%Y-%m-%d') = '".G5_TIME_YMD."' and (ca_id = '{$uplimit_ca}' or ca_id2 = '{$uplimit_ca}' or ca_id3 = '{$uplimit_ca}') ");
		if($row['cnt'] && $row['cnt'] >= $uplimit) {
		    alert("선택하신 분류 중 ".$uplimit_name." 분류는 하루 최대 ".$uplimit."개까지만 등록이 가능합니다.\\n\\n등록갯수 초과로 오늘은 더이상 등록할 수 없습니다.");
		}
	}

	// 등록비 체크	-가장 큰 등록비를 가져옴
	$row1 = sql_fetch(" select ca_id, pt_point from {$g5['g5_shop_category_table']} where pt_point > 0 $upoint_where order by pt_point desc ");

	$upoint = (int)$pt['pt_point'] + (int)$row1['pt_point'];

	if($upoint) {
		$new_upoint = $upoint * (-1); //부호 전환
		if($w == "u") {
			//기존 내역
			$row2 = sql_fetch(" select po_point from {$g5['point_table']} where mb_id = '{$member['mb_id']}' and po_rel_table = '@regit' and po_rel_id = '{$member['mb_id']}' and po_rel_action = '$it_id' order by po_id desc ");
			$old_upoint = $row2['po_point'];
			if($old_upoint) {
				if($new_upoint != $old_upoint) { // 서로 값이 다르면...
					$now_point = $member['mb_point'] - $old_upoint + $new_upoint;
					if($now_point < 0) { //포인트가 부족하면
						$now_point = $now_point * (-1);
					    alert("보유포인트 부족으로 등록할 수 없습니다.\\n\\n{$now_point} 포인트가 더 있어야 등록할 수 있습니다.");
					}
					$is_regit = 2;
				}
			} else {
				$now_point = $member['mb_point'] + $new_upoint;
				if($now_point < 0) { //포인트가 부족하면
					$now_point = $now_point * (-1);
				    alert("보유포인트 부족으로 등록할 수 없습니다.\\n\\n{$now_point} 포인트가 더 있어야 등록할 수 있습니다.");
				}
				$is_regit = 1;
			}
		} else {
			$now_point = $member['mb_point'] + $new_upoint;
			if($now_point < 0) { //포인트가 부족하면
				$now_point = $now_point * (-1);
			    alert("보유포인트 부족으로 등록할 수 없습니다.\\n\\n{$now_point} 포인트가 더 있어야 등록할 수 있습니다.");
			}
			$is_regit = 1;
		}
	}
}

// 파일정보
if($w == "u") {
    $sql = " select it_img1, it_img2, it_img3, it_img4, it_img5, it_img6, it_img7, it_img8, it_img9, it_img10
                from {$g5['g5_shop_item_table']}
                where it_id = '$it_id' ";
    $file = sql_fetch($sql);

    $it_img1    = $file['it_img1'];
    $it_img2    = $file['it_img2'];
    $it_img3    = $file['it_img3'];
    $it_img4    = $file['it_img4'];
    $it_img5    = $file['it_img5'];
    $it_img6    = $file['it_img6'];
    $it_img7    = $file['it_img7'];
    $it_img8    = $file['it_img8'];
    $it_img9    = $file['it_img9'];
    $it_img10   = $file['it_img10'];
}

$it_img_dir = G5_DATA_PATH.'/item';

// 파일삭제
if ($it_img1_del) {
    $file_img1 = $it_img_dir.'/'.clean_relative_paths($it_img1);
    @unlink($file_img1);
    delete_item_thumbnail(dirname($file_img1), basename($file_img1));
    $it_img1 = '';
}
if ($it_img2_del) {
    $file_img2 = $it_img_dir.'/'.clean_relative_paths($it_img2);
    @unlink($file_img2);
    delete_item_thumbnail(dirname($file_img2), basename($file_img2));
    $it_img2 = '';
}
if ($it_img3_del) {
    $file_img3 = $it_img_dir.'/'.clean_relative_paths($it_img3);
    @unlink($file_img3);
    delete_item_thumbnail(dirname($file_img3), basename($file_img3));
    $it_img3 = '';
}
if ($it_img4_del) {
    $file_img4 = $it_img_dir.'/'.clean_relative_paths($it_img4);
    @unlink($file_img4);
    delete_item_thumbnail(dirname($file_img4), basename($file_img4));
    $it_img4 = '';
}
if ($it_img5_del) {
    $file_img5 = $it_img_dir.'/'.clean_relative_paths($it_img5);
    @unlink($file_img5);
    delete_item_thumbnail(dirname($file_img5), basename($file_img5));
    $it_img5 = '';
}
if ($it_img6_del) {
    $file_img6 = $it_img_dir.'/'.clean_relative_paths($it_img6);
    @unlink($file_img6);
    delete_item_thumbnail(dirname($file_img6), basename($file_img6));
    $it_img6 = '';
}
if ($it_img7_del) {
    $file_img7 = $it_img_dir.'/'.clean_relative_paths($it_img7);
    @unlink($file_img7);
    delete_item_thumbnail(dirname($file_img7), basename($file_img7));
    $it_img7 = '';
}
if ($it_img8_del) {
    $file_img8 = $it_img_dir.'/'.clean_relative_paths($it_img8);
    @unlink($file_img8);
    delete_item_thumbnail(dirname($file_img8), basename($file_img8));
    $it_img8 = '';
}
if ($it_img9_del) {
    $file_img9 = $it_img_dir.'/'.clean_relative_paths($it_img9);
    @unlink($file_img9);
    delete_item_thumbnail(dirname($file_img9), basename($file_img9));
    $it_img9 = '';
}
if ($it_img10_del) {
    $file_img10 = $it_img_dir.'/'.clean_relative_paths($it_img10);
    @unlink($file_img10);
    delete_item_thumbnail(dirname($file_img10), basename($file_img10));
    $it_img10 = '';
}

// 이미지업로드
// it_img1 이미지는 사용자가 임의로 업로드 시킨 경우에는 그 이미지 파일을 사용하고 그렇지 않을 경우 ca_id3 의 코드를 참고하여 미리 설정된 이미지 사용하도록 else 추가하여 수정함 JSLEE
if ($_FILES['it_img1']['name']) {
    if($w == 'u' && $it_img1) {
        $file_img1 = $it_img_dir.'/'.clean_relative_paths($it_img1);
        @unlink($file_img1);
        delete_item_thumbnail(dirname($file_img1), basename($file_img1));
    }
    $it_img1 = it_img_upload($_FILES['it_img1']['tmp_name'], $_FILES['it_img1']['name'], $it_img_dir.'/'.$it_id);
} else {
    $row_ca_name = sql_fetch(" SELECT ca_name FROM {$g5['g5_shop_category_table']} WHERE ca_id = '{$ca_id3}' ");
    $ca_name = $row_ca_name['ca_name'];
    $vpn_protocol = isset($_POST['remoteProgram'][0]) ? strip_tags(clean_xss_attributes($_POST['remoteProgram'][0])) : '';

    if(strpos($vpn_protocol, "IKEv2") !== false) {
        $it_img1 = 'img_os/IKEv2.png';
    }
    else if(strpos($vpn_protocol, "L2TP") !== false) {
        $it_img1 = 'img_os/L2TP_IPsec.png';
    }
    else if(strpos($vpn_protocol, "OpenVPN") !== false) {
        $it_img1 = 'img_os/OpenVPN.png';
    }
    else if(strpos($vpn_protocol, "PPTP") !== false) {
        $it_img1 = 'img_os/PPTP.png';
    }
    else if(strpos($vpn_protocol, "WireGuard") !== false) {
        $it_img1 = 'img_os/WireGuard.png';
    }
    else  {
        $it_img1 = 'img_os/Etc_VPN.png';
    }
}

if ($_FILES['it_img2']['name']) {
    if($w == 'u' && $it_img2) {
        $file_img2 = $it_img_dir.'/'.clean_relative_paths($it_img2);
        @unlink($file_img2);
        delete_item_thumbnail(dirname($file_img2), basename($file_img2));
    }
    $it_img2 = it_img_upload($_FILES['it_img2']['tmp_name'], $_FILES['it_img2']['name'], $it_img_dir.'/'.$it_id);
}
if ($_FILES['it_img3']['name']) {
    if($w == 'u' && $it_img3) {
        $file_img3 = $it_img_dir.'/'.clean_relative_paths($it_img3);
        @unlink($file_img3);
        delete_item_thumbnail(dirname($file_img3), basename($file_img3));
    }
    $it_img3 = it_img_upload($_FILES['it_img3']['tmp_name'], $_FILES['it_img3']['name'], $it_img_dir.'/'.$it_id);
}
if ($_FILES['it_img4']['name']) {
    if($w == 'u' && $it_img4) {
        $file_img4 = $it_img_dir.'/'.clean_relative_paths($it_img4);
        @unlink($file_img4);
        delete_item_thumbnail(dirname($file_img4), basename($file_img4));
    }
    $it_img4 = it_img_upload($_FILES['it_img4']['tmp_name'], $_FILES['it_img4']['name'], $it_img_dir.'/'.$it_id);
}
if ($_FILES['it_img5']['name']) {
    if($w == 'u' && $it_img5) {
        $file_img5 = $it_img_dir.'/'.clean_relative_paths($it_img5);
        @unlink($file_img5);
        delete_item_thumbnail(dirname($file_img5), basename($file_img5));
    }
    $it_img5 = it_img_upload($_FILES['it_img5']['tmp_name'], $_FILES['it_img5']['name'], $it_img_dir.'/'.$it_id);
}
if ($_FILES['it_img6']['name']) {
    if($w == 'u' && $it_img6) {
        $file_img6 = $it_img_dir.'/'.clean_relative_paths($it_img6);
        @unlink($file_img6);
        delete_item_thumbnail(dirname($file_img6), basename($file_img6));
    }
    $it_img6 = it_img_upload($_FILES['it_img6']['tmp_name'], $_FILES['it_img6']['name'], $it_img_dir.'/'.$it_id);
}
if ($_FILES['it_img7']['name']) {
    if($w == 'u' && $it_img7) {
        $file_img7 = $it_img_dir.'/'.clean_relative_paths($it_img7);
        @unlink($file_img7);
        delete_item_thumbnail(dirname($file_img7), basename($file_img7));
    }
    $it_img7 = it_img_upload($_FILES['it_img7']['tmp_name'], $_FILES['it_img7']['name'], $it_img_dir.'/'.$it_id);
}
if ($_FILES['it_img8']['name']) {
    if($w == 'u' && $it_img8) {
        $file_img8 = $it_img_dir.'/'.clean_relative_paths($it_img8);
        @unlink($file_img8);
        delete_item_thumbnail(dirname($file_img8), basename($file_img8));
    }
    $it_img8 = it_img_upload($_FILES['it_img8']['tmp_name'], $_FILES['it_img8']['name'], $it_img_dir.'/'.$it_id);
}
if ($_FILES['it_img9']['name']) {
    if($w == 'u' && $it_img9) {
        $file_img9 = $it_img_dir.'/'.clean_relative_paths($it_img9);
        @unlink($file_img9);
        delete_item_thumbnail(dirname($file_img9), basename($file_img9));
    }
    $it_img9 = it_img_upload($_FILES['it_img9']['tmp_name'], $_FILES['it_img9']['name'], $it_img_dir.'/'.$it_id);
}
if ($_FILES['it_img10']['name']) {
    if($w == 'u' && $it_img10) {
        $file_img10 = $it_img_dir.'/'.clean_relative_paths($it_img10);
        @unlink($file_img10);
        delete_item_thumbnail(dirname($file_img10), basename($file_img10));
    }
    $it_img10 = it_img_upload($_FILES['it_img10']['tmp_name'], $_FILES['it_img10']['name'], $it_img_dir.'/'.$it_id);
}

if ($w == "" || $w == "u")
{
    // 다음 입력을 위해서 옵션값을 쿠키로 한달동안 저장함
    //@setcookie("ck_ca_id",  $ca_id,  time() + 86400*31, $default[de_cookie_dir], $default[de_cookie_domain]);
    //@setcookie("ck_maker",  stripslashes($it_maker),  time() + 86400*31, $default[de_cookie_dir], $default[de_cookie_domain]);
    //@setcookie("ck_origin", stripslashes($it_origin), time() + 86400*31, $default[de_cookie_dir], $default[de_cookie_domain]);
    @set_cookie("ck_ca_id", $ca_id, time() + 86400*31);
    @set_cookie("ck_ca_id2", $ca_id2, time() + 86400*31);
    @set_cookie("ck_ca_id3", $ca_id3, time() + 86400*31);
    @set_cookie("ck_maker", stripslashes($it_maker), time() + 86400*31);
    @set_cookie("ck_origin", stripslashes($it_origin), time() + 86400*31);
}


// 관련상품을 우선 삭제함
sql_query(" delete from {$g5['g5_shop_item_relation_table']} where it_id = '$it_id' ");

// 관련상품의 반대도 삭제
sql_query(" delete from {$g5['g5_shop_item_relation_table']} where it_id2 = '$it_id' ");

if($is_auth) {
	// 이벤트상품을 우선 삭제함
	sql_query(" delete from {$g5['g5_shop_event_item_table']} where it_id = '$it_id' ");
}

// 선택옵션
sql_query(" delete from {$g5['g5_shop_item_option_table']} where io_type = '0' and it_id = '$it_id' "); // 기존선택옵션삭제

$option_count = (isset($_POST['opt_id']) && is_array($_POST['opt_id'])) ? count($_POST['opt_id']) : array();
if($option_count) {
    // 옵션명
    $opt1_cnt = $opt2_cnt = $opt3_cnt = 0;
    for($i=0; $i<$option_count; $i++) {
        $_POST['opt_id'][$i] = preg_replace(G5_OPTION_ID_FILTER, '', strip_tags($_POST['opt_id'][$i]));

		$opt_val = explode(chr(30), $_POST['opt_id'][$i]);
        if($opt_val[0])
            $opt1_cnt++;
        if($opt_val[1])
            $opt2_cnt++;
        if($opt_val[2])
            $opt3_cnt++;
    }

    if($opt1_subject && $opt1_cnt) {
        $it_option_subject = $opt1_subject;
        if($opt2_subject && $opt2_cnt)
            $it_option_subject .= ','.$opt2_subject;
        if($opt3_subject && $opt3_cnt)
            $it_option_subject .= ','.$opt3_subject;
    }
}

// 추가옵션
sql_query(" delete from {$g5['g5_shop_item_option_table']} where io_type = '1' and it_id = '$it_id' "); // 기존추가옵션삭제

$supply_count = (isset($_POST['spl_id']) && is_array($_POST['spl_id'])) ? count($_POST['spl_id']) : array();
if($supply_count) {
    // 추가옵션명
    $arr_spl = array();
    for($i=0; $i<$supply_count; $i++) {
        $_POST['spl_id'][$i] = preg_replace(G5_OPTION_ID_FILTER, '', strip_tags($_POST['spl_id'][$i]));

		$spl_val = explode(chr(30), $_POST['spl_id'][$i]);
        if(!in_array($spl_val[0], $arr_spl))
            $arr_spl[] = $spl_val[0];
    }

    $it_supply_subject = implode(',', $arr_spl);
}

// 상품요약정보
$value_array = array();
for($i=0; $i<count($_POST['ii_article']); $i++) {
    $key = $_POST['ii_article'][$i];
    $val = $_POST['ii_value'][$i];
    $value_array[$key] = $val;
}
$it_info_value = addslashes(serialize($value_array));

// 포인트 비율 값 체크
if(($it_point_type == 1 || $it_point_type == 2) && $it_point > 99)
    alert("포인트 비율을 0과 99 사이의 값으로 입력해 주십시오.");

$it_name = strip_tags(clean_xss_attributes(trim($_POST['it_name'])));

// KVE-2019-0708
$check_sanitize_keys = array(
'it_order',             // 출력순서
'it_maker',             // 제조사
'it_origin',            // 원산지
'it_brand',             // 브랜드
'it_model',             // 모델
'it_tel_inq',           // 전화문의
'it_use',               // 판매가능
'it_nocoupon',          // 쿠폰적용안함
'ec_mall_pid',          // 네이버쇼핑 상품ID
'it_sell_email',        // 판매자 e-mail
'it_price',             // 판매가격
'it_cust_price',        // 시중가격
'it_point_type',        // 포인트 유형
'it_point',             // 포인트
'it_supply_point',      // 추가옵션상품 포인트
'it_soldout',           // 상품품절
'it_stock_sms',         // 재입고SMS 알림
'it_stock_qty',         // 재고수량
'it_noti_qty',          // 재고 통보수량
'it_buy_min_qty',       // 최소계약일수
'it_buy_max_qty',       // 최대계약시간
'it_notax',             // 상품과세 유형
'it_sc_type',           // 배송비 유형
'it_sc_method',         // 배송비 결제
'it_sc_price',          // 기본배송비
'it_sc_minimum',        // 배송비 상세조건
);

foreach( $check_sanitize_keys as $key ){
    $$key = isset($_POST[$key]) ? strip_tags(clean_xss_attributes($_POST[$key])) : '';
}

$it_basic = preg_replace('#<script(.*?)>(.*?)<\/script>#is', '', $it_basic);

if ($it_name == "")
    alert("제목 또는 상품명을 입력해 주십시오.");

// 추가값
$is_reserve = ($default['pt_reserve_end'] > 0 && $default['pt_reserve_day'] > 0 && $default['pt_reserve_cache'] > 0) ? true : false;
$is_reserve = ($is_reserve && ($is_admin == 'super' || $default['pt_reserve_use'] == "1")) ? true : false;

if($pt_reserve_use && $is_reserve) {
	if(!$pt_reserve) {
		$pt_reserve_time = "{$pt_reserve_date} {$pt_reserve_hour}:{$pt_reserve_minute}:00";
		$pt_reserve = strtotime($pt_reserve_time);
		$it_use = 0;
	}
} else {
	$pt_reserve_use = 0;
	$pt_reserve = 0;
}

if($pt_end_date && $default['pt_reserve_cache'] > 0) {
	$pt_end_time = "{$pt_end_date} {$pt_end_hour}:{$pt_end_minute}:00";
	$pt_end = strtotime($pt_end_time);
} else {
	$pt_end = 0;
}

$pt_review_sql = ($is_auth || $default['pt_review_use']) ? " pt_review_use = '$pt_review_use', " : "";
$pt_comment_sql = ($is_auth || $default['pt_comment_use']) ? " pt_comment_use = '$pt_comment_use', " : "";
$pt_syndi_sql = ($is_admin == 'super') ? " pt_syndi = '$pt_syndi', pt_commission = '$pt_commission', pt_incentive = '$pt_incentive', " : "";

// 소유자 정규화: pt_id와 it_spec_partner_id는 항상 동일 값으로 저장
$pt_id_posted = isset($_POST['pt_id']) ? trim(strip_tags(clean_xss_attributes($_POST['pt_id']))) : '';
$it_spec_partner_id_posted = isset($_POST['it_spec_partner_id']) ? trim(strip_tags(clean_xss_attributes($_POST['it_spec_partner_id']))) : '';
$session_mb_id = '';
if(function_exists('get_session')) {
    $session_mb_id = trim((string)get_session('ss_mb_id'));
}
if($session_mb_id === '' && isset($_SESSION['ss_mb_id'])) {
    $session_mb_id = trim((string)$_SESSION['ss_mb_id']);
}

$login_mb_id = isset($member['mb_id']) ? trim((string)$member['mb_id']) : '';
if($login_mb_id === '') {
    $login_mb_id = $session_mb_id;
}

$owner_id_final = $it_spec_partner_id_posted;
if($owner_id_final === '') {
    $owner_id_final = $pt_id_posted;
}
if($owner_id_final === '') {
    $owner_id_final = $login_mb_id;
}

// 셀러 등록/수정은 반드시 로그인한 본인 ID로 고정
if(!$is_auth && $login_mb_id !== '') {
    $owner_id_final = $login_mb_id;
}

if($owner_id_final === '') {
    alert('소유자ID를 확인할 수 없어 저장할 수 없습니다. 다시 로그인 후 시도해 주세요.');
}

$pt_id = $owner_id_final;
$it_spec_partner_id = $owner_id_final;

$admin_sql = '';
if($is_auth) {
	$admin_sql =  " it_type1			= '$it_type1',
					it_type2			= '$it_type2',
					it_type3			= '$it_type3',
					it_type4			= '$it_type4',
					it_type5			= '$it_type5',
					it_sell_email		= '$it_sell_email',
		            it_head_html        = '$it_head_html',
		            it_tail_html        = '$it_tail_html',
		            it_mobile_head_html = '$it_mobile_head_html',
		            it_mobile_tail_html = '$it_mobile_tail_html',
		            it_order            = '$it_order',
		            it_tel_inq          = '$it_tel_inq',
		            it_nocoupon         = '$it_nocoupon',
		            it_cust_price       = '$it_cust_price',
                    it_stock_sms		= '$it_stock_sms',
					";
}

// 원격접속정보를 JSON 포맷으로 변환 시킴 JSLEE {
// $remotePrograms = strip_tags(clean_xss_attributes($_POST['remoteProgram']));
// $remoteIps = strip_tags(clean_xss_attributes($_POST['remoteIp']));
// $remoteIds = strip_tags(clean_xss_attributes($_POST['remoteId']));
// $remotePasswords = strip_tags(clean_xss_attributes($_POST['remotePassword']));
// $remoteData = array();
// for ($i = 0; $i < count($remotePrograms); $i++) {
//     if ($i == 0) {
//         $remoteData[] = array(
//             'RemoteIP' => $remoteIps[$i],
//             'RemoteIP_Country' => '-',
//             'Program_'.$i => $remotePrograms[$i],
//             $remotePrograms[$i].'_ID' => $remoteIds[$i],
//             $remotePrograms[$i].'_PWD' => $remotePasswords[$i]
//         );
//     } else {
//         $remoteData[] = array(
//             'Program_'.$i => $remotePrograms[$i],
//             $remotePrograms[$i].'_ID' => $remoteIds[$i],
//             $remotePrograms[$i].'_PWD' => $remotePasswords[$i]
//         );
//     }
// }
// $jsonData_for_it_spec_remote_sw = json_encode($remoteData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);

function clean_input($data) {
    return strip_tags(clean_xss_attributes($data));
}

if(!function_exists('clean_input_recursive_vpn')) {
    function clean_input_recursive_vpn($value) {
        if (is_array($value)) {
            $cleaned = array();
            foreach ($value as $k => $v) {
                $cleaned[$k] = clean_input_recursive_vpn($v);
            }
            return $cleaned;
        }
        return clean_input($value);
    }
}

if(!function_exists('snapshot_preserve_value_vpn')) {
    function snapshot_preserve_value_vpn($value) {
        if (is_array($value)) {
            $copied = array();
            foreach ($value as $k => $v) {
                $copied[$k] = snapshot_preserve_value_vpn($v);
            }
            return $copied;
        }

        if (is_null($value)) {
            return '';
        }

        return (string)$value;
    }
}

if(!function_exists('vpnlink_merge_hour_split_post_fields_vpn')) {
    function vpnlink_merge_hour_split_post_fields_vpn($postData) {
        if (!is_array($postData)) {
            return $postData;
        }

        $fieldMap = array(
            array('hidden' => 'it_10', 'day' => 'it_10_day', 'hour' => 'it_10_hour', 'max_hours' => 3650 * 24),
            array('hidden' => 'it_buy_min_qty', 'day' => 'it_buy_min_qty_day', 'hour' => 'it_buy_min_qty_hour', 'max_hours' => 365 * 24),
            array('hidden' => 'it_buy_max_qty', 'day' => 'it_buy_max_qty_day', 'hour' => 'it_buy_max_qty_hour', 'max_hours' => 365 * 24)
        );

        foreach ($fieldMap as $map) {
            $hasDay = isset($postData[$map['day']]);
            $hasHour = isset($postData[$map['hour']]);
            if (!$hasDay && !$hasHour) {
                continue;
            }

            $day = $hasDay ? (int)$postData[$map['day']] : 0;
            $hour = $hasHour ? (int)$postData[$map['hour']] : 0;

            if ($day < 0) {
                $day = 0;
            }
            if ($hour < 0) {
                $hour = 0;
            }
            if ($hour > 23) {
                $hour = 23;
            }

            $hours = ($day * 24) + $hour;
            if (isset($map['max_hours']) && (int)$map['max_hours'] > 0 && $hours > (int)$map['max_hours']) {
                $hours = (int)$map['max_hours'];
            }

            $postData[$map['hidden']] = (string)$hours;
        }

        return $postData;
    }
}

if(!function_exists('vpnlink_normalize_checkbox_post_fields_vpn')) {
    function vpnlink_normalize_checkbox_post_fields_vpn($postData) {
        if (!is_array($postData)) {
            return $postData;
        }

        $checkboxDefaults = array(
            'it_is_hour_sale' => '0',
            'it_1' => '0',
            'it_2' => '0',
            'it_3' => '0',
            'it_7' => '0',
            'it_use' => '0',
            'it_soldout' => '0'
        );

        foreach ($checkboxDefaults as $fieldName => $defaultValue) {
            if (!array_key_exists($fieldName, $postData)) {
                $postData[$fieldName] = $defaultValue;
            }
        }

        return $postData;
    }
}

if(!function_exists('build_recent_itemform_summary_vpn')) {
    function build_recent_itemform_summary_vpn($values, $item_name = '') {
        $parts = array();

        $item_name_text = trim((string)$item_name);
        if ($item_name_text === '' && isset($values['__recent_item_name'])) {
            $item_name_text = trim((string)$values['__recent_item_name']);
        }

        if ($item_name_text !== '') {
            $parts[] = $item_name_text;
        } else if (isset($values['ca_id']) && $values['ca_id'] !== '') {
            $parts[] = 'VPN분류:' . $values['ca_id'];
        }
        if (isset($values['remoteProgram']) && is_array($values['remoteProgram']) && count($values['remoteProgram']) > 0) {
            $parts[] = '프로토콜:' . trim((string)$values['remoteProgram'][0]);
        }
        if (isset($values['remoteIp']) && is_array($values['remoteIp']) && count($values['remoteIp']) > 0) {
            $parts[] = '서버:' . trim((string)$values['remoteIp'][0]);
        }
        if (isset($values['it_price']) && $values['it_price'] !== '') {
            $parts[] = '시간요금:' . $values['it_price'];
        }
        if (!count($parts)) {
            return 'VPN 최근 입력 설정';
        }
        return implode(' | ', $parts);
    }
}

// POST 데이터 수집 및 정리
$remotePrograms = array_map('clean_input', $_POST['remoteProgram']);
$remoteIps = array_map('clean_input', $_POST['remoteIp']);
$remoteIpCountries = array_map('clean_input', '');
$remoteIpCities = array_map('clean_input', '');
$remoteIpLatitudes = array_map('clean_input', '');
$remoteIplongitudes = array_map('clean_input', '');
$remoteIds = array_map('clean_input', $_POST['remoteId']);
$remotePasswords = array_map('clean_input', $_POST['remotePassword']);
$remoteIpCountryCodes = array();

// JSON 데이터 준비
$remoteData = array();
for ($i = 0; $i < count($remotePrograms); $i++) {

    // 1. IP/도메인 추출 및 검증
    $currentInputIp = $remoteIps[$i];
    $resolvedIp = gethostbyname($currentInputIp);

    // IP 형식 검증
    if (!filter_var($resolvedIp, FILTER_VALIDATE_IP)) {
        alert("입력하신 서버주소([{$currentInputIp}])가 올바르지 않거나 도메인을 IP로 변환할 수 없습니다.");
    }

    // 사설 IP(Private IP) 및 예약된 IP(Reserved IP) 검증 - 공인 IP만 허용
    if (!filter_var($resolvedIp, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
        alert("입력하신 서버주소([{$currentInputIp}] -> {$resolvedIp})는 사설 IP(Local IP) 또는 예약된 IP 대역입니다.\\nVPN 서비스에는 외부에서 접속 가능한 공인 IP(Public IP)만 사용할 수 있습니다.");
    }

    // db에서 국가정보 , 시티정보, 지도좌표 가져오기 { JSLEE
    $result_geoip = sql_query("
        SELECT
            blocks.latitude,
            blocks.longitude,
            locations.city_name,
            locations.country_name,
            locations.country_iso_code
        FROM
            geoip_city_blocks_ipv4 AS blocks
        JOIN
            geoip_city_locations AS locations
        ON
            blocks.geoname_id = locations.geoname_id
        WHERE
            INET6_ATON('{$resolvedIp}') BETWEEN blocks.start_ip AND blocks.end_ip;
    ");

    if ($result_geoip->num_rows > 0) {
        $row_geoip = $result_geoip->fetch_assoc();
        $remoteIpCountries[$i] = $row_geoip['country_name'];
        $remoteIpCountryCodes[$i] = $row_geoip['country_iso_code'];
        $remoteIpCities[$i] = $row_geoip['city_name'];
        $remoteIpLatitudes[$i] = $row_geoip['latitude'];
        $remoteIplongitudes[$i] = $row_geoip['longitude'];
    } else {
        // 국가 정보를 찾을 수 없는 경우 (유효하지 않은 IP로 간주하여 차단)
        alert("입력하신 서버주소([{$currentInputIp}] -> {$resolvedIp})의 국가 정보를 식별할 수 없습니다.\\n유효한 VPN 서버 IP인지 확인해 주십시오.");
    }

    $remoteData[] = array(
        'RemoteIP__'.$i => $remoteIps[$i],
        'RemoteIP_CountryName__'.$i => $remoteIpCountries[$i],  // IP 국가명
        'RemoteIP_CountryCode__'.$i => $remoteIpCountryCodes[$i],  // IP 국가명
        'RemoteIP_City__'.$i => $remoteIpCities[$i],  // IP city 명
        'RemoteIP_Latitude__'.$i => $remoteIpLatitudes[$i],  // IP 지도상 위도
        'RemoteIP_Longitude__'.$i => $remoteIplongitudes[$i],  // IP 지도상 경도
        'Program__'.$i => $remotePrograms[$i],
        $remotePrograms[$i].'_ID__'.$i => $remoteIds[$i],
        $remotePrograms[$i].'_PWD__'.$i => $remotePasswords[$i]
    );

    // db에서 국가정보 , 시티정보, 지도좌표 가져오기 } JSLEE
}

// JSON 데이터 변환
$jsonData_for_it_spec_remote_sw = json_encode($remoteData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);

// 원격접속정보를 JSON 포맷으로 변환 시킴 JSLEE }

// VPN 상품 자동 설정값 (RPC와 포맷 통일) - 이미지 및 스펙 정보 { JSLEE
$it_spec_os = isset($remotePrograms[0]) ? $remotePrograms[0] : '';
$it_spec_app_ver = 'v0.0.0';
$it_1 = isset($_POST['it_1']) ? strip_tags(clean_xss_attributes($_POST['it_1'])) : '1';
$it_2 = isset($_POST['it_2']) ? strip_tags(clean_xss_attributes($_POST['it_2'])) : '1';
$it_3 = isset($_POST['it_3']) ? strip_tags(clean_xss_attributes($_POST['it_3'])) : '0';
// }

// VPN 요금은 내부 저장/계산 모두 1시간 기준으로 통일
$it_price = (int)$it_price;
if ($it_price < 0) {
    $it_price = 0;
}
$it_is_hour_sale_price = $it_price;

// 개통비/설치비 및 면제 기준시간 정규화
$it_install_price = isset($_POST['it_install_price']) ? (int)$_POST['it_install_price'] : (int)$it_install_price;
if ($it_install_price < 0) {
    $it_install_price = 0;
}

$it_8 = isset($_POST['it_8']) ? (int)$_POST['it_8'] : 0; // 할인 적용 시작시간(미사용 시 0)
$it_9 = isset($_POST['it_9']) ? (int)$_POST['it_9'] : 0; // 할인시 개통비(미사용 시 0)

if (isset($_POST['it_10_day']) || isset($_POST['it_10_hour'])) {
    $it_10_day = isset($_POST['it_10_day']) ? (int)$_POST['it_10_day'] : 0;
    $it_10_hour = isset($_POST['it_10_hour']) ? (int)$_POST['it_10_hour'] : 0;

    if ($it_10_day < 0) {
        $it_10_day = 0;
    }
    if ($it_10_hour < 0) {
        $it_10_hour = 0;
    }
    if ($it_10_hour > 23) {
        $it_10_hour = 23;
    }

    $it_10 = ($it_10_day * 24) + $it_10_hour;
} else {
    $it_10 = isset($_POST['it_10']) ? (int)$_POST['it_10'] : 0;
}

if ($it_8 < 0) {
    $it_8 = 0;
}
if ($it_9 < 0) {
    $it_9 = 0;
}
if ($it_10 < 0) {
    $it_10 = 0;
}
if ($it_10 > (3650 * 24)) {
    $it_10 = 3650 * 24;
}

// Added by AI: Manual extraction for Billing Plan
$it_billing_plan = isset($_POST['it_billing_plan']) ? strip_tags(clean_xss_attributes($_POST['it_billing_plan'])) : '';

$_vpn_grade_allowed = array('BASIC', 'PLUS', 'PRO', 'ULTRA', 'MAX');
$it_spec_grade = isset($_POST['it_spec_grade']) ? strtoupper(trim(strip_tags($_POST['it_spec_grade']))) : '';
if(!in_array($it_spec_grade, $_vpn_grade_allowed, true)) $it_spec_grade = '';
$it_7_post = isset($_POST['it_7']) ? trim((string)$_POST['it_7']) : '';
$it_7 = ($it_7_post === '1' || strtolower($it_7_post) === 'true' || strtolower($it_7_post) === 'yes' || strtolower($it_7_post) === 'on') ? '1' : '0';
$legacy_plan_key = strtolower(trim((string)$it_billing_plan));
if ($it_7 !== '1' && $legacy_plan_key === 'usage') {
    $it_7 = '1';
}
$it_billing_traffic_cost = isset($_POST['it_billing_traffic_cost']) ? strip_tags(clean_xss_attributes($_POST['it_billing_traffic_cost'])) : 0;
$it_billing_time_cost = isset($_POST['it_billing_time_cost']) ? strip_tags(clean_xss_attributes($_POST['it_billing_time_cost'])) : 0;
$billing_day_hours = isset($_POST['billing_day_hours']) ? (float)$_POST['billing_day_hours'] : 6.0;
$billing_month_hours = isset($_POST['billing_month_hours']) ? (float)$_POST['billing_month_hours'] : 20.0;
$billing_year_hours = isset($_POST['billing_year_hours']) ? (float)$_POST['billing_year_hours'] : 200.0;

if ($billing_day_hours <= 0) {
    $billing_day_hours = 6.0;
}
if ($billing_month_hours <= 0) {
    $billing_month_hours = 20.0;
}
if ($billing_year_hours <= 0) {
    $billing_year_hours = 200.0;
}

$it_4 = $billing_day_hours;
$it_5 = $billing_month_hours;
$it_6 = $billing_year_hours;

if ($it_7 === '1' && $it_is_hour_sale != "1" && $it_1 != '1' && $it_2 != '1' && $it_3 != '1') {
    $it_billing_plan = 'usage';
} else if ($it_is_hour_sale == "1") {
    $it_billing_plan = 'hourly';
} else if ($it_3 == '1' && $it_1 != '1' && $it_2 != '1') {
    $it_billing_plan = 'yearly';
} else if ($it_2 == '1' && $it_1 != '1') {
    $it_billing_plan = 'monthly';
} else {
    $it_billing_plan = 'monthly';
}

$it_billing_plan = apms_billing_plan_normalize($it_billing_plan);

if ($it_is_hour_sale == "1") { // 1시간 단위판매 허용 체크된 경우 (기본단위: 시간)
    $it_buy_min_qty = 1;
}

$it_buy_min_qty = (int)$it_buy_min_qty;
$it_buy_max_qty = (int)$it_buy_max_qty;

if ($it_buy_min_qty < 1) {
    $it_buy_min_qty = 1;
}

if ($it_buy_max_qty > 0 && $it_buy_max_qty <= 365) {
    // 과거 VPN 폼에서 일 단위(최대 365)로 넘어오던 값을 시간 단위로 보정
    $it_buy_max_qty *= 24;
}

if ($it_buy_max_qty <= 0) {
    $it_buy_max_qty = 8760;
}

if ($it_buy_max_qty > 8760) {
    $it_buy_max_qty = 8760;
}

if ($it_buy_min_qty > $it_buy_max_qty) {
    $it_buy_min_qty = $it_buy_max_qty;
}


$spec_sql =  "  it_spec_sales_type		= '$it_spec_sales_type',
                it_spec_partner_id		= '$it_spec_partner_id',
                it_spec_app_ver			= '$it_spec_app_ver',
                it_spec_mgr_nickname	= '$it_spec_mgr_nickname',
                it_spec_os			    = '$it_spec_os',
                it_spec_os_disp_lang	= '$it_spec_os_disp_lang',
                it_spec_cpu			    = '$it_spec_cpu',
                it_spec_ram			    = '$it_spec_ram',
                it_spec_ram_type		= '$it_spec_ram_type',
                it_spec_gpu			    = '$it_spec_gpu',
                it_spec_ssd			    = '$it_spec_ssd',
                it_spec_ssd_type		= '$it_spec_ssd_type',
                it_spec_hdd			    = '$it_spec_hdd',
                it_spec_hdd_type		= '$it_spec_hdd_type',
                it_spec_remote_sw		= '$jsonData_for_it_spec_remote_sw',
                it_spec_remote_ip_country_code = '$remoteIpCountryCodes[0]',
                it_install_price		= '$it_install_price',
                it_is_hour_sale		    = '$it_is_hour_sale',
                it_is_hour_sale_price   = '$it_is_hour_sale_price',
                it_billing_plan         = '$it_billing_plan',
                it_billing_traffic_cost = '$it_billing_traffic_cost',
                it_billing_time_cost    = '$it_billing_time_cost',
                it_is_vm                = '$it_is_vm',
                it_shop_memo			= '$it_shop_memo',
                it_spec_keyboard	    = '$it_spec_keyboard',
                it_spec_mouse			= '$it_spec_mouse',
                it_spec_grade			= '$it_spec_grade',
";

$sql_common = " ca_id               = '$ca_id',
                ca_id2              = '$ca_id2',
                ca_id3              = '$ca_id3',
                it_name             = '$it_name',
                it_maker            = '$it_maker',
                it_origin           = '$it_origin',
                it_brand            = '$it_brand',
                it_model            = '$it_model',
                it_option_subject   = '$it_option_subject',
                it_supply_subject   = '$it_supply_subject',
				it_basic            = '$it_basic',
                it_explan           = '$it_explan',
                it_explan2          = '".strip_tags(clean_xss_attributes(trim($_POST['it_explan'])))."',
                it_mobile_explan    = '$it_mobile_explan',
                it_price            = '$it_price',
                it_point            = '$it_point',
                it_point_type       = '$it_point_type',
                it_supply_point     = '$it_supply_point',
                it_notax            = '$it_notax',
                it_use              = '$it_use',
                it_soldout          = '$it_soldout',
                it_stock_qty        = '$it_stock_qty',
                it_noti_qty         = '$it_noti_qty',
                it_sc_type          = '$it_sc_type',
                it_sc_method        = '$it_sc_method',
                it_sc_price         = '$it_sc_price',
                it_sc_minimum       = '$it_sc_minimum',
                it_sc_qty           = '$it_sc_qty',
                it_buy_min_qty      = '$it_buy_min_qty',
                it_buy_max_qty      = '$it_buy_max_qty',
                it_ip               = '{$_SERVER['REMOTE_ADDR']}',
                it_info_gubun       = '$it_info_gubun',
                it_info_value       = '$it_info_value',
                it_img1             = '$it_img1',
                it_img2             = '$it_img2',
                it_img3             = '$it_img3',
                it_img4             = '$it_img4',
                it_img5             = '$it_img5',
                it_img6             = '$it_img6',
                it_img7             = '$it_img7',
                it_img8             = '$it_img8',
                it_img9             = '$it_img9',
                it_img10            = '$it_img10',
                it_1_subj           = '$it_1_subj',
                it_2_subj           = '$it_2_subj',
                it_3_subj           = '$it_3_subj',
                it_4_subj           = '$it_4_subj',
                it_5_subj           = '$it_5_subj',
                it_6_subj           = '$it_6_subj',
                it_7_subj           = '$it_7_subj',
                it_8_subj           = '$it_8_subj',
                it_9_subj           = '$it_9_subj',
                it_10_subj          = '$it_10_subj',
                it_1                = '$it_1',
                it_2                = '$it_2',
                it_3                = '$it_3',
                it_4                = '$it_4',
                it_5                = '$it_5',
                it_6                = '$it_6',
                it_7                = '$it_7',
                it_8                = '$it_8',
                it_9                = '$it_9',
                it_10               = '$it_10',
				$admin_sql
                $spec_sql
				pt_it				= '$pt_it',
                pt_id				= '$pt_id',
                pt_img				= '$pt_img',
                pt_ccl				= '$pt_ccl',
				pt_order			= '$pt_order',
				pt_show				= '$pt_show',
				pt_tag				= '$pt_tag',
                pt_link1			= '$pt_link1',
                pt_link2			= '$pt_link2',
				$pt_review_sql
				$pt_comment_sql
				pt_day				= '$pt_day',
				pt_end				= '$pt_end',
				pt_reserve			= '$pt_reserve',
				pt_reserve_use		= '$pt_reserve_use',
				$pt_syndi_sql
				pt_explan	        = '$pt_explan',
                pt_mobile_explan    = '$pt_mobile_explan',
				pt_msg1			    = '$pt_msg1',
                pt_msg2			    = '$pt_msg2',
                pt_msg3			    = '$pt_msg3'
				";

if ($w == "")
{
    $it_id = $_POST['it_id'];

    if (!trim($it_id)) {
        alert('코드가 없으므로 추가하실 수 없습니다.');
    }

    $t_it_id = preg_replace("/[A-Za-z0-9\-_]/", "", $it_id);
    if($t_it_id)
        alert('코드는 영문자, 숫자, -, _ 만 사용할 수 있습니다.');

	$pt_num = time();
    $sql_common .= " , it_time = '".G5_TIME_YMDHIS."' ";
    $sql_common .= " , it_update_time = '".G5_TIME_YMDHIS."' ";
    $sql = " insert {$g5['g5_shop_item_table']}
                set it_id = '$it_id',
					pt_num = '$pt_num',
					$sql_common	";
    sql_query($sql);





}
else if ($w == "u")
{
    $sql_common .= " , it_update_time = '".G5_TIME_YMDHIS."' ";
    $sql = " update {$g5['g5_shop_item_table']}
                set $sql_common
              where it_id = '$it_id' ";
    sql_query($sql);
}

// 저장 직후 소유자 컬럼 강제 동기화(방어 로직)
if($it_id && $owner_id_final) {
    sql_query(" update {$g5['g5_shop_item_table']} set pt_id = '".sql_real_escape_string($owner_id_final)."', it_spec_partner_id = '".sql_real_escape_string($owner_id_final)."' where it_id = '".sql_real_escape_string($it_id)."' ", false);

    $owner_verify = sql_fetch(" select pt_id, it_spec_partner_id from {$g5['g5_shop_item_table']} where it_id = '".sql_real_escape_string($it_id)."' ");
    // item_update_vpn_debug.txt logging disabled
}



if ($w == "" || $w == "u")
{
    // 관련상품 등록
    $it_id2 = explode(",", $it_list);
    for ($i=0; $i<count($it_id2); $i++)
    {
        if (trim($it_id2[$i]))
        {
            $sql = " insert into {$g5['g5_shop_item_relation_table']}
                        set it_id  = '$it_id',
                            it_id2 = '$it_id2[$i]',
                            ir_no = '$i' ";
            sql_query($sql, false);

            // 관련상품의 반대로도 등록
            $sql = " insert into {$g5['g5_shop_item_relation_table']}
                        set it_id  = '$it_id2[$i]',
                            it_id2 = '$it_id',
                            ir_no = '$i' ";
            sql_query($sql, false);
        }
    }

    // 이벤트상품 등록
	if($is_auth) {
		$ev_id = explode(",", $ev_list);
		for ($i=0; $i<count($ev_id); $i++)
		{
			if (trim($ev_id[$i]))
			{
				$sql = " insert into {$g5['g5_shop_event_item_table']}
							set ev_id = '$ev_id[$i]',
								it_id = '$it_id' ";
				sql_query($sql, false);
			}
		}
	}
}

// 선택옵션등록
if($option_count) {
    $comma = '';
    $sql = " INSERT INTO {$g5['g5_shop_item_option_table']}
                    ( `io_id`, `io_type`, `it_id`, `io_price`, `io_stock_qty`, `io_noti_qty`, `io_use` )
                VALUES ";
    for($i=0; $i<$option_count; $i++) {
        $sql .= $comma . " ( '{$_POST['opt_id'][$i]}', '0', '$it_id', '{$_POST['opt_price'][$i]}', '{$_POST['opt_stock_qty'][$i]}', '{$_POST['opt_noti_qty'][$i]}', '{$_POST['opt_use'][$i]}' )";
        $comma = ' , ';
    }

    sql_query($sql);
}

// 추가옵션등록
if($supply_count) {
    $comma = '';
    $sql = " INSERT INTO {$g5['g5_shop_item_option_table']}
                    ( `io_id`, `io_type`, `it_id`, `io_price`, `io_stock_qty`, `io_noti_qty`, `io_use` )
                VALUES ";
    for($i=0; $i<$supply_count; $i++) {
        $sql .= $comma . " ( '{$_POST['spl_id'][$i]}', '1', '$it_id', '{$_POST['spl_price'][$i]}', '{$_POST['spl_stock_qty'][$i]}', '{$_POST['spl_noti_qty'][$i]}', '{$_POST['spl_use'][$i]}' )";
        $comma = ' , ';
    }

    sql_query($sql);
}

// 태그 및 파일 등록
$file_upload_msg = '';
if ($w == "" || $w == "u") {
	//태그등록
	$it_time = G5_TIME_YMDHIS;
	if($w == "u") {
		$row = sql_fetch("select it_time from {$g5['g5_shop_item_table']} where it_id = '{$it_id}' ");
		$it_time = $row['it_time'];
	}

	apms_add_tag($it_id, $pt_tag, $it_time);

	//파일등록
	$file_upload_msg = apms_upload_file('item', $it_id);

	// 네이버 신디
	if ($is_admin == 'super' && $it_use && $pt_syndi) {
		apms_naver_syndi_ping($it_id);
	}
}

// 등록비 기존 삭제
if($is_regit = "2") {
	if(!delete_point($member['mb_id'], '@regit', $member['mb_id'], $it_id)) {
		insert_point($member['mb_id'], $old_upoint * (-1), "{$it_id} 등록 취소");
	}
}

// 등록비 신규 등록
if($is_regit) {
	insert_point($member['mb_id'], $new_upoint, "{$it_id} 등록", "@regit", $member['mb_id'], $it_id);
}

// 썸네일 업데이트
$it = apms_it($it_id);
$it['chk_img'] = true;
$it_thumb = apms_it_thumbnail($it, 0, 0, false, true);
$it_thumb = ($it_thumb) ? $it_thumb : 1;
sql_query(" update {$g5['g5_shop_item_table']} set pt_thumb = '".addslashes($it_thumb)."' where it_id = '{$it_id}' ", false);

// 신규등록 화면에서 재사용할 최근 설정 100세트 저장 (VPN 스코프 전용)
$recent_preset_exclude_vpn = array(
    'it_id',
    'it_name',
    'w',
    'token',
    'codedup',
    'x',
    'y',
    'qstr',
    'fn',
    'sca',
    'sst',
    'sod',
    'sfl',
    'stx',
    'page'
);

$recent_preset_values_vpn = array();
$recent_preset_html_keys_vpn = array(
    'it_explan',
    'it_mobile_explan',
    'pt_explan',
    'pt_mobile_explan',
    'it_head_html',
    'it_tail_html',
    'it_mobile_head_html',
    'it_mobile_tail_html'
);
if (isset($_POST['__recent_form_state']) && is_string($_POST['__recent_form_state']) && $_POST['__recent_form_state'] !== '') {
    $recent_state_decoded = json_decode($_POST['__recent_form_state'], true);
    if (is_array($recent_state_decoded)) {
        foreach ($recent_state_decoded as $key => $value) {
            if (in_array($key, $recent_preset_exclude_vpn, true)) {
                continue;
            }
            if ($key === '__recent_form_state') {
                continue;
            }

            if (in_array($key, $recent_preset_html_keys_vpn, true)) {
                if (is_array($value)) {
                    $recent_preset_values_vpn[$key] = snapshot_preserve_value_vpn($value);
                } else {
                    $recent_preset_values_vpn[$key] = (string)$value;
                }
                continue;
            }

            $recent_preset_values_vpn[$key] = snapshot_preserve_value_vpn($value);
        }
    }
}

foreach ($_POST as $key => $value) {
    if (in_array($key, $recent_preset_exclude_vpn, true)) {
        continue;
    }
    if ($key === '__recent_form_state') {
        continue;
    }

    if (in_array($key, $recent_preset_html_keys_vpn, true)) {
        if (is_array($value)) {
            $recent_preset_values_vpn[$key] = snapshot_preserve_value_vpn($value);
        } else {
            $recent_preset_values_vpn[$key] = (string)$value;
        }
        continue;
    }

    $recent_preset_values_vpn[$key] = snapshot_preserve_value_vpn($value);
}

$recent_preset_values_vpn = vpnlink_normalize_checkbox_post_fields_vpn($recent_preset_values_vpn);
$recent_preset_values_vpn = vpnlink_merge_hour_split_post_fields_vpn($recent_preset_values_vpn);

if (!isset($recent_preset_values_vpn['it_spec_sales_type']) || trim((string)$recent_preset_values_vpn['it_spec_sales_type']) === '') {
    $recent_preset_values_vpn['it_spec_sales_type'] = 'vpn-mall';
}

if (!isset($recent_preset_values_vpn['__recent_item_name']) || trim((string)$recent_preset_values_vpn['__recent_item_name']) === '') {
    $recent_preset_values_vpn['__recent_item_name'] = trim((string)$it_name);
}

$recent_preset_entry_vpn = array(
    'saved_at' => G5_TIME_YMDHIS,
    'saved_ts' => time(),
    'preset_scope' => 'vpn-mall',
    'summary'  => build_recent_itemform_summary_vpn($recent_preset_values_vpn, $it_name),
    'values'   => $recent_preset_values_vpn
);

$recent_preset_file_vpn = G5_DATA_PATH . '/item/recent_itemform_configs_vpn_' . $member['mb_id'] . '.json';
$recent_preset_list_vpn = array();
if (is_file($recent_preset_file_vpn)) {
    $recent_raw_vpn = @file_get_contents($recent_preset_file_vpn);
    $recent_decoded_vpn = json_decode($recent_raw_vpn, true);
    if (is_array($recent_decoded_vpn)) {
        $recent_preset_list_vpn = $recent_decoded_vpn;
    }
}

array_unshift($recent_preset_list_vpn, $recent_preset_entry_vpn);
$recent_preset_list_vpn = array_slice($recent_preset_list_vpn, 0, 100);
@file_put_contents($recent_preset_file_vpn, json_encode($recent_preset_list_vpn, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));

$qstr = "$qstr&amp;sca=$sca&amp;page=$page";

if ($w == "u") {
    //goto_url("./itemform.php?w=u&amp;it_id=$it_id&amp;$qstr");
    goto_url("./?ap=item_vpn&amp;w=u&amp;it_id=$it_id&amp;fn=$fn&amp;$qstr");
}


echo "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">";
?>
<style>
#after-save-confirm-layer {
    position: fixed;
    inset: 0;
    background: rgba(15, 23, 42, 0.52);
    backdrop-filter: blur(2px);
    -webkit-backdrop-filter: blur(2px);
    z-index: 20000;
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 1;
    transition: opacity .2s ease;
}
#after-save-confirm-layer .confirm-box {
    width: min(620px, calc(100vw - 28px));
    background: linear-gradient(180deg, #ffffff 0%, #f9fbff 100%);
    border: 1px solid #d7e3ff;
    border-radius: 14px;
    box-shadow: 0 18px 38px rgba(15, 23, 42, 0.28);
    padding: 18px 18px 14px;
    transform: translateY(0) scale(1);
}
#after-save-confirm-layer .confirm-title {
    font-size: 18px;
    font-weight: 700;
    color: #1f2937;
    margin-bottom: 8px;
}
#after-save-confirm-layer .confirm-message {
    font-size: 15px;
    line-height: 1.55;
    color: #111827;
}
#after-save-confirm-layer .confirm-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 16px;
}
#after-save-confirm-layer .confirm-actions button {
    border-radius: 999px;
    padding: 10px 20px;
    border: 1px solid transparent;
    font-size: 16px;
    cursor: pointer;
    min-width: 88px;
    transition: transform .15s ease, filter .15s ease;
}
#after-save-confirm-layer .btn-cancel {
    background: #eef2ff;
    color: #4338ca;
    border-color: #c7d2fe;
}
#after-save-confirm-layer .btn-ok {
    background: #4f46e5;
    color: #fff;
    border-color: #4338ca;
}
#after-save-confirm-layer .btn-cancel:hover,
#after-save-confirm-layer .btn-ok:hover {
    transform: translateY(-1px);
    filter: brightness(0.98);
}
</style>
<div id="after-save-confirm-layer" aria-hidden="false">
    <div class="confirm-box" role="dialog" aria-modal="true" aria-labelledby="after-save-confirm-title">
        <div class="confirm-title" id="after-save-confirm-title">저장이 완료되었습니다.</div>
        <div class="confirm-message">계속 입력하시겠습니까?</div>
        <div class="confirm-actions">
            <button type="button" class="btn-cancel" id="after-save-cancel">취소</button>
            <button type="button" class="btn-ok" id="after-save-ok">확인</button>
        </div>
    </div>
</div>
<script>
    (function() {
        var nextUrl = "<?php echo "./?ap=item_vpn&".str_replace('&amp;', '&', $qstr); ?>";
        var listUrl = "<?php echo "./?ap=list_vpn&".str_replace('&amp;', '&', $qstr); ?>";

        var layer = document.getElementById('after-save-confirm-layer');
        var okBtn = document.getElementById('after-save-ok');
        var cancelBtn = document.getElementById('after-save-cancel');

        function goNext() {
            location.href = nextUrl;
        }

        function goList() {
            location.href = listUrl;
        }

        if (okBtn) {
            okBtn.addEventListener('click', goNext);
            try { okBtn.focus(); } catch (e) {}
        }

        if (cancelBtn) {
            cancelBtn.addEventListener('click', goList);
        }

        if (layer) {
            layer.addEventListener('click', function(e) {
                if (e.target === layer) {
                    goList();
                }
            });
        }

        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                goList();
            }
        });
    })();
</script>
