<?php if (!defined("_GNUBOARD_")) exit; ?>

<style>
.amgr-badge { display:inline-block; padding:2px 9px; border-radius:10px; font-size:11px; font-weight:700; white-space:nowrap; }
/* PC 스펙 칩 */
.amgr-spec-grid { display:flex; flex-wrap:wrap; gap:3px; min-width:220px; }
.amgr-spec-chip { display:inline-flex; align-items:center; gap:3px; background:#f0f4f8; border:1px solid #e2e8f0; border-radius:4px; padding:2px 5px; }
.amgr-spec-chip .sc-l { font-size:9px; font-weight:800; color:#64748b; letter-spacing:.3px; flex-shrink:0; }
.amgr-spec-chip .sc-v { font-size:11px; color:#1e293b; max-width:120px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
/* 상품종류 배지 */
.vpn-type-badge { display:inline-block; padding:2px 7px; border-radius:4px; font-size:11px; font-weight:700; white-space:nowrap; }
.vpn-type-IKEv2    { background:#dbeafe; color:#1e40af; border:1px solid #93c5fd; }
.vpn-type-PPTP     { background:#f3f4f6; color:#374151; border:1px solid #d1d5db; }
.vpn-type-OpenVPN  { background:#d1fae5; color:#065f46; border:1px solid #6ee7b7; }
.vpn-type-WireGuard{ background:#fef3c7; color:#92400e; border:1px solid #fcd34d; }
.vpn-type-L2TP     { background:#ede9fe; color:#4c1d95; border:1px solid #c4b5fd; }
.vpn-type-RPC      { background:#fee2e2; color:#991b1b; border:1px solid #fca5a5; }
/* 상품등급 배지 */
.vpn-grade-badge { display:inline-block; padding:2px 7px; border-radius:4px; font-size:11px; font-weight:700; white-space:nowrap; }
.vpn-grade-BASIC { background:#f3f4f6; color:#374151; border:1px solid #d1d5db; }
.vpn-grade-PLUS  { background:#dbeafe; color:#1e40af; border:1px solid #93c5fd; }
.vpn-grade-PRO   { background:#d1fae5; color:#065f46; border:1px solid #6ee7b7; }
.vpn-grade-ULTRA { background:#fef3c7; color:#92400e; border:1px solid #fcd34d; }
.vpn-grade-MAX   { background:#fae8ff; color:#6b21a8; border:1px solid #d8b4fe; }
.amgr-active  { background:#d4edda; color:#155724; }
.amgr-won     { background:#cce5ff; color:#004085; }
.amgr-ifee-pending { background:#fff3cd; color:#856404; }
.amgr-ifee-paid    { background:#d4edda; color:#155724; }
.amgr-ifee-cancel  { background:#f8d7da; color:#721c24; }
.amgr-ifee-waived  { background:#e2e3e5; color:#383d41; }
.amgr-failed  { background:#e2e3e5; color:#383d41; }
.amgr-pending { background:#fff3cd; color:#856404; }
.amgr-cancelled { background:#f8d7da; color:#721c24; }
.amgr-countdown { font-variant-numeric: tabular-nums; font-size:12px; color:#c0392b; font-weight:700; }
.amgr-bid-row td { font-size:12px; padding:4px 8px !important; background:#f8f9fa; }
.amgr-bid-rank1 td { font-weight:700; color:#004085; background:#e8f3ff !important; }
.amgr-toggle { cursor:pointer; }
.amgr-toggle:hover td { background:#e8f0fe !important; }
.amgr-filter-bar { margin-bottom:16px; }
.amgr-filter-bar .btn { margin-right:4px; margin-bottom:4px; }
.amgr-actions .btn { padding:2px 7px; font-size:11px; margin:1px; }
.amgr-toast { position:fixed; bottom:24px; right:24px; z-index:9999; min-width:280px; }
</style>

<style>
/* ── auction_mgr 다크모드 ── */
[data-site-theme="dark"] h1 { color:#d4d4d8; }

/* 안내 박스 */
[data-site-theme="dark"] .alert-info {
    background-color: #1a2a3e !important;
    border-color: #2a4a6a !important;
    color: #93c5fd !important;
}
[data-site-theme="dark"] .alert-info a { color: #bfdbfe !important; }

/* 필터 버튼 */
[data-site-theme="dark"] .amgr-filter-bar .btn-default {
    background: #2c2c32 !important;
    border-color: #4a4a52 !important;
    color: #c4c4cc !important;
}
[data-site-theme="dark"] .amgr-filter-bar .btn-default:hover {
    background: #3a3a42 !important;
}
[data-site-theme="dark"] .amgr-filter-bar .btn-default.active {
    background: #4a3a20 !important;
    border-color: #c08040 !important;
    color: #fde68a !important;
    box-shadow: inset 0 2px 4px rgba(0,0,0,.4) !important;
}
[data-site-theme="dark"] .amgr-filter-bar .btn-success {
    background: #166534 !important;
    border-color: #15803d !important;
    color: #ffffff !important;
}
[data-site-theme="dark"] .amgr-filter-bar .btn-primary {
    background: #1e3a8a !important;
    border-color: #1d4ed8 !important;
    color: #ffffff !important;
}
[data-site-theme="dark"] .amgr-filter-bar .btn-warning {
    background: #854d0e !important;
    border-color: #a16207 !important;
    color: #ffffff !important;
}
[data-site-theme="dark"] .amgr-filter-bar .badge {
    background: #4a4a52 !important;
    color: #d4d4d8 !important;
}

/* 메인 테이블 */
[data-site-theme="dark"] .table-responsive { background: transparent !important; }
[data-site-theme="dark"] table.table-bordered,
[data-site-theme="dark"] table.table-bordered.table-hover {
    background: #1e2028 !important;
    border-color: #3a3a42 !important;
    color: #c4c4cc !important;
}
[data-site-theme="dark"] .table-bordered th,
[data-site-theme="dark"] .table-bordered td {
    border-color: #3a3a42 !important;
    color: #c4c4cc !important;
}
[data-site-theme="dark"] .table-bordered thead tr,
[data-site-theme="dark"] .table-bordered thead tr.active,
[data-site-theme="dark"] .table-bordered tr.active {
    background: #252530 !important;
    color: #d4d4d8 !important;
}
[data-site-theme="dark"] .table-bordered thead th {
    background: #252530 !important;
    color: #d4d4d8 !important;
    border-color: #3a3a42 !important;
}
[data-site-theme="dark"] .table-hover tbody tr:hover td {
    background: #252530 !important;
}

/* 행 토글 hover */
[data-site-theme="dark"] .amgr-toggle:hover td {
    background: #252530 !important;
}

/* 입찰자 펼침 영역 */
[data-site-theme="dark"] .amgr-bid-row td {
    background: #1a1c24 !important;
    color: #9ca3af !important;
    border-color: #2a2a32 !important;
}
[data-site-theme="dark"] .amgr-bid-rank1 td {
    background: #1a2a3e !important;
    color: #93c5fd !important;
    border-color: #2a3a5a !important;
}
[data-site-theme="dark"] tr[id^="amgr-bids-"] > td > table {
    background: #1a1c24 !important;
}
[data-site-theme="dark"] tr[id^="amgr-bids-"] thead tr {
    background: #252530 !important;
}
[data-site-theme="dark"] tr[id^="amgr-bids-"] th {
    background: #252530 !important;
    color: #9ca3af !important;
    border-color: #3a3a42 !important;
}

/* PC 스펙 칩 다크모드 */
[data-site-theme="dark"] .amgr-spec-chip { background:#252530; border-color:#3a3a42; }
[data-site-theme="dark"] .amgr-spec-chip .sc-l { color:#71717a; }
[data-site-theme="dark"] .amgr-spec-chip .sc-v { color:#d4d4d8; }
/* 상품종류/등급 배지 다크모드 */
[data-site-theme="dark"] .vpn-type-IKEv2    { background:#1e3a5f; color:#93c5fd; border-color:#3b6ea8; }
[data-site-theme="dark"] .vpn-type-PPTP     { background:#2c2c32; color:#9ca3af; border-color:#4a4a52; }
[data-site-theme="dark"] .vpn-type-OpenVPN  { background:#0d2818; color:#86efac; border-color:#166534; }
[data-site-theme="dark"] .vpn-type-WireGuard{ background:#2a2210; color:#fde68a; border-color:#854d0e; }
[data-site-theme="dark"] .vpn-type-L2TP     { background:#2a1a4a; color:#c4b5fd; border-color:#6d28d9; }
[data-site-theme="dark"] .vpn-type-RPC      { background:#2a1a1a; color:#fca5a5; border-color:#991b1b; }
[data-site-theme="dark"] .vpn-grade-BASIC   { background:#2c2c32; color:#9ca3af; border-color:#4a4a52; }
[data-site-theme="dark"] .vpn-grade-PLUS    { background:#1e3a5f; color:#93c5fd; border-color:#3b6ea8; }
[data-site-theme="dark"] .vpn-grade-PRO     { background:#0d2818; color:#86efac; border-color:#166534; }
[data-site-theme="dark"] .vpn-grade-ULTRA   { background:#2a2210; color:#fde68a; border-color:#854d0e; }
[data-site-theme="dark"] .vpn-grade-MAX     { background:#2a1040; color:#d8b4fe; border-color:#6b21a8; }

/* 상태 배지 (다크 적용) */
[data-site-theme="dark"] .amgr-active   { background:#0d2818 !important; color:#86efac !important; }
[data-site-theme="dark"] .amgr-won      { background:#1a2a3e !important; color:#93c5fd !important; }
[data-site-theme="dark"] .amgr-failed   { background:#2c2c32 !important; color:#9ca3af !important; }
[data-site-theme="dark"] .amgr-pending  { background:#2a2210 !important; color:#fde68a !important; }
[data-site-theme="dark"] .amgr-cancelled{ background:#2a1a1a !important; color:#fca5a5 !important; }
[data-site-theme="dark"] .amgr-ifee-pending { background:#2a2210 !important; color:#fde68a !important; }
[data-site-theme="dark"] .amgr-ifee-paid    { background:#0d2818 !important; color:#86efac !important; }
[data-site-theme="dark"] .amgr-ifee-cancel  { background:#2a1a1a !important; color:#fca5a5 !important; }
[data-site-theme="dark"] .amgr-ifee-waived  { background:#2c2c32 !important; color:#9ca3af !important; }

/* Bootstrap label 배지 */
[data-site-theme="dark"] .label-primary { background:#1a2a3e !important; color:#93c5fd !important; }
[data-site-theme="dark"] .label-default { background:#2c2c32 !important; color:#9ca3af !important; }
[data-site-theme="dark"] .label-success { background:#0d2818 !important; color:#86efac !important; }

/* 카운트다운 */
[data-site-theme="dark"] .amgr-countdown { color:#fca5a5 !important; }

/* 인라인 color:#999, color:#ccc */
[data-site-theme="dark"] [style*="color:#999"],
[data-site-theme="dark"] [style*="color: #999"],
[data-site-theme="dark"] [style*="color:#ccc"],
[data-site-theme="dark"] [style*="color: #ccc"],
[data-site-theme="dark"] [style*="color:#666"],
[data-site-theme="dark"] [style*="color: #666"] {
    color: #71717a !important;
}
[data-site-theme="dark"] [style*="color:#856404"],
[data-site-theme="dark"] [style*="color: #856404"] { color:#fde68a !important; }

/* 페이지네이션 */
[data-site-theme="dark"] .pagination > li > a,
[data-site-theme="dark"] .pagination > li > span {
    background: #1e2028 !important;
    border-color: #3a3a42 !important;
    color: #93c5fd !important;
}
[data-site-theme="dark"] .pagination > .active > a,
[data-site-theme="dark"] .pagination > .active > span {
    background: #1a2a3e !important;
    border-color: #3a5a8a !important;
    color: #bfdbfe !important;
}

/* 모달 */
[data-site-theme="dark"] .modal-content {
    background: #1e2028 !important;
    border-color: #3a3a42 !important;
    color: #d4d4d8 !important;
}
[data-site-theme="dark"] .modal-header {
    background: #252530 !important;
    border-bottom-color: #3a3a42 !important;
    color: #d4d4d8 !important;
}
[data-site-theme="dark"] .modal-title { color: #d4d4d8 !important; }
[data-site-theme="dark"] .modal-footer {
    background: #252530 !important;
    border-top-color: #3a3a42 !important;
}
[data-site-theme="dark"] .modal-header[style*="#f8d7da"] {
    background: #2a1a1a !important;
    border-bottom-color: #7a3030 !important;
}
[data-site-theme="dark"] .modal-title[style*="#721c24"] { color: #fca5a5 !important; }
[data-site-theme="dark"] .modal-body { background: #1e2028 !important; color: #c4c4cc !important; }
[data-site-theme="dark"] .modal-body p { color: #c4c4cc !important; }
[data-site-theme="dark"] .modal-body .form-control {
    background: #252530 !important;
    border-color: #3a3a42 !important;
    color: #d4d4d8 !important;
}
[data-site-theme="dark"] .modal-body .help-block { color: #71717a !important; }
[data-site-theme="dark"] .modal .close { color: #9ca3af !important; opacity: 1; }
[data-site-theme="dark"] .modal .btn-default {
    background: #2c2c32 !important;
    border-color: #4a4a52 !important;
    color: #c4c4cc !important;
}
[data-site-theme="dark"] .modal .btn-default:hover {
    background: #3a3a42 !important;
    border-color: #5a5a62 !important;
}
[data-site-theme="dark"] .modal-body .radio-inline { color: #c4c4cc !important; }
[data-site-theme="dark"] #ext-current-end { color: #fde68a !important; }

/* 토스트 */
[data-site-theme="dark"] .alert-success {
    background: #0d2818 !important;
    border-color: #276749 !important;
    color: #86efac !important;
}
[data-site-theme="dark"] .alert-danger {
    background: #2a1a1a !important;
    border-color: #7a3030 !important;
    color: #fca5a5 !important;
}
</style>

<h1><i class="fa fa-gavel"></i> 내상품(경매)현황 (RPC)</h1>

<div class="alert alert-info" style="padding:10px 14px; font-size:12px; margin-bottom:12px; line-height:1.7;">
  <i class="fa fa-info-circle"></i>
  <strong>이 페이지는 내가 판매자로 경매에 올린 RPC 목록</strong>과, 각 경매에 다른 회원(본인 포함)이 입찰한 현황을 확인·관리하는 <strong>셀러 전용</strong> 페이지입니다.<br>
  내가 <em>입찰자</em>로서 다른 판매자의 경매에 응찰한 내역은
  <a href="<?php echo G5_SHOP_URL; ?>/orderinquiry4auction.php" style="font-weight:700;">마이페이지 &gt; 입찰 내역 더보기</a>에서 확인할 수 있습니다.
</div>

<div class="amgr-filter-bar">
	<a href="<?php echo APMS_PARTNER_URL; ?>/?ap=auction_mgr"
	   class="btn btn-sm <?php echo $filter === '' ? 'btn-primary' : 'btn-default'; ?>">
		전체 <span class="badge"><?php echo number_format($total_count); ?></span>
	</a>
	<a href="<?php echo APMS_PARTNER_URL; ?>/?ap=auction_mgr&filter=active"
	   class="btn btn-sm <?php echo $filter === 'active' ? 'btn-success' : 'btn-default'; ?>">
		<i class="fa fa-play-circle"></i> 진행중
	</a>
	<a href="<?php echo APMS_PARTNER_URL; ?>/?ap=auction_mgr&filter=won"
	   class="btn btn-sm <?php echo $filter === 'won' ? 'btn-primary' : 'btn-default'; ?>">
		<i class="fa fa-trophy"></i> 낙찰
	</a>
	<a href="<?php echo APMS_PARTNER_URL; ?>/?ap=auction_mgr&filter=failed"
	   class="btn btn-sm <?php echo $filter === 'failed' ? 'btn-default active' : 'btn-default'; ?>">
		<i class="fa fa-times-circle"></i> 유찰
	</a>
	<a href="<?php echo APMS_PARTNER_URL; ?>/?ap=auction_mgr&filter=pending"
	   class="btn btn-sm <?php echo $filter === 'pending' ? 'btn-warning' : 'btn-default'; ?>">
		<i class="fa fa-clock-o"></i> 미경매
	</a>
</div>

<div class="table-responsive">
<table class="table table-bordered table-hover" style="font-size:12px; background:#fff;">
<thead>
<tr class="active">
	<th class="text-center" style="width:30px">#</th>
	<th class="text-center" style="width:82px">적용메뉴</th>
	<th class="text-center" style="width:72px">관리컴퓨터별명</th>
	<th class="text-left">상품명</th>
	<th class="text-center" style="width:56px">등급</th>
	<th class="text-left" style="min-width:220px">PC 스펙</th>
	<th class="text-center" style="width:76px">KBD/MOUSE</th>
	<th class="text-center" style="width:98px">원격접속IP</th>
	<th class="text-center" style="width:80px">원격제어S/W</th>
	<th class="text-center" style="width:50px">APP설치</th>
	<th class="text-center" style="width:66px">낙찰방식</th>
	<th class="text-right" style="width:74px">시작가</th>
	<th class="text-center" style="width:104px">종료일시</th>
	<th class="text-center" style="width:80px">남은 시간</th>
	<th class="text-center" style="width:34px">입찰</th>
	<th class="text-right" style="width:78px">최고 입찰가</th>
	<th class="text-center" style="width:74px">낙찰자</th>
	<th class="text-center" style="width:62px">상태</th>
	<th class="text-center" style="width:114px">액션</th>
</tr>
</thead>
<tbody>
<?php if (empty($list)) : ?>
<tr><td colspan="19" class="text-center" style="padding:30px;">등록된 경매 항목이 없습니다.</td></tr>
<?php else : ?>
<?php foreach ($list as $idx => $row) :
	$cls_map = array('active'=>'amgr-active','won'=>'amgr-won','failed'=>'amgr-failed','pending'=>'amgr-pending');
	$badge_cls = isset($cls_map[$row['status']]) ? $cls_map[$row['status']] : 'amgr-pending';
	$has_bids  = count($row['bids']) > 0;
	$row_id    = 'amgr-bids-' . $row['wr_id_off'];
	$end_fmt   = $row['end_ts'] > 0 ? date('y-m-d H:i', $row['end_ts']) : '-';
	$sub_arr   = explode('|', (string)$row['wr_subject']);
	$spec_full = isset($sub_arr[1]) ? trim($sub_arr[1]) : '';
	$pcnum_disp = htmlspecialchars($row['pcnum_disp']);
?>
<tr class="amgr-toggle" onclick="amgrToggle('<?php echo $row_id; ?>')"
    title="<?php echo $has_bids ? '클릭: 입찰자 목록 펼치기' : ''; ?>">
	<td class="text-center"><?php echo $row['wr_id_off']; ?></td>
	<td class="text-center" style="font-size:11px; line-height:1.3;">원격제어컴퓨터<br>(경매)</td>
	<td class="text-center"><?php echo htmlspecialchars($row['it_spec_mgr_nickname'] ?? ''); ?></td>
	<td>
		<?php if ($row['auction_board_href']) : ?>
			<a href="<?php echo $row['auction_board_href']; ?>" onclick="event.stopPropagation()" target="_blank">
				<b><?php echo htmlspecialchars(!empty($row['it_name']) ? $row['it_name'] : $pcnum_disp); ?></b>
			</a>
		<?php else : ?>
			<b><?php echo htmlspecialchars(!empty($row['it_name']) ? $row['it_name'] : $pcnum_disp); ?></b>
		<?php endif; ?>
		<div style="font-size:11px; color:#9ca3af; margin-top:2px;"><?php echo $pcnum_disp; ?></div>
	</td>
	<td class="text-center"> <!-- 등급 -->
		<?php
		$grade = $row['it_spec_grade'];
		if ($grade) {
			$safe = htmlspecialchars($grade);
			echo '<span class="vpn-grade-badge vpn-grade-'.$safe.'">'.$safe.'</span>';
		} else {
			echo '<span style="color:#9ca3af;">-</span>';
		}
		?>
	</td>
	<td class="text-left"> <!-- PC 스펙 -->
		<?php
		$_os  = trim($row['it_spec_os'] ?? '');
		$_cpu = trim($row['it_spec_cpu'] ?? '');
		$_ram = trim(($row['it_spec_ram_type'] ?? '') . ' ' . ($row['it_spec_ram'] ?? ''));
		$_gpu = trim($row['it_spec_gpu'] ?? '');
		$_ssd = trim(($row['it_spec_ssd_type'] ?? '') . ' ' . ($row['it_spec_ssd'] ?? ''));
		$_hdd = trim(($row['it_spec_hdd_type'] ?? '') . ' ' . ($row['it_spec_hdd'] ?? ''));
		if ($_cpu) {
			if (preg_match('/(i[3579]-[\w]+)/i', $_cpu, $_m)) $_cpu_s = $_m[1];
			elseif (preg_match('/(Ryzen\s+[39]\s+[\w]+)/i', $_cpu, $_m)) $_cpu_s = str_replace('Ryzen ', 'R', $_m[1]);
			elseif (strlen($_cpu) > 18) $_cpu_s = substr($_cpu, 0, 16) . '…';
			else $_cpu_s = $_cpu;
		} else { $_cpu_s = ''; }
		if ($_gpu) {
			if (preg_match('/(RTX\s*[\d]+(?:\s*[\w]+)?|GTX\s*[\d]+(?:\s*[\w]+)?|RX\s*[\d]+(?:\s*[\w]+)?)/i', $_gpu, $_m)) $_gpu_s = trim($_m[1]);
			elseif (strlen($_gpu) > 16) $_gpu_s = substr($_gpu, 0, 14) . '…';
			else $_gpu_s = $_gpu;
		} else { $_gpu_s = ''; }
		if ($_os) {
			$_os_s = str_replace(['Windows ', 'Enterprise', 'Professional'], ['Win', 'Ent', 'Pro'], $_os);
			if (strlen($_os_s) > 13) $_os_s = substr($_os_s, 0, 11) . '…';
		} else { $_os_s = ''; }
		$_achips = [];
		if ($_os_s)  $_achips[] = ['OS',  $_os_s,  $_os];
		if ($_cpu_s) $_achips[] = ['CPU', $_cpu_s, $_cpu];
		if ($_ram)   $_achips[] = ['RAM', $_ram,   $_ram];
		if ($_gpu_s) $_achips[] = ['GPU', $_gpu_s, $_gpu];
		if ($_ssd)   $_achips[] = ['SSD', $_ssd,   $_ssd];
		if ($_hdd)   $_achips[] = ['HDD', $_hdd,   $_hdd];
		if ($_achips) {
			echo '<div class="amgr-spec-grid">';
			foreach ($_achips as $_c) {
				echo '<span class="amgr-spec-chip">'
				   . '<span class="sc-l">'.htmlspecialchars($_c[0]).'</span>'
				   . '<span class="sc-v" title="'.htmlspecialchars($_c[2]).'">'.htmlspecialchars($_c[1]).'</span>'
				   . '</span>';
			}
			echo '</div>';
		} else {
			echo '<span style="color:#9ca3af;">-</span>';
		}
		?>
	</td>
	<td class="text-center"> <!-- KBD/MOUSE -->
		<?php
		$_kbd   = $row['it_spec_keyboard'] ?: '-';
		$_mouse = $row['it_spec_mouse'] ?: '-';
		echo htmlspecialchars($_kbd) . ' / ' . htmlspecialchars($_mouse);
		?>
	</td>
	<td class="text-center"> <!-- 원격접속IP -->
		<?php
		$_remote_ip_disp = '';
		$_remote_sw_disp = '';
		$_json_rsw = json_decode($row['it_spec_remote_sw'] ?? '', true);
		if (is_array($_json_rsw)) {
			foreach ($_json_rsw as $_ri => $_rd) {
				$_rip = $_rd["RemoteIP__{$_ri}"] ?? '';
				$_rpn = $_rd["Program__{$_ri}"] ?? '';
				if ($_rip) { $_remote_ip_disp = $_rip; $_remote_sw_disp = $_rpn; }
			}
		}
		echo htmlspecialchars($_remote_ip_disp ?: '-');
		?>
	</td>
	<td class="text-left"> <!-- 원격제어S/W -->
		<?php echo htmlspecialchars($_remote_sw_disp ?: '-'); ?>
	</td>
	<td class="text-center"> <!-- APP설치 -->
		<?php echo htmlspecialchars($row['it_spec_app_ver'] ?? ''); ?>
	</td>
	<td class="text-center"><?php echo htmlspecialchars($row['auction_method']); ?></td>
	<td class="text-right"><?php echo display_point($row['start_point']); ?></td>
	<td class="text-center"><?php echo $end_fmt; ?></td>
	<td class="text-center">
		<?php if ($row['status'] === 'active' && $row['remaining_sec'] > 0) : ?>
			<span class="amgr-countdown" data-end="<?php echo $row['end_ts']; ?>"><?php
				$d = floor($row['remaining_sec'] / 86400);
				$h = floor(($row['remaining_sec'] % 86400) / 3600);
				$m = floor(($row['remaining_sec'] % 3600) / 60);
				$s = $row['remaining_sec'] % 60;
				echo ($d > 0 ? $d.'일 ' : '') . sprintf('%02d:%02d:%02d', $h, $m, $s);
			?></span>
		<?php else : ?>
			<span style="color:#999">-</span>
		<?php endif; ?>
	</td>
	<td class="text-center">
		<?php if ($has_bids) : ?>
			<strong><?php echo (int)$row['bid_count']; ?></strong>
			<i class="fa fa-angle-down" style="margin-left:3px; color:#666;"></i>
		<?php else : ?>0<?php endif; ?>
	</td>
	<td class="text-right"><?php echo ($row['highest_bid'] > 0) ? display_point($row['highest_bid']) : '-'; ?></td>
	<td class="text-center"><?php echo ($row['winner_mb_id'] !== '') ? htmlspecialchars($row['winner_mb_id']) : '-'; ?></td>
	<td class="text-center"><span class="amgr-badge <?php echo $badge_cls; ?>"><?php echo $row['status_text']; ?></span></td>
	<td class="text-center amgr-actions" onclick="event.stopPropagation()">
		<?php if ($row['status'] === 'active') : ?>
			<button type="button" class="btn btn-xs btn-info"
				onclick="amgrExtend(<?php echo $row['wr_id_off']; ?>, '<?php echo addslashes($end_fmt); ?>')">
				<i class="fa fa-clock-o"></i> 연장
			</button>
			<?php if (!$has_bids) : ?>
			<button type="button" class="btn btn-xs btn-danger"
				onclick="amgrCancel(<?php echo $row['wr_id_off']; ?>, 0)">
				<i class="fa fa-ban"></i> 취소
			</button>
			<?php else : ?>
			<button type="button" class="btn btn-xs btn-warning"
				onclick="amgrCancel(<?php echo $row['wr_id_off']; ?>, <?php echo (int)$row['bid_count']; ?>)">
				<i class="fa fa-ban"></i> 취소
			</button>
			<?php endif; ?>
		<?php elseif ($row['status'] === 'pending') : ?>
			<button type="button" class="btn btn-xs btn-danger"
				onclick="amgrCancel(<?php echo $row['wr_id_off']; ?>, 0)">
				<i class="fa fa-ban"></i> 취소
			</button>
		<?php elseif ($row['status'] === 'won') : ?>
			<?php
			$_ifs = (int)$row['install_fee_status'];
			$_ifl = (int)$row['install_fee'];
			$_ifd = $row['install_fee_deadline'];
			$_ifee_label = array(0=>'미확인',1=>'납부대기',2=>'납부완료',3=>'미납취소',9=>'면제');
			$_ifee_cls   = array(0=>'',1=>'amgr-ifee-pending',2=>'amgr-ifee-paid',3=>'amgr-ifee-cancel',9=>'amgr-ifee-waived');
			?>
			<?php if ($_ifl > 0) : ?>
			<div style="margin-bottom:4px;font-size:11px;">
				개통비 <strong><?php echo number_format($_ifl); ?>P</strong>
				<span class="label <?php echo $_ifee_cls[$_ifs] ?? ''; ?>" style="margin-left:4px;"><?php echo $_ifee_label[$_ifs] ?? '-'; ?></span>
				<?php if ($_ifs === 1 && $_ifd) : ?><small style="color:#856404"> (~<?php echo substr($_ifd,0,10); ?>)</small><?php endif; ?>
			</div>
			<?php if ($_ifs === 1) : ?>
			<button type="button" class="btn btn-xs btn-success" style="margin-bottom:2px;"
				onclick="amgrInstallFee(<?php echo $row['wr_id_off']; ?>,'confirm')">
				<i class="fa fa-check"></i> 납부확인
			</button>
			<button type="button" class="btn btn-xs btn-default" style="margin-bottom:2px;"
				onclick="amgrInstallFee(<?php echo $row['wr_id_off']; ?>,'waive')">
				<i class="fa fa-times-circle"></i> 면제
			</button>
			<button type="button" class="btn btn-xs btn-danger" style="margin-bottom:2px;"
				onclick="amgrInstallFee(<?php echo $row['wr_id_off']; ?>,'cancel')">
				<i class="fa fa-ban"></i> 미납취소
			</button>
			<?php endif; ?>
			<?php endif; ?>
			<button type="button" class="btn btn-xs btn-primary"
				onclick="amgrMemo(<?php echo $row['wr_id_off']; ?>, 'winner', '<?php echo addslashes($row['winner_mb_id']); ?>', '<?php echo addslashes($pcnum_disp); ?>', '<?php echo addslashes($spec_full); ?>')">
				<i class="fa fa-envelope"></i> 낙찰자 쪽지
			</button>
			<?php if ($has_bids) : ?>
			<button type="button" class="btn btn-xs btn-default"
				onclick="amgrMemo(<?php echo $row['wr_id_off']; ?>, 'all', '', '<?php echo addslashes($pcnum_disp); ?>', '<?php echo addslashes($spec_full); ?>')">
				<i class="fa fa-users"></i> 전체 쪽지
			</button>
			<?php endif; ?>
		<?php elseif ($row['status'] === 'failed' && $has_bids) : ?>
			<button type="button" class="btn btn-xs btn-default"
				onclick="amgrMemo(<?php echo $row['wr_id_off']; ?>, 'all', '', '<?php echo addslashes($pcnum_disp); ?>', '<?php echo addslashes($spec_full); ?>')">
				<i class="fa fa-users"></i> 입찰자 쪽지
			</button>
		<?php else : ?>
			<span style="color:#ccc; font-size:11px">-</span>
		<?php endif; ?>
	</td>
</tr>
<?php if ($has_bids) : ?>
<tr id="<?php echo $row_id; ?>" style="display:none;">
	<td colspan="19" style="padding:0 !important; border-top:none;">
		<table class="table table-condensed" style="margin:0; font-size:11px; background:#f8f9fa;">
		<thead>
			<tr style="background:#e9ecef;">
				<th class="text-center" style="width:40px">순위</th>
				<th class="text-center">입찰자 ID</th>
				<th class="text-center">닉네임</th>
				<th class="text-right">입찰금액</th>
				<th class="text-center">입찰일시</th>
				<th class="text-center">결과</th>
			</tr>
		</thead>
		<tbody>
		<?php foreach ($row['bids'] as $bi => $bid) :
			$bid_status_map = array('0'=>'대기','1'=>'진행중','2'=>'낙찰','3'=>'유찰');
			$bid_status_text = isset($bid_status_map[$bid['td_status']]) ? $bid_status_map[$bid['td_status']] : '-';
			$is_winner = ($bid['td_status'] === '2' || ($row['winner_mb_id'] !== '' && $bid['mb_id'] === $row['winner_mb_id']));
		?>
		<tr class="amgr-bid-row <?php echo ($bi === 0) ? 'amgr-bid-rank1' : ''; ?>">
			<td class="text-center"><?php echo $bi + 1; ?></td>
			<td class="text-center"><?php echo htmlspecialchars($bid['mb_id']); ?></td>
			<td class="text-center"><?php echo htmlspecialchars($bid['mb_nick'] ?? '-'); ?></td>
			<td class="text-right" style="font-weight:700"><?php echo display_point($bid['td_tender_point']); ?></td>
			<td class="text-center"><?php echo substr($bid['td_datetime'], 2, 14); ?></td>
			<td class="text-center">
				<?php if ($is_winner) : ?>
					<span class="label label-primary">낙찰</span>
				<?php elseif ($bid['td_status'] === '3') : ?>
					<span class="label label-default">유찰</span>
				<?php elseif ($bid['td_status'] === '1') : ?>
					<span class="label label-success">진행중</span>
				<?php else : ?>
					<span class="label label-default"><?php echo $bid_status_text; ?></span>
				<?php endif; ?>
			</td>
		</tr>
		<?php endforeach; ?>
		</tbody>
		</table>
	</td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>

<div class="text-center">
	<ul class="pagination pagination-sm en">
		<?php echo apms_paging($write_pages, $page, $total_page, $list_page); ?>
	</ul>
</div>

<!-- 기간 연장 모달 -->
<div class="modal fade" id="modal-extend" tabindex="-1">
	<div class="modal-dialog modal-sm">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal">&times;</button>
				<h4 class="modal-title"><i class="fa fa-clock-o"></i> 경매 기간 연장</h4>
			</div>
			<div class="modal-body">
				<p style="font-size:12px; color:#666;">현재 종료일: <strong id="ext-current-end"></strong></p>
				<div class="form-group">
					<label style="font-size:13px;">연장 기간 선택</label>
					<div>
						<label class="radio-inline"><input type="radio" name="ext-days" value="1"> +1일</label>
						<label class="radio-inline"><input type="radio" name="ext-days" value="3" checked> +3일</label>
						<label class="radio-inline"><input type="radio" name="ext-days" value="7"> +7일</label>
						<label class="radio-inline"><input type="radio" name="ext-days" value="0"> 직접입력</label>
					</div>
				</div>
				<div class="form-group" id="ext-custom-wrap" style="display:none;">
					<label style="font-size:12px;">종료 일시</label>
					<input type="datetime-local" id="ext-custom-end" class="form-control input-sm">
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default btn-sm" data-dismiss="modal">취소</button>
				<button type="button" class="btn btn-info btn-sm" id="btn-extend-ok">
					<i class="fa fa-check"></i> 연장 확인
				</button>
			</div>
		</div>
	</div>
</div>

<!-- 경매 취소 모달 -->
<div class="modal fade" id="modal-cancel" tabindex="-1">
	<div class="modal-dialog modal-sm">
		<div class="modal-content">
			<div class="modal-header" style="background:#f8d7da;">
				<button type="button" class="close" data-dismiss="modal">&times;</button>
				<h4 class="modal-title" style="color:#721c24;"><i class="fa fa-ban"></i> 경매 취소</h4>
			</div>
			<div class="modal-body">
				<p>이 경매를 취소하시겠습니까?<br>취소 후에는 되돌릴 수 없습니다.</p>
				<div id="cancel-notify-wrap" class="form-group" style="display:none;">
					<label>
						<input type="checkbox" id="cancel-notify" checked>
						<span style="font-size:12px; color:#c0392b;">입찰자에게 취소 쪽지 발송</span>
					</label>
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default btn-sm" data-dismiss="modal">닫기</button>
				<button type="button" class="btn btn-danger btn-sm" id="btn-cancel-ok">
					<i class="fa fa-ban"></i> 취소 확정
				</button>
			</div>
		</div>
	</div>
</div>

<!-- 쪽지 발송 모달 -->
<div class="modal fade" id="modal-memo" tabindex="-1">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal">&times;</button>
				<h4 class="modal-title"><i class="fa fa-envelope"></i> 쪽지 발송</h4>
			</div>
			<div class="modal-body">
				<p class="text-muted" style="font-size:12px;" id="memo-target-desc"></p>
				<div class="form-group">
					<label style="font-size:12px;">메시지</label>
					<textarea id="memo-message" class="form-control" rows="8" style="font-size:12px; resize:vertical;"></textarea>
					<span class="help-block" style="font-size:11px;"><span id="memo-char-count">0</span> / 2000자</span>
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-default btn-sm" data-dismiss="modal">취소</button>
				<button type="button" class="btn btn-primary btn-sm" id="btn-memo-ok">
					<i class="fa fa-paper-plane"></i> 발송
				</button>
			</div>
		</div>
	</div>
</div>

<!-- 토스트 알림 -->
<div id="amgr-toast" class="amgr-toast" style="display:none;"></div>

<script>
var AMGR_AJAX_URL = '<?php echo APMS_PARTNER_URL; ?>/ajax.auction_mgr.php';
var _amgrWrIdOff = 0;

// ── 토스트 ──────────────────────────────────────────────────────────────────
function amgrToast(msg, type) {
	var cls = type === 'error' ? 'alert-danger' : 'alert-success';
	var el = document.getElementById('amgr-toast');
	el.innerHTML = '<div class="alert ' + cls + ' alert-dismissible" role="alert" style="margin:0;box-shadow:0 2px 8px rgba(0,0,0,.2)">' +
		'<button type="button" class="close" onclick="this.parentNode.parentNode.style.display=\'none\'">&times;</button>' + msg + '</div>';
	el.style.display = 'block';
	setTimeout(function(){ el.style.display = 'none'; }, 4000);
}

// ── 기간 연장 ───────────────────────────────────────────────────────────────
function amgrExtend(wr_id_off, currentEnd) {
	_amgrWrIdOff = wr_id_off;
	document.getElementById('ext-current-end').textContent = currentEnd;
	$('input[name="ext-days"][value="3"]').prop('checked', true);
	$('#ext-custom-wrap').hide();
	$('#modal-extend').modal('show');
}
$('input[name="ext-days"]').on('change', function() {
	$('#ext-custom-wrap').toggle(this.value === '0');
});
$('#btn-extend-ok').on('click', function() {
	var days = parseInt($('input[name="ext-days"]:checked').val(), 10);
	var data = { action: 'extend', wr_id_off: _amgrWrIdOff };
	if (days > 0) { data.days = days; }
	else { data.custom_end = $('#ext-custom-end').val().replace('T', ' ') + ':00'; }
	amgrPost(data, function(res) {
		$('#modal-extend').modal('hide');
		amgrToast(res.message);
		if (res.success) setTimeout(function(){ location.reload(); }, 1200);
	});
});

// ── 경매 취소 ───────────────────────────────────────────────────────────────
function amgrInstallFee(wrIdOff, action) {
    var labels = { confirm: '납부 확인 처리하시겠습니까?', waive: '개통비를 면제 처리하시겠습니까?', cancel: '미납으로 낙찰을 취소하시겠습니까?\n\n낙찰자에게 취소 쪽지가 발송됩니다.' };
    if (!confirm(labels[action] || '처리하시겠습니까?')) return;
    $.post('<?php echo APMS_PARTNER_URL; ?>/?ap=ajax_auction_mgr', { action: 'install_fee_' + action, wr_id_off: wrIdOff })
     .done(function(r) {
         if (r.success) { alert(r.message); location.reload(); }
         else alert('오류: ' + r.message);
     }).fail(function() { alert('요청 실패'); });
}

function amgrCancel(wr_id_off, bidCount) {
	_amgrWrIdOff = wr_id_off;
	$('#cancel-notify-wrap').toggle(bidCount > 0);
	$('#cancel-notify').prop('checked', bidCount > 0);
	$('#modal-cancel').modal('show');
}
$('#btn-cancel-ok').on('click', function() {
	var notify = $('#cancel-notify').is(':checked') ? '1' : '0';
	amgrPost({ action: 'cancel', wr_id_off: _amgrWrIdOff, notify: notify }, function(res) {
		$('#modal-cancel').modal('hide');
		amgrToast(res.message, res.success ? '' : 'error');
		if (res.success) setTimeout(function(){ location.reload(); }, 1200);
	});
});

// ── 쪽지 발송 ───────────────────────────────────────────────────────────────
function amgrMemo(wr_id_off, target, winnerMbId, pcnum, spec) {
	_amgrWrIdOff = wr_id_off;
	$('#modal-memo').data('target', target);
	var desc, template;
	if (target === 'winner') {
		desc = '수신: 낙찰자 <strong>' + winnerMbId + '</strong>';
		template = '[낙찰 안내]\n\n안녕하세요.\n아래 경매에 낙찰되셨습니다.\n\n· PC 번호: ' + pcnum + '\n· PC 스펙: ' + spec + '\n\n원격 접속 정보를 안내드립니다.\n\n접속 주소: \n아이디: \n비밀번호: \n\n이용에 궁금한 사항은 쪽지로 문의해 주세요.';
	} else {
		desc = '수신: <strong>입찰자 전체</strong>';
		template = '[경매 안내]\n\nPC 번호 ' + pcnum + ' 경매에 입찰해 주셔서 감사합니다.\n\n메시지를 입력해 주세요.';
	}
	$('#memo-target-desc').html(desc);
	$('#memo-message').val(template);
	$('#memo-char-count').text(template.length);
	$('#modal-memo').modal('show');
}
$('#memo-message').on('input', function() {
	$('#memo-char-count').text($(this).val().length);
});
$('#btn-memo-ok').on('click', function() {
	var target  = $('#modal-memo').data('target');
	var message = $('#memo-message').val().trim();
	if (!message) { amgrToast('메시지를 입력해 주세요.', 'error'); return; }
	amgrPost({ action: 'memo', wr_id_off: _amgrWrIdOff, target: target, message: message }, function(res) {
		$('#modal-memo').modal('hide');
		amgrToast(res.message, res.success ? '' : 'error');
	});
});

// ── 공통 AJAX ───────────────────────────────────────────────────────────────
function amgrPost(data, callback) {
	$.ajax({
		url: AMGR_AJAX_URL,
		type: 'POST',
		data: data,
		dataType: 'json',
		success: callback,
		error: function() { amgrToast('서버 오류가 발생했습니다.', 'error'); }
	});
}

// ── 입찰자 펼치기 ───────────────────────────────────────────────────────────
function amgrToggle(id) {
	var el = document.getElementById(id);
	if (el) el.style.display = (el.style.display === 'none') ? 'table-row' : 'none';
}

// ── 카운트다운 ──────────────────────────────────────────────────────────────
(function() {
	var timers = document.querySelectorAll('.amgr-countdown[data-end]');
	if (!timers.length) return;
	function pad(n) { return n < 10 ? '0' + n : '' + n; }
	function tick() {
		var now = Math.floor(Date.now() / 1000);
		timers.forEach(function(el) {
			var diff = parseInt(el.getAttribute('data-end'), 10) - now;
			if (diff <= 0) { el.textContent = '종료'; return; }
			var d = Math.floor(diff / 86400), h = Math.floor((diff % 86400) / 3600),
			    m = Math.floor((diff % 3600) / 60), s = diff % 60;
			el.textContent = (d > 0 ? d + '일 ' : '') + pad(h) + ':' + pad(m) + ':' + pad(s);
		});
	}
	tick();
	setInterval(tick, 1000);
})();
</script>
