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

$oi_list_perf_enabled = (isset($_GET['perf']) && $_GET['perf'] == '1');
$oi_list_perf_start = microtime(true);
$oi_list_perf_count_query_ms = 0;
$oi_list_perf_list_query_ms = 0;
$oi_list_perf_item_loop_ms = 0;
$oi_list_perf_auction_ms = 0;
$oi_list_perf_sql_count_start = isset($g5['perf_sql_count']) ? (int)$g5['perf_sql_count'] : 0;
$oi_list_perf_sql_time_start = isset($g5['perf_sql_time']) ? (float)$g5['perf_sql_time'] : 0.0;

$oi_list_cache_enabled = (
	!$is_member
	&& !$is_admin
	&& isset($_SERVER['REQUEST_METHOD'])
	&& strtoupper((string)$_SERVER['REQUEST_METHOD']) === 'GET'
	&& !isset($_GET['perf'])
);

$oi_list_cache_file = '';
if ($oi_list_cache_enabled) {
	$oi_list_cache_dir = G5_DATA_PATH.'/cache/list_page';
	if (!is_dir($oi_list_cache_dir)) {
		@mkdir($oi_list_cache_dir, G5_DIR_PERMISSION, true);
	}
	$oi_list_cache_key = md5((isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '') . '|' . (G5_IS_MOBILE ? 'm' : 'p'));
	$oi_list_cache_file = $oi_list_cache_dir.'/'.$oi_list_cache_key.'.html';
	$oi_list_cache_ttl = 45;

	if (is_file($oi_list_cache_file) && (time() - (int)@filemtime($oi_list_cache_file) <= $oi_list_cache_ttl)) {
		header('X-List-Cache: HIT');
		header('Cache-Control: private, max-age='.$oi_list_cache_ttl.', stale-while-revalidate=15');
		header('Pragma: public');
		readfile($oi_list_cache_file);
		exit;
	}

	header('X-List-Cache: MISS');
	ob_start();
}

global $g5, $write_table, $tender_table, $member;

//경매정보 라이브러리
// include_once (G5_SKIN_PATH.'/board/auction/auction.lib.php');

if(USE_G5_THEME && defined('G5_THEME_PATH')) {
    require_once(G5_SHOP_PATH.'/yc/list.php');
    return;
}

// 상품 리스트에서 다른 필드로 정렬을 하려면 아래의 배열 코드에서 해당 필드를 추가하세요.
if( isset($sort) && ! in_array($sort, array('it_name', 'it_sum_qty', 'it_price', 'it_use_avg', 'it_use_cnt', 'it_update_time', 'pt_comment', 'it_type1', 'it_type2', 'it_type3', 'it_type4', 'it_type5')) ){
    $sort='';
}

$plan_filter = '';
if (isset($_GET['plan'])) {
	$plan_filter = trim((string)$_GET['plan']);
} else if (isset($plan)) {
	$plan_filter = trim((string)$plan);
}
if (!in_array($plan_filter, array('', 'usage', 'hour', 'day', 'month', 'year'), true)) {
	$plan_filter = '';
}

// 상품등급 필터
$grade_filter = '';
if (isset($_GET['grade'])) {
	$grade_filter = strtoupper(trim((string)$_GET['grade']));
}
if (!in_array($grade_filter, array('', 'BASIC', 'PLUS', 'PRO', 'ULTRA', 'MAX'), true)) {
	$grade_filter = '';
}

// 상품종류 필터
$subtype_filter = '';
$subtype_filter_mode = '';
$_st_ca_prefix = substr((string)$ca_id, 0, 2);
if (isset($_GET['subtype']) && trim((string)$_GET['subtype']) !== '') {
	$_st_raw = trim((string)$_GET['subtype']);
	if (preg_match('/^[A-Za-z0-9 ._\-]{1,60}$/', $_st_raw)) {
		$subtype_filter = $_st_raw;
	}
}
if ($_st_ca_prefix === '30' || $_st_ca_prefix === '10' || $_st_ca_prefix === '20') {
	$subtype_filter_mode = 'os';
}

$sql = " select * from {$g5['g5_shop_category_table']} where ca_id = '$ca_id' and ca_use = '1'  ";
$ca = sql_fetch($sql);
if (!$ca['ca_id'])
    alert('등록된 분류가 없습니다.');

// 테마체크
$at = apms_ca_thema($ca_id, $ca);
if(!defined('THEMA_PATH')) {
	include_once(G5_LIB_PATH.'/apms.thema.lib.php');
}

// 본인인증, 성인인증체크
if(!$is_admin) {
    $msg = shop_member_cert_check($ca_id, 'list');
    if($msg)
        alert($msg, G5_SHOP_URL);
}

// 리스트 분류
$cate = array();
$cate = apms_item_category_array($ca_id);
$is_cate = (count($cate) > 0) ? true : false;

$thumb_w = $ca['ca_'.MOBILE_.'img_width'];
$thumb_h = $ca['ca_'.MOBILE_.'img_height'];
$list_mods = $ca['ca_'.MOBILE_.'list_mod'];
$list_rows = $ca['ca_'.MOBILE_.'list_row'];

// 스킨설정
$list_skin = $at['list'];

$wset = array();
if($ca['as_'.MOBILE_.'list_set']) {
	$wset = apms_unpack($ca['as_'.MOBILE_.'list_set']);
}

// 데모
if($is_demo) {
	@include($demo_setup_file);
}

// List
$list_skin_path = G5_SKIN_PATH.'/apms/list/'.$list_skin;
$list_skin_url = G5_SKIN_URL.'/apms/list/'.$list_skin;

// 추가설정
$sql_apms_where = $sql_apms_orderby = '';
@include_once($list_skin_path.'/list.head.skin.php');

$order_by = ($sort != "") ? $sort.' '.$sortodr.' ,'.$sql_apms_orderby.' it_order, pt_num desc, it_id desc' : $sql_apms_orderby.' it_order, pt_num desc, it_id desc'; // 상품 출력순서가 있다면
$where = "it_use = '1'";
if(isset($type) && $type) {
	$where .= " and it_type{$type} = '1'";
	$qstr .= '&amp;type='.$type;
}
$where .= " and (ca_id like '{$ca_id}%' or ca_id2 like '{$ca_id}%' or ca_id3 like '{$ca_id}%')";

// 판매허용 요금제 필터(AND 조건)
if ($plan_filter) {
	switch ($plan_filter) {
		case 'usage':
			$where .= " and (it_7 = '1' or it_billing_plan = 'usage')";
			break;
		case 'hour':
			$where .= " and coalesce(it_billing_plan, '') <> 'usage' and coalesce(it_7, '') <> '1'";
			$where .= " and cast(coalesce(it_buy_min_qty, 0) as decimal(10,6)) < 24";
			break;
		case 'day':
			$where .= " and coalesce(it_billing_plan, '') <> 'usage' and coalesce(it_7, '') <> '1'";
			$where .= " and cast(coalesce(it_buy_min_qty, 0) as decimal(10,6)) >= 24";
			$where .= " and cast(coalesce(it_buy_min_qty, 0) as decimal(10,6)) < 720";
			break;
		case 'month':
			$where .= " and coalesce(it_billing_plan, '') <> 'usage' and coalesce(it_7, '') <> '1'";
			$where .= " and cast(coalesce(it_buy_min_qty, 0) as decimal(10,6)) >= 720";
			$where .= " and cast(coalesce(it_buy_min_qty, 0) as decimal(10,6)) < 8760";
			break;
		case 'year':
			$where .= " and coalesce(it_billing_plan, '') <> 'usage' and coalesce(it_7, '') <> '1'";
			$where .= " and cast(coalesce(it_buy_min_qty, 0) as decimal(10,6)) >= 8760";
			break;
	}
	$qstr .= '&amp;plan='.$plan_filter;
}

// 상품등급 필터 WHERE
if ($grade_filter) {
	$esc_grade = sql_real_escape_string($grade_filter);
	$where .= " and it_spec_grade = '{$esc_grade}'";
	$qstr .= '&amp;grade='.$grade_filter;
}

// 상품종류 필터 WHERE
if ($subtype_filter !== '' && $subtype_filter_mode !== '') {
	$esc_st = sql_real_escape_string($subtype_filter);
	if ($subtype_filter_mode === 'ca_id2') {
		$where .= " and (ca_id2 like '{$esc_st}%' or ca_id3 like '{$esc_st}%')";
	} elseif ($subtype_filter_mode === 'os') {
		$where .= " and it_spec_os like '%{$esc_st}%'";
	}
	$qstr .= '&amp;subtype='.urlencode($subtype_filter);
}

$where .= $sql_apms_where;

// 정렬
$list_sort_href = './list.php?ca_id='.$ca_id.$qstr.'&amp;sort=';

if($sort) $qstr .= '&amp;sort='.$sort;
if($sortodr) $qstr .= '&amp;sortodr='.$sortodr;

// 상위분류
$ca_id_len = strlen($ca_id);
$up_href = '';
if ($ca_id_len > 2) {
	$len1 = $ca_id_len - 2;
	$up_href = './list.php?ca_id='.substr($ca_id,0,$len1).$qstr;
}

$g5['title'] = $ca['ca_name'].' 리스트';

if ($ca['ca_include_head'] && is_include_path_check($ca['ca_include_head']))
    @include_once($ca['ca_include_head']);
else
    include_once(G5_SHOP_PATH.'/_head.php');

// 상단 HTML
echo '<div id="sct_hhtml">'.conv_content($ca['ca_'.MOBILE_.'head_html'], 1).'</div>'.PHP_EOL;

// 상품 리스트
$list = array();

if(!$list_mods) $list_mods = 3;
if(!$list_rows) $list_rows = 5;

// 총몇개 = 한줄에 몇개 * 몇줄
$item_rows = $list_rows * $list_mods;

// 페이지가 없으면 첫 페이지 (1 페이지)
if ($page < 1) $page = 1;
// 시작 레코드 구함
$from_record = ($page - 1) * $item_rows;

// 전체 페이지 계산
$oi_list_perf_t = microtime(true);
$row_cnt = sql_fetch(" select count(*) as cnt from `{$g5['g5_shop_item_table']}` where $where ");
$oi_list_perf_count_query_ms = round((microtime(true) - $oi_list_perf_t) * 1000, 2);
$total_count = $row_cnt['cnt'];
$total_page  = ceil($total_count / $item_rows);

$num = $total_count - ($page - 1) * $item_rows;
$oi_list_perf_t = microtime(true);
$result = sql_query(" select * from `{$g5['g5_shop_item_table']}` where $where order by $order_by limit $from_record, $item_rows ");
$oi_list_perf_list_query_ms = round((microtime(true) - $oi_list_perf_t) * 1000, 2);

$oi_list_perf_loop_t = microtime(true);
for ($i=0; $row=sql_fetch_array($result); $i++) {
	$list[$i] = $row;
	$list[$i]['href'] = './item.php?it_id='.$row['it_id'].'&amp;ca_id='.$ca_id.$qstr.'&amp;page='.$page;
	$list[$i]['num'] = $num;
	$list[$i]['auction_on'] = $row['auction_on'];
	$list[$i]['it_id'] = get_text($row['it_id']);

	// 경매정보 이미지 위에 표시 {
	if ($list[$i]['auction_on'] == '1') {
		$oi_list_perf_auction_t = microtime(true);

		$row1_tmp = sql_fetch(" select * from `{$g5['write_auction_table']}` where pcnum = '{$list[$i]['it_id']}' order by wr_id desc limit 1 ");

		//get_info_auction($row1_tmp['wr_id'], $row1_tmp); // 이 함수 호출로 인해 최신의 경매상태정보를 변경시킴

		//////////////////////////////////////////////////////////
		// get_info_auction($row1_tmp['wr_id'], $row1_tmp); // 이 함수 호출시 auction.lib.php include 시 커뮤니티 플랫폼과 쇼핑몰 플랫폼과의 차이 오류로 인해 auction.lib.php 소스코드중 일부코드를 가져와서 수정함 {
		//////////////////////////////////////////////////////////

		$write_table = $g5['write_auction_table'];
		$tender_table = $g5['write_auction_tender_table'];
		$wr_id = $row1_tmp['wr_id'];

		$row_auction = sql_fetch(" select mb_id, wr_subject, wr_1, wr_2, wr_3, wr_4, wr_5, wr_6, wr_7, wr_8, wr_9, wr_10, pcnum, rpc_rental_days from $write_table where wr_id = '{$wr_id}' ");

		$pd = explode("|", $row_auction[wr_subject]);//0-공급업체, 1-상품명, 2-입찰단위금액, 3-입찰방식, 4-낙찰방식, 5-한 사람(회원) 입찰 가능수, 6-낙찰하기 위한 입찰자 수,7-배송방법, 8-배송비용

		unset($res);
		$res[wr_id] = $wr_id;
		$res[company] = trim($pd[0]);
		$res[product] = trim($pd[1]);
		////경매-부가정보////
		$res[tender_unit] = trim($pd[2]);
		$res[tender_method] = trim($pd[3]);
		$res[auction_off_method] = trim($pd[4]);
		$res[tender_possible_count] = trim($pd[5]);
		$res[auction_off_member_count] = trim($pd[6]);
		$res[delivery_method] = trim($pd[7]);
		$res[delivery_price] = trim($pd[8]);
		//최고가-최저가 쿼리
		if($res[auction_off_method]=="최저가") {$res[order_by] = "";} else {$res[order_by] = "desc";} //최저가-최대가(desc)
		$res[auction_query] = " select td_tender_point as point, count(td_tender_point) as cnt from $tender_table where wr_id = '{$wr_id}' group by point order by point {$res[order_by]}, cnt limit 1 ";
		//최고가-최저가 쿼리
		//낙찰을 위한 입찰자 쿼리
		$res[off_row_query] = " Select COUNT(DISTINCT mb_id) As cnt From $tender_table Where wr_id = '{$wr_id}' ";
		//낙찰을 위한 입찰자 쿼리
		////경매-정보////
		$res[start_datetime] = $row_auction[wr_1];
		$res[end_datetime] = $row_auction[wr_2];
		$res[inter_point] = doubleval($row_auction[wr_3]); //doubleval -  추가
		$res[tender_lower] = doubleval($row_auction[wr_4]);
		$res[tender_higher] = doubleval($row_auction[wr_5]);
		$res[day_limit] = intval($row_auction[wr_6]);
		$res[rpc_rental_hours] = intval(isset($row_auction['rpc_rental_hours']) ? $row_auction['rpc_rental_hours'] : 0);
		if($res[rpc_rental_hours] < 1) {
			$res[rpc_rental_hours] = intval($row_auction[rpc_rental_days]);
		}
		if($res[rpc_rental_hours] < 1) {
			$res[rpc_rental_hours] = 1;
		}
		$res[rpc_rental_days] = $res[rpc_rental_hours];
		//즉시구매가
		if($res[auction_off_method]=="최고가"){if($res[tender_higher]>0){$res[buy_now_price] = $res[tender_higher];} else {$res[buy_now_price] = 0;}} //최고가-->tender_higher를 즉시 구매가로 설정
		if($res[auction_off_method]=="최저가"){if($res[tender_lower]>0){$res[buy_now_price] = $res[tender_lower];} else {$res[buy_now_price] = 0;}} //최고가-->tender_higher를 즉시 구매가로 설정
		if($res[auction_off_method]=="최고가"){$res[lower_label]="시작가";$res[higher_label]="상한가";} //라벨설정
		if($res[auction_off_method]=="최저가"){$res[lower_label]="하한가";$res[higher_label]="시작가";} //라벨설정
		//즉시구매가
		////경매-정보////
		////경매-입찰정보 { ////
		$res[tender_count] = intval($row_auction[wr_7]);
		$res[status] = intval($row_auction[wr_8]);
		$res[auction_off_point] = doubleval($row_auction[wr_9]);//낙찰금액
		$res[mb_id] = $row_auction[wr_10];
		$res[pcnum] = $row_auction[pcnum];
		////경매-입찰정보 } ////

		////경매-상품정보 { ////
		$is_vpn_item = (stripos(trim($list[$i]['it_name']), 'VPN') === 0) || (stripos(trim($row['it_name']), 'VPN') === 0);
		if($is_vpn_item){
			$headers = ["", "IP"];
		}else{
			$headers = ["", "OS", "CPU", "GPU", "IP", "RAM", "SSD", "HDD", "USB"];
		}
		$rows = [];

		$result_api_data = sql_query("SELECT * FROM {$g5['g5_shop_item_table']} WHERE it_id='{$row_auction[pcnum]}' ORDER BY it_id DESC LIMIT 1");
		while($api_data = sql_fetch_array($result_api_data)){
			$it_id = $api_data['it_id'];
			$it_origin_mgr_from_api = $api_data['it_origin_mgr_from_api'];
			$M_storeid = explode("Ž",$api_data['it_origin_mgr_from_api'])[0]." ".explode("Ž",$api_data['it_origin_mgr_from_api'])[1];
			$M_storename = explode("Ž",$api_data['it_origin_mgr_from_api'])[2];
			// $extIP = $api_data['extIP'];
			// JSON 데이터
			$jsonData_it_spec_remote_sw = $api_data['it_spec_remote_sw'];

			// JSON 데이터를 배열로 디코드
			$dataArray_it_spec_remote_sw = json_decode($jsonData_it_spec_remote_sw, true);

			// RemoteIP 값을 추출하여 $extIP 변수에 저장
			$extIP = isset($dataArray_it_spec_remote_sw[0]['RemoteIP__0']) ? $dataArray_it_spec_remote_sw[0]['RemoteIP__0'] : null;
			$remote_ip_org = explode(" ", $extIP)[0];
			$remote_ip_parts = explode(".", $remote_ip_org); // IP 주소를 점(.)으로 분리
			// 각 부분을 3자리로 맞추기 위해 앞에 0을 추가
			foreach ($remote_ip_parts as &$part) {
				$part = str_pad($part, 3, '0', STR_PAD_LEFT);
			}
			// 마스킹할 부분을 선택
			$remote_ip_parts[1] = '***';
			$remote_ip_parts[3] = '***';
			// 마스킹된 IP 주소를 다시 조합
			$masked_ip = implode(".", $remote_ip_parts);
			$remote_ip = $masked_ip; // 출력: 111.***.022.***

			$remote_ip_country_code = strtolower($dataArray_it_spec_remote_sw[0]['RemoteIP_CountryCode__0']);
			$remote_ip_country_name = $dataArray_it_spec_remote_sw[0]['RemoteIP_CountryName__0'];
			$remote_ip_city_name = $dataArray_it_spec_remote_sw[0]['RemoteIP_City__0'];
			$remote_ip_country_flag = "<img src='" . G5_DATA_URL . "/item/img_nation_flag/svg/{$remote_ip_country_code}.svg' class='nation_flag_img2'>";

			//$it_spec_cpu_arr = explode("Ž", trim(str_ireplace(array("(R)", "(TM)", "Intel", "AMD", "with Radeon Graphics", "with Radeon Vega Graphics", "CPU", "Core ", " Cores", "Eight-Processor"), array("", "", "", "", "", "", "", "", "C", ""), $api_data['it_spec_cpu'])));
			$it_spec_cpu_arr = explode("Ž", trim(str_ireplace(array("(R)", "(TM)", "with Radeon Graphics", "with Radeon Vega Graphics", "CPU", "Core ", "Eight-Processor"), array("", "", "", "", "", "", ""), $api_data['it_spec_cpu'])));
			if (count($it_spec_cpu_arr) == 1) {
				$it_spec_cpu = $it_spec_cpu_arr[0];
			} else if (count($it_spec_cpu_arr) == 2) {
				$it_spec_cpu = "[Dual] " . $it_spec_cpu_arr[0];
			} else if (count($it_spec_cpu_arr) == 3) {
				$it_spec_cpu = "[Triple] " . $it_spec_cpu_arr[0];
			} else if (count($it_spec_cpu_arr) == 4) {
				$it_spec_cpu = "[Quad] " . $it_spec_cpu_arr[0];
			}
			if (stripos($it_spec_cpu, 'intel') !== false) {
				$logo_cpu = "<img src='" . G5_DATA_URL . "/item/img_logo/logo_intel.png' class='cpu_logo_img2'>";
			} else if (stripos($it_spec_cpu, 'amd') !== false) {
				$logo_cpu = "<img src='" . G5_DATA_URL . "/item/img_logo/logo_amd.png' class='cpu_logo_img2'>";
			} else {
				$logo_cpu = "";
			}

			// CPU 데이터
			$cpu_data = $api_data['it_spec_cpu'];

			// 정규식을 사용하여 괄호 속에 "Cores"라는 단어가 포함된 숫자를 추출
			if (preg_match('/\((\d+) Cores\)/', $cpu_data, $matches)) {
				// 추출된 숫자를 $cpu_core 변수에 저장
				$cpu_core = $matches[1];
			} else {
				// "Cores"가 포함된 문자열이 없는 경우
				$cpu_core = null;
			}
			$it_spec_mainboard = $api_data['it_spec_mainboard'];
			$it_spec_ram = $api_data['it_spec_ram'];
			$it_spec_ram_type = $api_data['it_spec_ram_type'];
			//$SSDinfo = $api_data['SSDinfo'];
			$it_spec_ssd =  $api_data['it_spec_ssd'] === "0 GB" ? "<div style='width:100%; min-width:40px; text-align:left;'>Not installed</div>" : $api_data['it_spec_ssd'];
			$it_spec_ssd_type = $api_data['it_spec_ssd_type'];
			//$SSD = $api_data['SSD'];
			//$HDDinfo = $api_data['HDDinfo'];
			$it_spec_hdd = $api_data['it_spec_hdd'] === "0 GB" ? "<div style='width:100%; min-width:40px; text-align:left;'>Not installed</div>" : $api_data['it_spec_hdd'];
			$it_spec_hdd_type = $api_data['it_spec_hdd_type'];
			//$HDD = $api_data['HDD'];
			$it_spec_gpu_arr = explode("Ž", trim(str_ireplace(array("(R)", "(TM)"), array("", ""), $api_data['it_spec_gpu'])));
			if (count($it_spec_gpu_arr) == 1) {
				$it_spec_gpu = $it_spec_gpu_arr[0];
			} else if (count($it_spec_gpu_arr) > 1) {
				if ((strpos($it_spec_gpu_arr[0], "NVIDIA") !== false) || (strpos($it_spec_gpu_arr[0], "AMD") !== false)) {
					$it_spec_gpu = $it_spec_gpu_arr[0];
				} else if ((strpos($it_spec_gpu_arr[1], "NVIDIA") !== false) || (strpos($it_spec_gpu_arr[1], "AMD") !== false)) {
					$it_spec_gpu = $it_spec_gpu_arr[1];
				} else {
					$it_spec_gpu = $it_spec_gpu_arr[0] . "<br>" . $it_spec_gpu_arr[1];
				}
			}
			if (stripos($it_spec_gpu, 'nvidia') !== false) {
				$logo_gpu = "<img src='" . G5_DATA_URL . "/item/img_logo/logo_nvidia.png' class='gpu_logo_img2'>";
			}
			if (stripos($it_spec_gpu, 'quadro') !== false) {
				$logo_gpu = "<img src='" . G5_DATA_URL . "/item/img_logo/logo_nvidia_quadro.png' class='gpu_logo_img2'>";
			} else if (stripos($it_spec_gpu, 'geforce') !== false) {
				$logo_gpu = "<img src='" . G5_DATA_URL . "/item/img_logo/logo_nvidia_geforce.png' class='gpu_logo_img2'>";
			}

			if (stripos($it_spec_gpu, 'radeon') !== false) {
				$logo_gpu = "<img src='" . G5_DATA_URL . "/item/img_logo/logo_amd_radeon.png' class='gpu_logo_img2'>";
			} else {
				$logo_gpu = "";
			}

			//$gpu_ram = $api_data['gpu_ram'];

			//$it_spec_os = trim(str_ireplace(array("Microsoft", "Windows", "(64Bit)"), array("", "Win", ""), $api_data['it_spec_os']));
			$it_spec_os = trim($api_data['it_spec_os']);
			if (stripos($it_spec_os, 'Windows 11') !== false || stripos($it_spec_os, 'Windows11') !== false) {
				$it_spec_os = (stripos($it_spec_os, 'Microsoft') !== false) ? $it_spec_os : "Microsoft " . $it_spec_os;
				$OS_flag = "<img src='" . G5_DATA_URL . "/item/img_os/Windows11.png' class='os_img2'>";
			} else if (stripos($it_spec_os, 'Windows 10') !== false || stripos($it_spec_os, 'Windows10') !== false) {
				$it_spec_os = (stripos($it_spec_os, 'Microsoft') !== false) ? $it_spec_os : "Microsoft " . $it_spec_os;
				$OS_flag = "<img src='" . G5_DATA_URL . "/item/img_os/Windows10.png' class='os_img2'>";
			} else if (stripos($it_spec_os, 'Windows 8') !== false || stripos($it_spec_os, 'Windows8') !== false) {
				$it_spec_os = (stripos($it_spec_os, 'Microsoft') !== false) ? $it_spec_os : "Microsoft " . $it_spec_os;
				$OS_flag = "<img src='" . G5_DATA_URL . "/item/img_os/Windows8.png' class='os_img2'>";
			} else if (stripos($it_spec_os, 'Windows 7') !== false || stripos($it_spec_os, 'Windows7') !== false) {
				$it_spec_os = (stripos($it_spec_os, 'Microsoft') !== false) ? $it_spec_os : "Microsoft " . $it_spec_os;
				$OS_flag = "<img src='" . G5_DATA_URL . "/item/img_os/Windows7.png' class='os_img2'>";
			} else if (stripos($it_spec_os, 'Windows Server 2016') !== false) {
				$it_spec_os = (stripos($it_spec_os, 'Microsoft') !== false) ? $it_spec_os : "Microsoft " . $it_spec_os;
				$OS_flag = "<img src='" . G5_DATA_URL . "/item/img_os/WindowsServer2016.png' class='os_img2'>";
			} else {
				$OS_flag = "";
			}

			$rantal_fee_type = $api_data['rantal_fee_type'];
			$rental_fee = $api_data['rental_fee'];
			$rental_setting_fee = $api_data['rental_setting_fee'];
			$rental_fee_first_daily = round(($rental_fee + $rental_setting_fee) / 30);
			$rental_fee_ext_daily = round(($rental_fee) / 30);
			$rental_stat = $api_data['rental_stat'];
			$client_number = $api_data['client_number'];
			$cpu_clock = $api_data['cpu_clock'];
			$AppVer = $api_data['AppVer'];

			$it_spec_keyboard = !empty(trim($api_data['it_spec_keyboard'])) ? "KEYBOARD" : "";
			$it_spec_mouse = !empty(trim($api_data['it_spec_mouse'])) ? "MOUSE" : "";

			// Initialize the array
			$it_spec_device_arr = [];

			// Check if $it_spec_keyboard is not empty and add to array
			if (!empty(trim($it_spec_keyboard))) {
				$it_spec_device_arr[] = "KEYBOARD(O)";
			} else {
				$it_spec_device_arr[] = "KEYBOARD(X)";
			}

			// Check if $it_spec_mouse is not empty and add to array
			if (!empty(trim($it_spec_mouse))) {
				$it_spec_device_arr[] = "MOUSE(O)";
			} else {
				$it_spec_device_arr[] = "MOUSE(X)";
			}

			// Join array elements with a comma if there are multiple elements
			$it_spec_devices = (count($it_spec_device_arr) > 0) ? implode(', ', $it_spec_device_arr) : "KEYBOARD(X) , MOUSE(X)";

			if($is_vpn_item){
				$rows[] = [
					!empty(trim($remote_ip_country_name)) ? !empty($remote_ip_city_name) ? $remote_ip_country_flag . $remote_ip_country_name . " / " . $remote_ip_city_name : $remote_ip_country_flag . $remote_ip_country_name : "",
					!empty(trim($remote_ip_country_name)) ? $remote_ip : $remote_ip
				];
			} else {
				$rows[] = [
					!empty(trim($remote_ip_country_name)) ? !empty($remote_ip_city_name) ? $remote_ip_country_flag . $remote_ip_country_name . " / " . $remote_ip_city_name : $remote_ip_country_flag . $remote_ip_country_name : "",
					$it_spec_cpu,
					$it_spec_gpu,
					!empty(trim($remote_ip_country_name)) ? $remote_ip : $remote_ip,
					$it_spec_ram . (!empty($it_spec_ram_type) ? " ($it_spec_ram_type)" : ""),
					$it_spec_ssd . (!empty($it_spec_ssd_type) ? " ($it_spec_ssd_type)" : ""),
					$it_spec_hdd . (!empty($it_spec_hdd_type) ? " ($it_spec_hdd_type)" : ""),
					$it_spec_devices
				];
			}
		}

		$product_from_shop_item = "";
		// $ignore_headers = ["IP", "RAM", "SSD", "HDD", "USB"];
		if($is_vpn_item){
			$headers = ["", "IP"];
			$ignore_headers = ["IP"];
		}else{
			$headers = ["", "CPU", "GPU", "IP", "RAM", "SSD", "HDD", "USB"];
			$ignore_headers = ["", "CPU", "GPU", "IP", "RAM", "SSD", "HDD", "USB"];
		}
		foreach ($headers as $index => $header) {
			$product_from_shop_item .= "<tr>";
			if (!in_array($header, $ignore_headers)) {
				foreach ($rows as $row_auction) {
					$product_from_shop_item .= "<td colspan='2'>{$row_auction[$index]}</td>";
				}
			} else {
				$product_from_shop_item .= "<td>&nbsp;&nbsp;$header </td>";
				foreach ($rows as $row_auction) {
					$product_from_shop_item .= "<td>{$row_auction[$index]}</td>";
				}
			}

			$product_from_shop_item .= "</tr>";
		}
		$res['product_from_shop_item'] = $product_from_shop_item; // shop_item 에서 추출한 하드웨어 스펙
		$list[$i]['product_from_shop_item'] = $product_from_shop_item;
		////경매-상품정보 } ////

		// 경매 상태 변경 --  추가
		// 경매전 -> 시작시간이 지났을 때 -> 경매진행중
		// if ($res[status] == "0" && $res[start_datetime] <= G5_TIME_YMDHIS)
		// {
		// sql_query(" update $write_table set wr_8 = '1' where wr_id = '$res[wr_id]' ");
		// $res[status] = "1";
		// }

		// 낙찰자가 있는 경우가 아니면 경매상품 경매종료시간 수정시 경매진행중으로 언제나 변경가능하게 함 JSLEE
		if ($res[status] != "2" && $res[start_datetime] <= G5_TIME_YMDHIS)
		{
			sql_query(" update $write_table set wr_8 = '1' where wr_id = '$res[wr_id]' ");
			$res[status] = "1";
		}

		// 경매진행중 -> 종료시간이 지났을 때 -> 경매종료
		if ($res[status] == "1" && $res[end_datetime] <= G5_TIME_YMDHIS)
		{////--1
			$result_auction = auction_successful($res);
			if ($result_auction[wr_8] > 1)
			{////--2
				$res[tender_count] = $result_auction[wr_7];
				$res[status] = $result_auction[wr_8];
				$res[auction_off_point] = doubleval($result_auction[wr_9]);//낙찰금액
				$res[mb_id] = $result_auction[wr_10];
			}////--2
		}////--1

		// auction_tender 테이블의 status 와 동기화 시키기 위해 update
		sql_query(" update $tender_table set td_status = '$res[status]' where wr_id = '$res[wr_id]' ");

		//////////////////////////////////////////////////////////
		// get_info_auction($row1_tmp['wr_id'], $row1_tmp); // 이 함수 호출시 auction.lib.php include 시 커뮤니티 플랫폼과 쇼핑몰 플랫폼과의 차이 오류로 인해 auction.lib.php 소스코드중 일부코드를 가져와서 수정함 }
		//////////////////////////////////////////////////////////


		$row1 = sql_fetch(" select * from `{$g5['write_auction_table']}` where pcnum = '{$list[$i]['it_id']}' order by wr_id desc limit 1 ");
		$row2 = sql_fetch(" select * from `{$g5['write_auction_tender_table']}` where pcnum = '{$list[$i]['it_id']}' order by td_tender_point desc limit 1 ");

		if ($row2['td_tender_point'] === null || $row2['td_tender_point'] == 0) {

			$list[$i]['last_auction_price'] = $row1['wr_4']; // 경매 시작가
			$list[$i]['buy_it_now_price'] = $row1['wr_5']; // 경매 상한가 (즉구가)
			$list[$i]['origin_start_price'] = intval($row1['wr_4']); // 경매 원본 시작가
			$_my_mb_id = isset($member['mb_id']) ? addslashes($member['mb_id']) : '';
			$list[$i]['my_bid'] = $_my_mb_id ? (sql_fetch(" select td_id from `{$g5['write_auction_tender_table']}` where pcnum='{$list[$i]['it_id']}' and mb_id='$_my_mb_id' limit 1 ") ? 1 : 0) : 0;

			// 0=시작전, 1=진행중, 2=종료[낙찰], 3=종료[유찰]
			switch($row1['wr_8']) {
				case '0' : $od_status = '경매시작전'; $od_status_display = '<span style="color:silver">경매시작전</span>'; break;
				case '1' : $od_status = '경매진행중'; $od_status_display = '<span style="color:#66FF66">경매진행중</span>'; break;
				case '2' : $od_status = '경매종료[낙찰]'; $od_status_display = '<span style="color:#FFFF66">경매종료[낙찰]</span>'; break;
				case '3' : $od_status = '경매종료[유찰]'; $od_status_display = '<span style="color:silver">경매종료[유찰]</span>'; break;
				default  : $od_status = '경매취소'; $od_status_display = '<span style="color:silver">경매취소</span>'; break;
			}
			$list[$i]['last_auction_status'] = $od_status; // 경매 진행상태
			$list[$i]['last_auction_status_display'] = $od_status_display; // 경매 진행상태
			$list[$i]['rpc_rental_hours'] = (int)(isset($row1['rpc_rental_hours']) ? $row1['rpc_rental_hours'] : $row1['rpc_rental_days']);
			if($list[$i]['rpc_rental_hours'] < 1) {
				$list[$i]['rpc_rental_hours'] = 1;
			}
			$list[$i]['rpc_rental_days'] = $list[$i]['rpc_rental_hours']; // 경매 대여기간(시간)

			// 경매시작일시 주어진 시간 변수 (예: "2024-07-16 12:23:15")
			$auction_term_start = $row1['wr_1']; // 경매시작일시
			// 현재 시간
			$current_time = new DateTime();
			// 주어진 시간을 DateTime 객체로 변환
			$auction_term_start_dt = new DateTime($auction_term_start);
			// 두 시간의 차이 계산
			$interval = $current_time->diff($auction_term_start_dt);
			// 경과한 시간 형식 지정
			$auction_term_start_display = '';
			$start_display_flag = true;
			if ($interval->y > 0) {
				$auction_term_start_display .= $interval->y . '년 ';
				$start_display_flag = false;
			}
			if ($interval->m > 0) {
				$auction_term_start_display .= $interval->m . '개월 ';
				$start_display_flag = false;
			}
			if ($interval->d > 0 && $start_display_flag) {
				$auction_term_start_display .= $interval->d . '일 ';
				$start_display_flag = false;
			}
			if ($interval->h > 0 && $start_display_flag) {
				$auction_term_start_display .= $interval->h . '시간 ';
			}
			if ($interval->i > 0 && $start_display_flag) {
				$auction_term_start_display .= $interval->i . '분 ';
			}
			if ($interval->s > 0 && $start_display_flag) {
				$auction_term_start_display .= $interval->s . '초 ';
			}
			// 경과한 시간이 없다면 "0초" 표시
			if (empty($auction_term_start_display)) {
				$auction_term_start_display = '0초';
			}
			if ($start_display_flag) {
				if ((strtotime($auction_term_start)-G5_SERVER_TIME) < 0) {
					$term_start_tail_display = "경과";
				} else {
					$term_start_tail_display = "남음";
				}
			} else {
				if ((strtotime($auction_term_start)-G5_SERVER_TIME) < 0) {
					$term_start_tail_display = "이상 경과";
				} else {
					$term_start_tail_display = "이상 남음";
				}
			}

			// 경매종료일시 주어진 시간 변수 (예: "2024-07-16 12:23:15")
			$auction_term_stop = $row1['wr_2']; // 경매종료일시
			// 현재 시간
			$current_time = new DateTime();
			// 주어진 시간을 DateTime 객체로 변환
			$auction_term_stop_dt = new DateTime($auction_term_stop);
			// 두 시간의 차이 계산
			$interval = $current_time->diff($auction_term_stop_dt);
			// 경과한 시간 형식 지정
			$auction_term_stop_display = '';
			$stop_display_flag = true;
			if ($interval->y > 0) {
				$auction_term_stop_display .= $interval->y . '년 ';
				$stop_display_flag = false;
			}
			if ($interval->m > 0) {
				$auction_term_stop_display .= $interval->m . '개월 ';
				$stop_display_flag = false;
			}
			if ($interval->d > 0 && $stop_display_flag) {
				$auction_term_stop_display .= $interval->d . '일 ';
				$stop_display_flag = false;
			}
			if ($interval->h > 0 && $stop_display_flag) {
				$auction_term_stop_display .= $interval->h . '시간 ';
			}
			if ($interval->i > 0 && $stop_display_flag) {
				$auction_term_stop_display .= $interval->i . '분 ';
			}
			if ($interval->s > 0 && $stop_display_flag) {
				$auction_term_stop_display .= $interval->s . '초 ';
			}
			// 경과한 시간이 없다면 "0초" 표시
			if (empty($auction_term_stop_display)) {
				$auction_term_stop_display = '0초';
			}
			if ($stop_display_flag) {
				if ((strtotime($auction_term_stop)-G5_SERVER_TIME) < 0) {
					$term_stop_tail_display = "경과";
				} else {
					$term_stop_tail_display = "남음";
				}
			} else {
				if ((strtotime($auction_term_stop)-G5_SERVER_TIME) < 0) {
					$term_stop_tail_display = "이상 경과";
				} else {
					$term_stop_tail_display = "이상 남음";
				}
			}
			$list[$i]['rpc_auction_expire_remaintime'] = $auction_term_stop_display . $term_stop_tail_display; // 경매 종료시간

			$list[$i]['rpc_auction_expire_date'] = $row1['wr_2']; // 경매 종료시간

			$list[$i]['rpc_auction_term_stop'] = strtotime($auction_term_stop) * 1000; // 자바스크립트에서 사용할 밀리초 단위 시간

		} else {

			$list[$i]['last_auction_price'] = $row2['td_tender_point']; // 경매 시작가
			$list[$i]['buy_it_now_price'] = $row1['wr_5']; // 경매 상한가 (즉구가)
			$list[$i]['origin_start_price'] = intval($row1['wr_4']); // 경매 원본 시작가
			$_my_mb_id = isset($member['mb_id']) ? addslashes($member['mb_id']) : '';
			$list[$i]['my_bid'] = $_my_mb_id ? (sql_fetch(" select td_id from `{$g5['write_auction_tender_table']}` where pcnum='{$list[$i]['it_id']}' and mb_id='$_my_mb_id' limit 1 ") ? 1 : 0) : 0;

			// 0=시작전, 1=진행중, 2=종료[낙찰], 3=종료[유찰]
			switch($row2['td_status']) {
				case '0' : $od_status = '경매시작전'; $od_status_display = '<span style="color:silver">경매시작전</span>'; break;
				case '1' : $od_status = '경매진행중'; $od_status_display = '<span style="color:#66FF66">경매진행중</span>'; break;
				case '2' : $od_status = '경매종료[낙찰]'; $od_status_display = '<span style="color:#FFFF66">경매종료[낙찰]</span>'; break;
				case '3' : $od_status = '경매종료[유찰]'; $od_status_display = '<span style="color:silver">경매종료[유찰]</span>'; break;
				default  : $od_status = '경매취소'; $od_status_display = '<span style="color:silver">경매취소</span>'; break;
			}
			$list[$i]['last_auction_status'] = $od_status; // 경매 진행상태
			$list[$i]['last_auction_status_display'] = $od_status_display; // 경매 진행상태
			$list[$i]['rpc_rental_hours'] = (int)(isset($row1['rpc_rental_hours']) ? $row1['rpc_rental_hours'] : $row1['rpc_rental_days']);
			if($list[$i]['rpc_rental_hours'] < 1) {
				$list[$i]['rpc_rental_hours'] = 1;
			}
			$list[$i]['rpc_rental_days'] = $list[$i]['rpc_rental_hours']; // 경매 대여기간(시간)

			// 경매시작일시 주어진 시간 변수 (예: "2024-07-16 12:23:15")
			$auction_term_start = $row1['wr_1']; // 경매시작일시
			// 현재 시간
			$current_time = new DateTime();
			// 주어진 시간을 DateTime 객체로 변환
			$auction_term_start_dt = new DateTime($auction_term_start);
			// 두 시간의 차이 계산
			$interval = $current_time->diff($auction_term_start_dt);
			// 경과한 시간 형식 지정
			$auction_term_start_display = '';
			$start_display_flag = true;
			if ($interval->y > 0) {
				$auction_term_start_display .= $interval->y . '년 ';
				$start_display_flag = false;
			}
			if ($interval->m > 0) {
				$auction_term_start_display .= $interval->m . '개월 ';
				$start_display_flag = false;
			}
			if ($interval->d > 0 && $start_display_flag) {
				$auction_term_start_display .= $interval->d . '일 ';
				$start_display_flag = false;
			}
			if ($interval->h > 0 && $start_display_flag) {
				$auction_term_start_display .= $interval->h . '시간 ';
			}
			if ($interval->i > 0 && $start_display_flag) {
				$auction_term_start_display .= $interval->i . '분 ';
			}
			if ($interval->s > 0 && $start_display_flag) {
				$auction_term_start_display .= $interval->s . '초 ';
			}
			// 경과한 시간이 없다면 "0초" 표시
			if (empty($auction_term_start_display)) {
				$auction_term_start_display = '0초';
			}
			if ($start_display_flag) {
				if ((strtotime($auction_term_start)-G5_SERVER_TIME) < 0) {
					$term_start_tail_display = "경과";
				} else {
					$term_start_tail_display = "남음";
				}
			} else {
				if ((strtotime($auction_term_start)-G5_SERVER_TIME) < 0) {
					$term_start_tail_display = "이상 경과";
				} else {
					$term_start_tail_display = "이상 남음";
				}
			}

			// 경매종료일시 주어진 시간 변수 (예: "2024-07-16 12:23:15")
			$auction_term_stop = $row1['wr_2']; // 경매종료일시
			// 현재 시간
			$current_time = new DateTime();
			// 주어진 시간을 DateTime 객체로 변환
			$auction_term_stop_dt = new DateTime($auction_term_stop);
			// 두 시간의 차이 계산
			$interval = $current_time->diff($auction_term_stop_dt);
			// 경과한 시간 형식 지정
			$auction_term_stop_display = '';
			$stop_display_flag = true;
			if ($interval->y > 0) {
				$auction_term_stop_display .= $interval->y . '년 ';
				$stop_display_flag = false;
			}
			if ($interval->m > 0) {
				$auction_term_stop_display .= $interval->m . '개월 ';
				$stop_display_flag = false;
			}
			if ($interval->d > 0 && $stop_display_flag) {
				$auction_term_stop_display .= $interval->d . '일 ';
				$stop_display_flag = false;
			}
			if ($interval->h > 0 && $stop_display_flag) {
				$auction_term_stop_display .= $interval->h . '시간 ';
			}
			if ($interval->i > 0 && $stop_display_flag) {
				$auction_term_stop_display .= $interval->i . '분 ';
			}
			if ($interval->s > 0 && $stop_display_flag) {
				$auction_term_stop_display .= $interval->s . '초 ';
			}
			// 경과한 시간이 없다면 "0초" 표시
			if (empty($auction_term_stop_display)) {
				$auction_term_stop_display = '0초';
			}
			if ($stop_display_flag) {
				if ((strtotime($auction_term_stop)-G5_SERVER_TIME) < 0) {
					$term_stop_tail_display = "경과";
				} else {
					$term_stop_tail_display = "남음";
				}
			} else {
				if ((strtotime($auction_term_stop)-G5_SERVER_TIME) < 0) {
					$term_stop_tail_display = "이상 경과";
				} else {
					$term_stop_tail_display = "이상 남음";
				}
			}
			$list[$i]['rpc_auction_expire_remaintime'] = $auction_term_stop_display . $term_stop_tail_display; // 경매 종료시간

			$list[$i]['rpc_auction_expire_date'] = $row1['wr_2']; // 경매 종료시간

			$list[$i]['rpc_auction_term_stop'] = strtotime($auction_term_stop) * 1000; // 자바스크립트에서 사용할 밀리초 단위 시간

		}

		$oi_list_perf_auction_ms += (microtime(true) - $oi_list_perf_auction_t) * 1000;
	}
	// 경매정보 이미지 위에 표시 }

	$num--;
}
$oi_list_perf_item_loop_ms = round((microtime(true) - $oi_list_perf_loop_t) * 1000, 2);

// 네비게이션
$nav = array();
$len = strlen($ca_id) / 2;
$n=0;
for ($i=1; $i<=$len; $i++) {
	$code = substr($ca_id,0,$i*2);
	$nav[$n]['ca_id'] = $code;

	$row = sql_fetch(" select ca_name from {$g5['g5_shop_category_table']} where ca_id = '$code' ");
	$nav[$n]['name'] = $row['ca_name'];

	if($ca_id === $code) {
		$nav[$n]['on'] = true;
		$nav[$n]['cnt'] = $total_count;
	} else {
		$nav[$n]['on'] = false;
		$nav[$n]['cnt'] = 0;
	}

	$n++;
}

$is_nav = ($n > 0) ? true : false;
$nav_title = $ca['ca_name'];

// 페이징
$write_pages = G5_IS_MOBILE ? $config['cf_mobile_pages'] : $config['cf_write_pages'];
$list_page = $_SERVER['SCRIPT_NAME'].'?ca_id='.$ca_id.$qstr.'&amp;page=';

// Button
$admin_href = $config_href = $write_href = '';
if(USE_PARTNER) {
	if($is_admin) {
		if(IS_PARTNER) {
			$write_href = './myshop.php?mode=item&amp;fn='.$ca['pt_form'];
			$admin_href = './myshop.php?mode=list&amp;sca='.$ca_id;
		} else {
			$write_href = G5_ADMIN_URL.'/shop_admin/itemform.php?fn='.$ca['pt_form'];
			$admin_href = G5_ADMIN_URL.'/shop_admin/itemlist.php?ca_id='.$ca_id;
		}
		$config_href = G5_ADMIN_URL.'/shop_admin/categoryform.php?w=u&amp;ca_id='.$ca_id;
	} else if (IS_PARTNER && $ca['pt_use']) {
		$write_href = './myshop.php?mode=item&amp;fn='.$ca['pt_form'];
		$admin_href = './myshop.php?mode=list&amp;sca='.$ca_id;
	}
} else {
	if($is_admin == 'super') {
		$write_href = G5_ADMIN_URL.'/shop_admin/itemform.php?fn='.$ca['pt_form'];
		$admin_href = G5_ADMIN_URL.'/shop_admin/itemlist.php?ca_id='.$ca_id;
		$config_href = G5_ADMIN_URL.'/shop_admin/categoryform.php?w=u&amp;ca_id='.$ca_id;
	}
}

$rss_href = ($ca_id) ? G5_URL.'/rss/?cid='.urlencode($ca_id) : '';

$lm = ''; // 리스트 모드
$ls = $list_skin; // 리스트 스킨

// 셋업
$setup_href = '';
if (!$ev_id && is_file($list_skin_path.'/setup.skin.php') && ($is_demo || $is_designer)) {
    $setup_href = './skin.setup.php?skin=list&amp;name='.urlencode($ls).'&amp;ca_id='.urlencode($ca_id);
}

// 스킨
// $list_skin_path = /skin/apms/list/basic/list.skin.php
$list_skin_file = $list_skin_path.'/list.skin.php';

if(file_exists($list_skin_file)) {
	include_once($list_skin_file);
} else {
	echo '<p>'.str_replace(G5_PATH.'/', '', $list_skin_file).' 파일을 찾을 수 없습니다.<br>관리자에게 알려주시면 감사하겠습니다.</p>';
}

// 통신판매중개 플랫폼 거래 안내
if(function_exists('vpnlink_platform_notice')) echo vpnlink_platform_notice('list');

// 하단 HTML
echo '<div id="sct_thtml">'.conv_content($ca['ca_'.MOBILE_.'tail_html'], 1).'</div>'.PHP_EOL;

if ($ca['ca_include_tail'] && is_include_path_check($ca['ca_include_tail']))
    @include_once($ca['ca_include_tail']);
else
    include_once(G5_SHOP_PATH.'/_tail.php');

echo "\n<!-- {$ca['ca_'.MOBILE_.'skin']} -->\n";

if ($oi_list_perf_enabled) {
	$oi_list_perf_total_ms = round((microtime(true) - $oi_list_perf_start) * 1000, 2);
	$oi_list_perf_sql_count_end = isset($g5['perf_sql_count']) ? (int)$g5['perf_sql_count'] : 0;
	$oi_list_perf_sql_time_end = isset($g5['perf_sql_time']) ? (float)$g5['perf_sql_time'] : 0.0;
	$oi_list_perf_sql_delta_count = max(0, $oi_list_perf_sql_count_end - $oi_list_perf_sql_count_start);
	$oi_list_perf_sql_delta_ms = round(max(0, ($oi_list_perf_sql_time_end - $oi_list_perf_sql_time_start) * 1000), 2);

	header('X-List-Perf: total_ms='.$oi_list_perf_total_ms.'; count_query_ms='.$oi_list_perf_count_query_ms.'; list_query_ms='.$oi_list_perf_list_query_ms.'; item_loop_ms='.$oi_list_perf_item_loop_ms.'; auction_ms='.round($oi_list_perf_auction_ms, 2));
	header('X-List-Perf-SQL: sql_count='.$oi_list_perf_sql_delta_count.'; sql_time_ms='.$oi_list_perf_sql_delta_ms);
	echo "\n<!-- LIST_PERF total_ms={$oi_list_perf_total_ms} count_query_ms={$oi_list_perf_count_query_ms} list_query_ms={$oi_list_perf_list_query_ms} item_loop_ms={$oi_list_perf_item_loop_ms} auction_ms=".round($oi_list_perf_auction_ms, 2)." sql_count={$oi_list_perf_sql_delta_count} sql_time_ms={$oi_list_perf_sql_delta_ms} -->\n";
}

if ($oi_list_cache_enabled) {
	$oi_list_cache_html = ob_get_contents();
	if ($oi_list_cache_html !== false && $oi_list_cache_file) {
		@file_put_contents($oi_list_cache_file, $oi_list_cache_html, LOCK_EX);

		// 캐시 디렉터리 과다 누적 방지: 5% 확률로 만료 파일 정리
		if (mt_rand(1, 20) === 1) {
			$_oi_cache_files = glob($oi_list_cache_dir . '/*.html');
			if (is_array($_oi_cache_files)) {
				$_oi_max_files   = 300;  // 유지할 최대 파일 수
				$_oi_expire_secs = 600;  // 이 시간(초)보다 오래된 파일은 삭제 (TTL 45초의 13배)
				$_oi_now = time();
				// 만료된 파일 먼저 삭제
				foreach ($_oi_cache_files as $_oi_f) {
					if (($_oi_now - (int)@filemtime($_oi_f)) > $_oi_expire_secs) {
						@unlink($_oi_f);
					}
				}
				// 여전히 파일이 최대치를 넘으면 오래된 것부터 추가 삭제
				$_oi_cache_files = glob($oi_list_cache_dir . '/*.html');
				if (is_array($_oi_cache_files) && count($_oi_cache_files) > $_oi_max_files) {
					usort($_oi_cache_files, function($a, $b) { return filemtime($a) - filemtime($b); });
					$_oi_delete_count = count($_oi_cache_files) - $_oi_max_files;
					for ($__i = 0; $__i < $_oi_delete_count; $__i++) {
						@unlink($_oi_cache_files[$__i]);
					}
				}
			}
		}
	}
	ob_end_flush();
}

?>




<?php
	function auction_successful($auction) {
		global $g5, $write_table, $tender_table;
		// 나중에 등록한 게시물의 종료시간이 더 짧으면 모두 종료되는 오류 수정

		// 경매상태 조회 - 이미 종료되었으면 return
		if ($auction[status] > 1){return false;}

		// 경매가 시작전이면 return
		if ($auction[start_datetime] > G5_TIME_YMDHIS){return false;}

		// 경매날짜를 비교하여 진행중일경우 return
		if ($auction[start_datetime] < G5_TIME_YMDHIS && $auction[end_datetime] > G5_TIME_YMDHIS){return false;}

		// 최고|최저 입찰된 내역을 조회 --
		$row = sql_fetch($auction[auction_query]);

		// 입찰자수 조회 내역을 조회 --
		$off_row = sql_fetch($auction[off_row_query]);

		// 중복되었거나 입찰내역이 없을 경우, 입찰자 수가 낙찰하기 위한 입찰자 수보다 적은 경우 유찰
		if ($row[cnt] > 1 || !$row || $off_row[cnt] < $auction[auction_off_member_count]) {
			sql_query(" update $write_table set wr_8 = '3' where wr_id = '{$auction[wr_id]}' ");

			$res = sql_fetch(" select wr_7, wr_8, wr_9, wr_10, pcnum from $write_table where wr_id = '{$auction[wr_id]}' ");
			return $res;
		} else {
			// 낙찰된 입찰정보 가져오기
			$row = sql_fetch(" select * from $tender_table where td_tender_point = '{$row[point]}' and wr_id = '{$auction[wr_id]}' ");
			sql_query(" update $write_table set wr_8 = '2', wr_9 = '{$row[td_tender_point]}', wr_10 = '{$row[mb_id]}' where wr_id = '{$auction[wr_id]}' ");

			$res = sql_fetch(" select wr_7, wr_8, wr_9, wr_10, pcnum from $write_table where wr_id = '{$auction[wr_id]}' ");
			return $res;
		}
	}
?>