<?php
if (!defined("_GNUBOARD_")) exit; // 개별 페이지 접근 불가

//분류권한
$is_cauth = apms_is_cauth();

// 분류
$category = array();
$category_options  = '';
$sql = " select * from {$g5['g5_shop_category_table']} Where ca_id NOT LIKE '30%' ";
if (!$is_cauth)
    $sql .= " and pt_use = '1'";
$sql .= " order by ca_order, ca_id ";
$result = sql_query($sql);
for ($i=0; $row=sql_fetch_array($result); $i++) {
	$c = $row['ca_id'];
	$category[$c] = $row['ca_name'];

	$len = strlen($row['ca_id']) / 2 - 1;
    $nbsp = '';
    for ($i=0; $i<$len; $i++) {
        $nbsp .= '&nbsp;&nbsp;&nbsp;';
    }

	if($row['as_line']) {
		$category_options .= "<option value=\"\">".$nbsp."------------</option>\n";
	}

    $category_options .= '<option value="'.$row['ca_id'].'">'.$nbsp.$row['ca_name'].'</option>'.PHP_EOL;
}

$list = array();

$sfl = '';
$where = " and ";
$sql_search = "";
if ($stx != "") {
	$sfl = 'it_name';
    if ($sfl != "") {
        $sql_search .= " $where $sfl like '%$stx%' ";
        $where = " and ";
    }
    if ($save_stx != $stx)
        $page = 1;
}

if ($sca != "") {
    $sql_search .= " $where (a.ca_id like '$sca%' or a.ca_id2 like '$sca%' or a.ca_id3 like '$sca%') ";
}

$lock_only = (isset($lock_only) && (string)$lock_only === '1') ? '1' : '';
$lock_reason = isset($lock_reason) ? trim((string)$lock_reason) : '';
$vpn_conflict_window = (isset($vpn_conflict_window) && $vpn_conflict_window === 'all') ? 'all' : '30d';
$vpn_conflict_date_sql = ($vpn_conflict_window === '30d') ? " and created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)" : "";
if($lock_reason !== 'paid' && $lock_reason !== 'cancelled') {
    $lock_reason = '';
}
if($lock_reason !== '') {
    $lock_only = '1';
}

$lock_subquery_paid = "
    select distinct c.it_id
    from {$g5['g5_shop_cart_table']} c
    left join {$g5['g5_shop_order_table']} o on (c.od_id = o.od_id)
    where c.ct_select = '1'
      and c.ct_status in ('입금','준비','배송','완료')
";

$lock_subquery_cancelled = "
    select distinct c.it_id
    from {$g5['g5_shop_cart_table']} c
    left join {$g5['g5_shop_order_table']} o on (c.od_id = o.od_id)
    where c.ct_select = '1'
      and c.ct_status in ('취소','반품')
      and (
            IFNULL(o.od_receipt_price, 0) > 0
            or IFNULL(o.od_receipt_point, 0) > 0
            or (
                IFNULL(o.od_receipt_time, '') <> ''
                and IFNULL(o.od_receipt_time, '') <> '0000-00-00 00:00:00'
            )
          )
";

$lock_subquery_all = "
    select distinct c.it_id
    from {$g5['g5_shop_cart_table']} c
    left join {$g5['g5_shop_order_table']} o on (c.od_id = o.od_id)
    where c.ct_select = '1'
      and (
            c.ct_status in ('입금','준비','배송','완료')
            or (
                c.ct_status in ('취소','반품')
                and (
                    IFNULL(o.od_receipt_price, 0) > 0
                    or IFNULL(o.od_receipt_point, 0) > 0
                    or (
                        IFNULL(o.od_receipt_time, '') <> ''
                        and IFNULL(o.od_receipt_time, '') <> '0000-00-00 00:00:00'
                    )
                )
            )
          )
";

$sql_common = " from {$g5['g5_shop_item_table']} a ,
                     {$g5['g5_shop_category_table']} b
               where (a.ca_id = b.ca_id";
if ($is_auth) {
	$sql_common .= " and (a.pt_id = '' or a.pt_id = '{$mb_id}')";
} else {
	$sql_common .= " and a.pt_id = '{$mb_id}'";
}
$sql_common .= ") ";

// RPC 목록(일반/경매): 10/20 상품군만 표시
$sql_common .= " and (a.ca_id in ('10','20')) ";

$sql_common .= $sql_search;
if($lock_only === '1') {
    if($lock_reason === 'paid') {
        $sql_common .= " and a.it_id in ( $lock_subquery_paid ) ";
    } else if($lock_reason === 'cancelled') {
        $sql_common .= " and a.it_id in ( $lock_subquery_cancelled ) ";
    } else {
        $sql_common .= " and a.it_id in ( $lock_subquery_all ) ";
    }
}

$lock_stats = array('locked' => 0, 'paid' => 0, 'cancelled' => 0);
$row_lock = sql_fetch(" select count(distinct a.it_id) as cnt $sql_common and a.it_id in ( $lock_subquery_all ) ");
$row_paid = sql_fetch(" select count(distinct a.it_id) as cnt $sql_common and a.it_id in ( $lock_subquery_paid ) ");
$row_cancelled = sql_fetch(" select count(distinct a.it_id) as cnt $sql_common and a.it_id in ( $lock_subquery_cancelled ) ");
$lock_stats['locked'] = isset($row_lock['cnt']) ? (int)$row_lock['cnt'] : 0;
$lock_stats['paid'] = isset($row_paid['cnt']) ? (int)$row_paid['cnt'] : 0;
$lock_stats['cancelled'] = isset($row_cancelled['cnt']) ? (int)$row_cancelled['cnt'] : 0;

// 테이블의 전체 레코드수만 얻음
$sql = " select count(*) as cnt " . $sql_common;
$row = sql_fetch($sql);
$total_count = $row['cnt'];

$rows = $config['cf_'.MOBILE_.'page_rows'];
$total_page  = ceil($total_count / $rows);  // 전체 페이지 계산
if ($page < 1) { $page = 1; } // 페이지가 없으면 첫 페이지 (1 페이지)
$from_record = ($page - 1) * $rows; // 시작 열을 구함

$sql_order = "order by a.pt_show, a.pt_num desc, a.it_id desc";

$sql  = " select *
           $sql_common
           $sql_order
           limit $from_record, $rows ";
$result = sql_query($sql);
for ($i=0; $row=sql_fetch_array($result); $i++) {
	$list[$i] = $row;
	$list[$i]['href'] = G5_SHOP_URL.'/item.php?it_id='.$row['it_id'];
    $list[$i]['vpn_id_conflict_count'] = 0;
    $list[$i]['vpn_id_conflict_last'] = '';
    $list[$i]['vpn_id_conflict_last_pair'] = '';
    $list[$i]['vpn_id_conflict_last_od_id'] = '';

    $lock_info = function_exists('get_item_permanent_lock_info') ? get_item_permanent_lock_info($row['it_id']) : array('locked' => false);
    $is_permanent_locked = !empty($lock_info['locked']);
    if($is_permanent_locked) {
        $list[$i]['it_soldout'] = 1;
    }

	$c1 = $row['ca_id'];
	$c2 = ($row['ca_id2']) ? $row['ca_id2'] : substr($c1,0,4);
	$c3 = ($row['ca_id3']) ? $row['ca_id3'] : substr($c1,0,2);

	$list[$i]['ca_name1'] = $category[$c1];
	$list[$i]['ca_name2'] = $category[$c2];
	$list[$i]['ca_name3'] = $category[$c3];

	$list[$i]['it_install_price'] = $row['it_install_price']; // 개통비
    $billing_plan = strtolower(trim((string)$row['it_billing_plan']));
    if($billing_plan === 'yearly') {
        $plan_label = '연정액';
    } else {
        $plan_label = '월정액';
    }

    $daily_price = (int)$row['it_price'];
    if($daily_price < 0) $daily_price = 0;
    $hourly_price = (int)$row['it_is_hour_sale_price'];
    if($hourly_price <= 0) {
        $hourly_price = (int)round($daily_price / 24);
    }
    $monthly_price = $daily_price * 30;

    $list[$i]['it_price_1h'] = $hourly_price;
    $list[$i]['it_price_1d'] = $daily_price;
    $list[$i]['it_price_1m'] = $monthly_price;
    $list[$i]['it_billing_plan_label'] = $plan_label;

	$list[$i]['it_spec_app_ver'] = ($row['it_spec_app_ver']!='v0.0.0' && $row['it_spec_app_ver']=='') ? $row['it_spec_app_ver'] : 'X'; // APP VERSION
	$list[$i]['it_spec_mgr_nickname'] = $row['it_spec_mgr_nickname'] ? $row['it_spec_mgr_nickname'] : 'X'; // 관리컴퓨터별명

    // 원격제어S/W JSON 데이터 파싱
    $jsonData_remote_sw = json_decode($row['it_spec_remote_sw'], true);
    if (is_array($jsonData_remote_sw)) {
        foreach ($jsonData_remote_sw as $index => $data) {
            $programName = $data["Program__{$index}"] ?? '';
            $remoteIP = $data["RemoteIP__{$index}"] ?? '';
            $programId = $data["{$programName}_ID__{$index}"] ?? '';
            $programPwd = $data["{$programName}_PWD__{$index}"] ?? '';
            $countryName = $data["RemoteIP_CountryName__{$index}"] ?? '';
            $countryCode = $data["RemoteIP_CountryCode__{$index}"] ?? '';
            $cityName = $data["RemoteIP_City__{$index}"] ?? '';

            $flag_url = G5_DATA_URL."/item/img_nation_flag/svg/unknown.svg";
            if ($countryCode) {
                $flag_low = strtolower($countryCode);
                if (file_exists(G5_DATA_PATH."/item/img_nation_flag/svg/".$flag_low.".svg")) {
                    $flag_url = G5_DATA_URL."/item/img_nation_flag/svg/".$flag_low.".svg";
                }
            }

            // 원격제어S/W
            if ($remoteIP) {
                $displayCountry = $countryName ? $countryName : ($cityName ? $cityName : 'Unknown');
                $list[$i]['it_spec_remote_ip'] = "<div style='display:flex; justify-content:center; align-items:center; flex-direction:column;'><div class='flag-and-city'><img src='".$flag_url."' alt='{$displayCountry}'><span>{$displayCountry}</span></div></div><div><span>{$remoteIP}</span></div></div>";
                $list[$i]['it_spec_remote_program'] .= "<div><span>{$programName}</span></div>";
            } else {
                $list[$i]['it_spec_remote_ip'] = 'X';
                $list[$i]['it_spec_remote_program'] = '<div style="width:100%; text-align:center;">X</div>';
            }
        }
    }

    $list[$i]['it_spec_os'] = $row['it_spec_os'] ? $row['it_spec_os'] : 'X'; // OS
    $list[$i]['it_spec_mainboard'] = $row['it_spec_mainboard'] ? $row['it_spec_mainboard'] : 'X'; // MainBoard
    $list[$i]['it_spec_ram'] = $row['it_spec_ram'] ? $row['it_spec_ram'] : 'X'; // RAM
    $list[$i]['it_spec_ram_type'] = $row['it_spec_ram_type'] ? $row['it_spec_ram_type'] : 'X'; // RAM TYPE
    $list[$i]['it_spec_gpu'] = $row['it_spec_gpu'] ? $row['it_spec_gpu'] : 'X'; // GPU
    $list[$i]['it_spec_ssd'] = $row['it_spec_ssd'] ? $row['it_spec_ssd'] : 'X'; // SSD
    $list[$i]['it_spec_ssd_type'] = $row['it_spec_ssd_type'] ? $row['it_spec_ssd_type'] : 'X'; // SSD TYPE
    $list[$i]['it_spec_hdd'] = $row['it_spec_hdd'] ? $row['it_spec_hdd'] : 'X'; // HDD
    $list[$i]['it_spec_hdd_type'] = $row['it_spec_hdd_type'] ? $row['it_spec_hdd_type'] : 'X'; // HDD TYPE
    $list[$i]['it_spec_keyboard'] = $row['it_spec_keyboard'] ? 'O' : 'X'; // KEYBOARD
    $list[$i]['it_spec_mouse'] = $row['it_spec_mouse'] ? 'O' : 'X'; // MOUSE

	$list[$i]['it_specs'] = $row['it_spec_os'] ?  $row['it_spec_os'] : ''; // OS
	$list[$i]['it_specs'] .= $row['it_spec_mainboard'] ?  ' / '.$row['it_spec_mainboard'] : ''; // MainBoard
	$list[$i]['it_specs'] .= $row['it_spec_ram'] ?  ' / '.$row['it_spec_ram'] : ''; // RAM
	$list[$i]['it_specs'] .= $row['it_spec_ram_type'] ?  ' / '.$row['it_spec_ram_type'] : ''; // RAM TYPE
	$list[$i]['it_specs'] .= $row['it_spec_gpu'] ?  ' / '.$row['it_spec_gpu'] : ''; // GPU
	$list[$i]['it_specs'] .= $row['it_spec_ssd'] ?  ' / '.$row['it_spec_ssd'] : ''; // SSD
	$list[$i]['it_specs'] .= $row['it_spec_ssd_type'] ?  ' / '.$row['it_spec_ssd_type'] : ''; // SSD TYPE
	$list[$i]['it_specs'] .= $row['it_spec_hdd'] ?  ' / '.$row['it_spec_hdd'] : ''; // HDD
	$list[$i]['it_specs'] .= $row['it_spec_hdd_type'] ?  ' / '.$row['it_spec_hdd_type'] : ''; // HDD TYPE
	$list[$i]['it_specs'] .= $row['it_spec_keyboard'] ?  ' / '.$row['it_spec_keyboard'] : ''; // KEYBOARD
	$list[$i]['it_specs'] .= $row['it_spec_mouse'] ?  ' / '.$row['it_spec_mouse'] : ''; // MOUSE


    $result_status = sql_query(" SELECT ct_status, mb_id, ct_time, ct_qty, ct_price, ct_install_price FROM {$g5['g5_shop_cart_table']} WHERE it_id = '{$row['it_id']}' ORDER BY od_id DESC ");
    $result_status_count = sql_num_rows($result_status);
    for ($j=0; $row_status=sql_fetch_array($result_status); $j++) {
        if ($row_status['ct_status']) {
            if ($j == 0) {
                $list[$i]['ct_status'] = "<select style='width:105px;'>";
            }
            if ($row_status['ct_status'] == "쇼핑") {
                $ct_status_disp = "장바구니";
            } else {
                $ct_status_disp = $row_status['ct_status'];
            }
            $sum_od_price = $row_status['ct_price'] + $row_status['ct_install_price'];
            // $list[$i]['ct_status'] .= $row_status['ct_status'] . " / " . substr($row_status['ct_time'],2,14) . " / " . $row_status['mb_id'] . " / " . $row_status['ct_qty'] . " Days / " . number_format($row_status['sum_od_price']) . " Point" . "<br>";
            $list[$i]['ct_status'] .= "<option>" . ($result_status_count - $j) . ") " . $ct_status_disp . " / " . substr($row_status['ct_time'],2,14) . " / " . $row_status['mb_id'] . " / " . $row_status['ct_qty'] . " Days / " . number_format($sum_od_price) . " Point" . "</option>";
            //$list[$i]['ct_status'] .= "<option>" . $row_status['ct_status'] . "</option>";
        } else {
            if ($list[$i]['it_use'] == 1) {
                $list[$i]['ct_status'] .= "<div style='width:100%; text-align:center;'>판매중</div>";
            } else {
                $list[$i]['ct_status'] .= "<div style='width:100%; text-align:center;'>판매 중지 설정됨</div>";
            }
        }
    }
    if ($j > 0) {
        $list[$i]['ct_status'] .= "</select>";
    }

    if($is_permanent_locked) {
        $lock_reason = isset($lock_info['reason']) ? get_text($lock_info['reason']) : '결제완료 이력으로 영구잠금';
        $lock_first_od_id = isset($lock_info['first_od_id']) ? get_text($lock_info['first_od_id']) : '-';
        $list[$i]['ct_status'] .= "<div style='margin-top:6px; padding:6px; border:1px solid #d9534f; border-radius:4px; background:#fff5f5; text-align:left;'>"
            . "<div style='font-weight:700; color:#d9534f;'>영구잠금</div>"
            . "<div style='font-size:11px; color:#333;'>사유: {$lock_reason}</div>"
            . "<div style='font-size:11px; color:#333;'>최초 구매주문번호: {$lock_first_od_id}</div>"
            . "</div>";
    }
}

if (count($list) > 0) {
    $it_ids = array();
    for ($i=0; $i<count($list); $i++) {
        $tmp_it_id = trim((string)($list[$i]['it_id'] ?? ''));
        if ($tmp_it_id === '') {
            continue;
        }
        $it_ids[$tmp_it_id] = true;
    }

    if (count($it_ids) > 0) {
        $in = array();
        foreach (array_keys($it_ids) as $tmp_it_id) {
            $in[] = "'" . sql_escape_string($tmp_it_id) . "'";
        }
        $in_sql = implode(',', $in);

        $conflict_map = array();

        $res_count = sql_query("SELECT it_id, COUNT(*) AS cnt, MAX(created_at) AS last_at
                              FROM app_ikev2_id_conflict_history
                             WHERE it_id IN (" . $in_sql . ")" . $vpn_conflict_date_sql . "
                             GROUP BY it_id", false);
        if ($res_count) {
            for ($ci = 0; $crow = sql_fetch_array($res_count); $ci++) {
                $tmp_it_id = trim((string)($crow['it_id'] ?? ''));
                if ($tmp_it_id === '') {
                    continue;
                }
                $conflict_map[$tmp_it_id] = array(
                    'cnt' => (int)($crow['cnt'] ?? 0),
                    'last_at' => trim((string)($crow['last_at'] ?? '')),
                    'last_pair' => '',
                    'last_od_id' => ''
                );
            }
        }

        $res_last = sql_query("SELECT h.it_id, h.od_id, h.original_user_id, h.resolved_user_id
                             FROM app_ikev2_id_conflict_history h
                             INNER JOIN (
                                 SELECT it_id, MAX(conflict_id) AS max_conflict_id
                                   FROM app_ikev2_id_conflict_history
                                                                    WHERE it_id IN (" . $in_sql . ")" . $vpn_conflict_date_sql . "
                                  GROUP BY it_id
                             ) x ON h.conflict_id = x.max_conflict_id", false);
        if ($res_last) {
            for ($li = 0; $lrow = sql_fetch_array($res_last); $li++) {
                $tmp_it_id = trim((string)($lrow['it_id'] ?? ''));
                if ($tmp_it_id === '') {
                    continue;
                }
                $pair = trim((string)($lrow['original_user_id'] ?? '')) . ' -> ' . trim((string)($lrow['resolved_user_id'] ?? ''));
                if (!isset($conflict_map[$tmp_it_id])) {
                    $conflict_map[$tmp_it_id] = array('cnt' => 0, 'last_at' => '', 'last_pair' => $pair, 'last_od_id' => trim((string)($lrow['od_id'] ?? '')));
                } else {
                    $conflict_map[$tmp_it_id]['last_pair'] = $pair;
                    $conflict_map[$tmp_it_id]['last_od_id'] = trim((string)($lrow['od_id'] ?? ''));
                }
            }
        }

        for ($i=0; $i<count($list); $i++) {
            $tmp_it_id = trim((string)($list[$i]['it_id'] ?? ''));
            if ($tmp_it_id === '' || !isset($conflict_map[$tmp_it_id])) {
                continue;
            }
            $list[$i]['vpn_id_conflict_count'] = (int)($conflict_map[$tmp_it_id]['cnt'] ?? 0);
            $list[$i]['vpn_id_conflict_last'] = trim((string)($conflict_map[$tmp_it_id]['last_at'] ?? ''));
            $list[$i]['vpn_id_conflict_last_pair'] = trim((string)($conflict_map[$tmp_it_id]['last_pair'] ?? ''));
            $list[$i]['vpn_id_conflict_last_od_id'] = trim((string)($conflict_map[$tmp_it_id]['last_od_id'] ?? ''));
        }
    }
}

// 페이징
$write_pages = (G5_IS_MOBILE) ? $config['cf_mobile_pages'] : $config['cf_write_pages'];
$list_page = './?ap='.$ap.'&amp;sca='.$sca.'&amp;save_stx='.$stx.'&amp;stx='.$stx.'&amp;lock_only='.$lock_only.'&amp;lock_reason='.$lock_reason.'&amp;vpn_conflict_window='.$vpn_conflict_window.'&amp;page=';

echo '<script src="./script.js"></script>'.PHP_EOL;

include_once($skin_path.'/itemlist.skin.php');
?>
