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

$mb_id_esc = sql_escape_string($member['mb_id']);
$now = G5_SERVER_TIME;

$rows = 20;
$page = max(1, (int)(isset($_GET['page']) ? $_GET['page'] : 1));
$from_record = ($page - 1) * $rows;

$filter = isset($_GET['filter']) ? preg_replace('/[^a-z]/', '', $_GET['filter']) : '';
$sql_filter = '';
switch ($filter) {
	case 'active':  $sql_filter = " AND bo.auction_on = 1 AND bo.wr_2 > NOW()"; break;
	case 'won':     $sql_filter = " AND (bo.wr_10 IS NOT NULL AND bo.wr_10 != '')"; break;
	case 'failed':  $sql_filter = " AND bo.auction_on != 1 AND (bo.wr_10 IS NULL OR bo.wr_10 = '') AND bo.wr_2 != '' AND bo.wr_2 != '0000-00-00 00:00:00' AND bo.wr_2 < NOW()"; break;
	case 'pending': $sql_filter = " AND bo.auction_on = 0 AND (bo.wr_2 = '' OR bo.wr_2 = '0000-00-00 00:00:00' OR bo.wr_2 > NOW())"; break;
}

$sql_where = " WHERE bo.mb_id = '{$mb_id_esc}' {$sql_filter}";

$cnt_row = sql_fetch("SELECT COUNT(*) as cnt FROM g5_write_auction_off AS bo {$sql_where}");
$total_count = (int)$cnt_row['cnt'];
$write_pages = $config['cf_write_pages'];
$total_page  = ceil($total_count / $rows);
if ($page < 1) $page = 1;

$tab_param = $filter ? '&amp;filter=' . $filter : '';
$list_page = APMS_PARTNER_URL . '/?ap=auction_mgr' . $tab_param . '&amp;page=';

$sql = "
	SELECT
		bo.*,
		COUNT(td.td_id)         AS bid_count,
		MAX(td.td_tender_point) AS highest_bid,
		it.it_name,
		it.it_spec_vpn_type,
		it.it_spec_grade,
		it.it_spec_mgr_nickname,
		it.it_spec_cpu,
		it.it_spec_os,
		it.it_spec_ram_type,
		it.it_spec_ram,
		it.it_spec_gpu,
		it.it_spec_ssd_type,
		it.it_spec_ssd,
		it.it_spec_hdd_type,
		it.it_spec_hdd,
		it.it_spec_keyboard,
		it.it_spec_mouse,
		it.it_spec_remote_sw,
		it.it_spec_app_ver
	FROM g5_write_auction_off AS bo
	LEFT JOIN g5_write_auction_tender AS td ON bo.wr_id = td.wr_id
	LEFT JOIN {$g5['g5_shop_item_table']} AS it ON bo.pcnum = it.it_id
	{$sql_where}
	GROUP BY bo.wr_id_off
	ORDER BY bo.auction_on DESC, bo.wr_id_off DESC
	LIMIT {$from_record}, {$rows}
";
$result = sql_query($sql);

$list = array();
while ($row = sql_fetch_array($result)) {
	$sub      = explode('|', (string)$row['wr_subject']);
	$spec     = isset($sub[1]) ? trim($sub[1]) : '';
	$start_pt = isset($sub[2]) && trim($sub[2]) !== '' ? (int)trim($sub[2]) : 0;
	$method   = isset($sub[4]) && trim($sub[4]) !== '' ? trim($sub[4]) : '-';

	$raw_e  = trim((string)$row['wr_2']);
	$end_ts = ($raw_e && $raw_e !== '0000-00-00 00:00:00') ? (int)@strtotime($raw_e) : 0;
	$winner = trim((string)$row['wr_10']);

	if ((int)$row['auction_on'] === 1 && $end_ts > $now) {
		$status      = 'active';
		$status_text = '경매 진행중';
	} elseif ($winner !== '') {
		$status      = 'won';
		$status_text = '낙찰';
	} elseif ($end_ts > 0 && $end_ts < $now) {
		$status      = 'failed';
		$status_text = '유찰';
	} else {
		$status      = 'pending';
		$status_text = '미경매';
	}

	$remaining_sec = ($status === 'active') ? max(0, $end_ts - $now) : 0;

	// 입찰자 목록 (최대 50건)
	$bids = array();
	if ((int)$row['bid_count'] > 0 && $row['wr_id']) {
		$bid_res = sql_query("
			SELECT td.td_id, td.mb_id, td.td_tender_point, td.td_datetime, td.td_status,
			       m.mb_nick
			FROM g5_write_auction_tender AS td
			LEFT JOIN {$g5['member_table']} AS m ON td.mb_id = m.mb_id
			WHERE td.wr_id = '" . (int)$row['wr_id'] . "'
			ORDER BY td.td_tender_point DESC
			LIMIT 50
		");
		while ($bid = sql_fetch_array($bid_res)) {
			$bids[] = $bid;
		}
	}

	$row['spec_summary']       = $spec;
	$row['start_point']        = $start_pt;
	$row['auction_method']     = ($method !== '-') ? $method . ' 낙찰' : '-';
	$row['end_ts']             = $end_ts;
	$row['winner_mb_id']       = $winner;
	$row['status']             = $status;
	$row['status_text']        = $status_text;
	$row['remaining_sec']      = $remaining_sec;
	$row['bids']               = $bids;
	// 개통비 납부 상태 데이터 로드
	$row['install_fee']        = isset($row['install_fee']) ? (int)$row['install_fee'] : 0;
	$row['install_fee_status'] = isset($row['install_fee_status']) ? (int)$row['install_fee_status'] : 0;
	$row['install_fee_deadline'] = isset($row['install_fee_deadline']) ? $row['install_fee_deadline'] : '';
	$row['install_fee_paid_at']  = isset($row['install_fee_paid_at'])  ? $row['install_fee_paid_at']  : '';
	$row['pcnum_disp']         = 'RPC-A' . trim((string)$row['pcnum']);
	$row['auction_board_href'] = ($row['wr_id'])
		? G5_BBS_URL . '/board.php?bo_table=auction&amp;wr_id=' . (int)$row['wr_id']
		: '';
	$list[] = $row;
}

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