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

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

define("_ORDERINQUIRY_", true);

$inquiry_type = isset($_GET['inquiry_type']) ? trim((string)$_GET['inquiry_type']) : '';
$is_vpn_inquiry = ($inquiry_type === 'vpn');
$vpn_exists_condition = "exists (select 1 from {$g5['g5_shop_cart_table']} c left join {$g5['g5_shop_item_table']} it on c.it_id = it.it_id where c.od_id = {$g5['g5_shop_order_table']}.od_id and ((it.it_id is not null and LEFT(it.ca_id, 2) IN ('30', '40')) or (it.it_id is null and c.it_name like 'VPN-%')))";
$order_filter_sql = $is_vpn_inquiry
	? " and {$vpn_exists_condition} "
	: " and not {$vpn_exists_condition} ";
$item_category_filter_condition = $is_vpn_inquiry
	? "((it.it_id is not null and LEFT(it.ca_id, 2) IN ('30', '40')) or (it.it_id is null and c.it_name like 'VPN-%'))"
	: "((it.it_id is not null and LEFT(it.ca_id, 2) NOT IN ('30', '40')) or (it.it_id is null and c.it_name not like 'VPN-%'))";

if (!function_exists('oi_render_toast')) {
	function oi_render_toast($msg = '', $type = 'error')
	{
		if ($msg === '') {
			return;
		}

		$toast_msg_js = json_encode($msg, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
		$toast_type_js = json_encode($type, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
		$script = <<<EOT
<script>
(function(){
	var msg = {$toast_msg_js};
	var type = {$toast_type_js};
	if(!msg){ return; }

	if(!window.oiShowToast){
		var sid = "oi-toast-style";
		if(!document.getElementById(sid)){
			var st = document.createElement("style");
			st.id = sid;
			st.textContent = ".oi-toast{position:fixed;left:50%;top:14px;z-index:99999;max-width:min(92vw,680px);color:#fff;padding:14px 18px;border-radius:12px;box-shadow:0 12px 30px rgba(0,0,0,.28);font-size:15px;font-weight:700;line-height:1.45;opacity:0;transform:translate(-50%,-28px);transition:opacity .3s ease,transform .3s ease;pointer-events:none}.oi-toast.show{opacity:1;transform:translate(-50%,0)}.oi-toast .oi-icon{margin-right:8px;font-size:16px;vertical-align:-1px}.oi-toast--error{background:linear-gradient(135deg,#b91c1c,#7f1d1d)}.oi-toast--success{background:linear-gradient(135deg,#059669,#047857)}.oi-toast--info{background:linear-gradient(135deg,#2563eb,#1d4ed8)}";
			document.head.appendChild(st);
		}

		window.oiShowToast = function(message, toastType){
			var typeMap = {
				error: { icon: "⚠️", cls: "oi-toast--error" },
				success: { icon: "✅", cls: "oi-toast--success" },
				info: { icon: "ℹ️", cls: "oi-toast--info" }
			};
			var conf = typeMap[toastType] || typeMap.error;
			var el = document.createElement("div");
			el.className = "oi-toast " + conf.cls;
			el.setAttribute("role", "status");
			el.setAttribute("aria-live", "polite");

			var icon = document.createElement("span");
			icon.className = "oi-icon";
			icon.textContent = conf.icon;

			var txt = document.createElement("span");
			txt.textContent = String(message);

			el.appendChild(icon);
			el.appendChild(txt);
			document.body.appendChild(el);

			requestAnimationFrame(function(){ el.className += " show"; });
			setTimeout(function(){
				el.className = "oi-toast " + conf.cls;
				setTimeout(function(){ if(el.parentNode){ el.parentNode.removeChild(el); } }, 320);
			}, 3200);
		};
	}

	window.oiShowToast(msg, type);
})();
</script>
EOT;

		echo $script;
	}
}

$od_id = oi_clean_id($od_id);
$od_id_esc = oi_sql($od_id);
$od_pwd = get_encrypt_string($od_pwd);
$od_pwd_esc = oi_sql($od_pwd);
$member_mb_id_esc = '';
if ($is_member) {
	$member_mb_id_esc = sql_escape_string($member['mb_id']);
}

// 회원인 경우
if ($is_member)
{
	$sql_common = " from {$g5['g5_shop_order_table']} where mb_id = '{$member_mb_id_esc}' {$order_filter_sql} ";
}
else if ($od_id && $od_pwd) // 비회원인 경우 주문번호와 비밀번호가 넘어왔다면
{
	$sql_common = " from {$g5['g5_shop_order_table']} where od_id = '{$od_id_esc}' and od_pwd = '{$od_pwd_esc}' {$order_filter_sql} ";
}
else // 그렇지 않다면 로그인으로 가기
{
    goto_url(G5_BBS_URL.'/login.php?url='.urlencode(G5_SHOP_URL.'/orderinquiry.php'));
}

$rows = $config['cf_page_rows'];
if ($page < 1) { $page = 1; }
$orderinquiry_toast_msg = '';

if (!$is_vpn_inquiry) {
	// 테이블의 전체 레코드수만 얻음
	$sql = " select count(*) as cnt " . $sql_common;
	$row = sql_fetch($sql);
	$total_count = $row['cnt'];
	if ($total_count == 0) {
		$orderinquiry_toast_msg = '주문이 존재하지 않습니다.';
	}
	$total_page  = ceil($total_count / $rows);
	$from_record = ($page - 1) * $rows;
} else {
	// VPN: 전체 건수는 포스트필터 후 계산 (SQL LIMIT 미사용)
	$total_count = 0;
	$total_page  = 1;
	$from_record = 0;
}

// 비회원 주문확인의 경우 바로 주문서 상세조회로 이동
if (!$is_member)
{
	$sql = " select od_id, od_time, od_ip from {$g5['g5_shop_order_table']} where od_id = '{$od_id_esc}' and od_pwd = '{$od_pwd_esc}' {$order_filter_sql} ";
    $row = sql_fetch($sql);
    if ($row['od_id']) {
        $uid = md5($row['od_id'].$row['od_time'].$row['od_ip']);
        set_session('ss_orderview_uid', $uid);
		$inquiry_qs = $is_vpn_inquiry ? '&amp;inquiry_type=vpn' : '';
		goto_url(G5_SHOP_URL.'/orderinquiryview.php?od_id='.$row['od_id'].'&amp;uid='.$uid.$inquiry_qs);
    }
}

$list = array();

if ($is_member) {
	// VPN: SQL LIMIT 없이 전체 취득 후 PHP 페이지네이션
	$limit = $is_vpn_inquiry ? '' : " limit $from_record, $rows ";
	$sql = " select *
		   from {$g5['g5_shop_order_table']}
		  where mb_id = '{$member_mb_id_esc}' {$order_filter_sql}
		  order by od_time desc
		  $limit ";
	$result = sql_query($sql);
	for ($i=0; $row=sql_fetch_array($result); $i++) {
		$uid = md5($row['od_id'].$row['od_time'].$row['od_ip']);

		$sql_ct = "
			select c.it_id
			from {$g5['g5_shop_cart_table']} c
			left join {$g5['g5_shop_item_table']} it on c.it_id = it.it_id
			where c.od_id = '{$row['od_id']}'
			  and {$item_category_filter_condition}
			order by c.ct_id desc
			limit 1
		";
		$row_ct = sql_fetch($sql_ct);

		switch($row['od_status']) {
			case '주문':
				$od_status = '입금확인중';
				break;
			case '입금':
				$od_status = '입금완료';
				break;
			case '준비':
				$od_status = '상품준비중';
				break;
			case '배송':
				$od_status = '상품배송';
				break;
			case '완료':
				$od_status = '배송완료';
				break;
			default:
				$od_status = '주문취소';
				break;
		}

		$list[$i] = $row;
		$inquiry_qs = $is_vpn_inquiry ? '&amp;inquiry_type=vpn' : '';
		$list[$i]['od_href'] = G5_SHOP_URL.'/orderinquiryview.php?od_id='.$row['od_id'].'&amp;uid='.$uid.$inquiry_qs;
		$list[$i]['od_total_price'] = $row['od_cart_price'] + $row['od_send_cost'] + $row['od_send_cost2'];
		$list[$i]['od_status'] = $od_status;
		$list[$i]['it_id'] = ($is_vpn_inquiry ? "VPN-" : "RPC-").$row_ct['it_id'];
		$ext_paid_point = isset($row['od_receipt_point_for_extension_of_period']) ? (float)$row['od_receipt_point_for_extension_of_period'] : 0;
		$ext_order_count = 0;
		if ($ext_paid_point > 0) {
			// od_receipt_point_for_extension_of_period 기반 연장 건수 계산 (기존 방식)
			$od_id_for_ext = sql_escape_string((string)$row['od_id']);
			$sql_ext = " select extension_of_period_price
					from {$g5['g5_shop_cart_table']}
				   where od_id = '{$od_id_for_ext}' ";
			$result_ext = sql_query($sql_ext);
			while ($row_ext = sql_fetch_array($result_ext)) {
				$ext_price_raw = isset($row_ext['extension_of_period_price']) ? trim((string)$row_ext['extension_of_period_price']) : '';
				if ($ext_price_raw === '') {
					continue;
				}
				$ext_price_lines = preg_split('/\r\n|\r|\n/', $ext_price_raw);
				$ext_price_line_count = 0;
				for ($e=0; $e < count($ext_price_lines); $e++) {
					if (trim((string)$ext_price_lines[$e]) !== '') {
						$ext_price_line_count++;
					}
				}
				if ($ext_price_line_count > 1) {
					$ext_order_count += ($ext_price_line_count - 1);
				}
			}
			if ($ext_order_count < 1) {
				$ext_order_count = 1;
			}
		}
		// od_mod_history 파싱으로 계약연장 보완 (od_receipt_point_for_extension_of_period=0인 경우 대비)
		if ($ext_paid_point <= 0) {
			$mod_hist = isset($row['od_mod_history']) ? (string)$row['od_mod_history'] : '';
			if ($mod_hist !== '' && strpos($mod_hist, '계약연장') !== false) {
				$hist_ext_count = substr_count($mod_hist, '계약연장');
				$hist_ext_total = 0;
				preg_match_all('/계약연장[^\n]*결제\s*([\d,]+)\s*Point/u', $mod_hist, $hist_matches);
				foreach ($hist_matches[1] as $hist_m) {
					$hist_ext_total += (int)str_replace(',', '', $hist_m);
				}
				if ($hist_ext_count > 0 && $hist_ext_total > 0) {
					$ext_paid_point = $hist_ext_total;
					$ext_order_count = $hist_ext_count;
				}
			}
		}
		$list[$i]['extension_summary_text'] = ($ext_paid_point > 0)
			? ('연장주문 ' . number_format($ext_order_count) . '건 / +' . number_format($ext_paid_point) . ' Point')
			: '';
		// VPN 조회 시: 동일 it_id의 주문을 나중에 집계하기 위해 it_num 저장
		$list[$i]['_it_num_raw'] = (int)(isset($row_ct['it_id']) ? $row_ct['it_id'] : 0);
		$list[$i]['_od_receipt_point'] = isset($row['od_receipt_point']) ? (float)$row['od_receipt_point'] : 0;
	}

	// VPN 조회: 동일 VPN 상품의 중복/별도연장 주문들을 첫번째(가장 오래된) 주문에 집계
	if ($is_vpn_inquiry && count($list) > 0) {
		// list는 od_time DESC (최신→오래된) 순. 역순으로 돌면서 가장 오래된 것이 canonical
		$it_canonical_idx = array(); // it_num => canonical list index (가장 오래된)
		for ($k = count($list) - 1; $k >= 0; $k--) {
			$it_num_k = (int)$list[$k]['_it_num_raw'];
			if ($it_num_k > 0) {
				$it_canonical_idx[$it_num_k] = $k;
			}
		}
		$hide_indices = array();
		for ($k = 0; $k < count($list); $k++) {
			$it_num_k = (int)$list[$k]['_it_num_raw'];
			if ($it_num_k <= 0) continue;
			$canonical_k = isset($it_canonical_idx[$it_num_k]) ? $it_canonical_idx[$it_num_k] : $k;
			if ($k === $canonical_k) continue; // 이미 canonical
			// 이 항목은 canonical이 아님 (더 최신 순서 = 후속 중복/연장)
			$canonical_od_time = strtotime(isset($list[$canonical_k]['od_time']) ? $list[$canonical_k]['od_time'] : '');
			$this_od_time = strtotime(isset($list[$k]['od_time']) ? $list[$k]['od_time'] : '');
			$time_diff = abs($canonical_od_time - $this_od_time);
			if ($time_diff <= 300) {
				// 5분 이내 = 중복 주문 → 그냥 숨김
			} else {
				// 5분 초과 = 연장 주문 → canonical에 집계
				$add_ext_pt = $list[$k]['_od_receipt_point']
				            + (isset($list[$k]['od_receipt_point_for_extension_of_period']) ? (float)$list[$k]['od_receipt_point_for_extension_of_period'] : 0);
				if ($add_ext_pt > 0) {
					// canonical의 extension_summary_text 갱신
					$prev_text = $list[$canonical_k]['extension_summary_text'];
					if ($prev_text === '') {
						$list[$canonical_k]['extension_summary_text'] = '연장주문 1건 / +' . number_format((int)$add_ext_pt) . ' Point';
					} else {
						// 기존 텍스트에서 숫자 추출 후 합산
						$prev_count = 1;
						$prev_pt = 0;
						if (preg_match('/연장주문\s*([\d,]+)건\s*\/\s*\+([\d,]+)\s*Point/', $prev_text, $pm)) {
							$prev_count = (int)str_replace(',', '', $pm[1]);
							$prev_pt = (int)str_replace(',', '', $pm[2]);
						}
						$list[$canonical_k]['extension_summary_text'] = '연장주문 ' . number_format($prev_count + 1) . '건 / +' . number_format($prev_pt + (int)$add_ext_pt) . ' Point';
					}
				}
			}
			$hide_indices[] = $k;
		}
		// 숨길 항목 제거 (역순으로 제거해야 인덱스 안 깨짐)
		rsort($hide_indices);
		foreach ($hide_indices as $hi) {
			array_splice($list, $hi, 1);
		}
	}
	// VPN: 포스트필터 후 실제 건수로 페이지네이션 재계산
	if ($is_vpn_inquiry) {
		$total_count = count($list);
		if ($total_count == 0) {
			$orderinquiry_toast_msg = '주문이 존재하지 않습니다.';
		}
		$total_page  = max(1, (int)ceil($total_count / $rows));
		if ($page > $total_page) { $page = $total_page; }
		$from_record = ($page - 1) * $rows;
		$list = array_values(array_slice($list, $from_record, $rows));
	}
}

$write_pages = G5_IS_MOBILE ? $config['cf_mobile_pages'] : $config['cf_write_pages'];
// $qstr에 포함된 page=N 제거 후 클린 URL 구성
$_cqs = trim(preg_replace('/(&amp;|&)?page=\d*/', '', $qstr), '&;');
$_eqs = ($_cqs ? $_cqs . '&amp;' : '') . ($is_vpn_inquiry ? 'inquiry_type=vpn&amp;' : '');
$list_page = $_SERVER['SCRIPT_NAME'] . '?' . $_eqs . 'page=';

// Page ID
$pid = ($pid) ? $pid : 'inquiry';
$at = apms_page_thema($pid);
include_once(G5_LIB_PATH.'/apms.thema.lib.php');

$skin_row = array();
$skin_row = apms_rows('order_'.MOBILE_.'skin, order_'.MOBILE_.'set');
$skin_name = $skin_row['order_'.MOBILE_.'skin'];
$order_skin_path = G5_SKIN_PATH.'/apms/order/'.$skin_name;
$order_skin_url = G5_SKIN_URL.'/apms/order/'.$skin_name;

// 스킨 체크
list($order_skin_path, $order_skin_url) = apms_skin_thema('shop/order', $order_skin_path, $order_skin_url);

// 스킨설정
$wset = array();
if($skin_row['order_'.MOBILE_.'set']) {
	$wset = apms_unpack($skin_row['order_'.MOBILE_.'set']);
}

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

// 설정값 불러오기
$is_inquiry_sub = false;
@include_once($order_skin_path.'/config.skin.php');

$g5['title'] = $is_vpn_inquiry ? 'VPN 주문내역조회' : '주문내역조회';

if($is_inquiry_sub) {
	include_once(G5_PATH.'/head.sub.php');
	if(!USE_G5_THEME) @include_once(THEMA_PATH.'/head.sub.php');
} else {
	include_once('./_head.php');
}

oi_render_toast($orderinquiry_toast_msg, 'error');

$skin_path = $order_skin_path;
$skin_url = $order_skin_url;

// 셋업
$setup_href = '';
if(is_file($skin_path.'/setup.skin.php') && ($is_demo || $is_designer)) {
	$setup_href = './skin.setup.php?skin=order&amp;name='.urlencode($skin_name).'&amp;ts='.urlencode(THEMA);
}

include_once($skin_path.'/orderinquiry.skin.php');

// 취소·환불 시스템 안내
if(function_exists('vpnlink_platform_notice')) echo vpnlink_platform_notice('orderdone', array('compact' => true));

if($is_inquiry_sub) {
	if(!USE_G5_THEME) @include_once(THEMA_PATH.'/tail.sub.php');
	include_once(G5_PATH.'/tail.sub.php');
} else {
	include_once('./_tail.php');
}
?>