<?php
if (!defined("_GNUBOARD_")) exit; // 개별 페이지 접근 불가
include_once(G5_PLUGIN_PATH.'/jquery-ui/datepicker.php');

$list = array();
$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)" : "";

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

// 분류
$category = array();
$category_options  = '';
$sql = " select * from {$g5['g5_shop_category_table']} ";
if (!$is_cauth)
    $sql .= " where 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;
}

// 검색
$sql_search = "";
if ($stx) {
	if($sfl == 'a.od_id') {
		$stx = str_replace("-", "", $stx);
	}
	$sql_search .= " and $sfl like '%$stx%' ";
}

if ($sca) {
    $sql_search .= " and (b.ca_id like '$sca%' or b.ca_id2 like '$sca%' or b.ca_id3 like '$sca%') ";
}

//조회기간이 있으면
$sql_date = '';
if(isset($fr_date) && $fr_date && isset($to_date) && $to_date) {
	$fr_day = preg_replace("/([0-9]{4})([0-9]{2})([0-9]{2})/", "\\1-\\2-\\3", $fr_date);
	$to_day = preg_replace("/([0-9]{4})([0-9]{2})([0-9]{2})/", "\\1-\\2-\\3", $to_date);
	$sql_date .= "and SUBSTRING(a.pt_datetime,1,10) between '$fr_day' and '$to_day'";
	$qstr .= '&amp;fr_date='.$fr_date.'&amp;to_date='.$to_date;

} else {
	$fr_date = $to_date = '';
}

$sql_common = " from {$g5['g5_shop_cart_for_extension_of_period_table']} a left join {$g5['g5_shop_item_table']} b on ( a.it_id = b.it_id ) where a.pt_id = '{$member['mb_id']}' and a.ct_status = '완료' and a.ct_select = '1' $sql_date $sql_search ";

// 테이블의 전체 레코드수만 얻음
$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 = " select a.*, b.pt_commission as b_pt_commission, b.pt_point as b_pt_point, b.pt_incentive as b_pt_incentive  $sql_common order by a.pt_datetime desc, a.ct_id desc limit $from_record, $rows ";
$result = sql_query($sql);
for ($i=0; $row=sql_fetch_array($result); $i++) {
    $list[$i] = $row;
    $list[$i]['num'] = $total_count - ($page - 1) * $rows - $i;
    $list[$i]['date'] = $row['pt_datetime'];
    $list[$i]['href'] = G5_SHOP_URL.'/item.php?it_id='.$row['it_id'];
    $list[$i]['inquiry'] = './inquiryview.php?no='.$row['od_id'];
    $list[$i]['sale'] = $row['pt_sale'];
    $list[$i]['qty'] = $row['ct_qty'];
    $list[$i]['point'] = $row['pt_point'];
    $list[$i]['commission'] = $row['pt_commission'];
    $list[$i]['incentive'] = $row['pt_incentive'];

        // 데이터 출처 테이블에 따라 'fromtable' 필드 설정
        if ($row['ct_qty_for_extension_of_period'] == 0 AND $row['ct_qty_hour_for_extension_of_period'] == 0) {
        	$list[$i]['fromtable'] = 'shop_cart';
        } else {
		$list[$i]['fromtable'] = 'shop_cart_for_extension_of_period';
        }

    // 주문번호에 - 추가
    switch(strlen($row['od_id'])) {
        case 16:
            $disp_od_id = substr($row['od_id'],0,8).'-'.substr($row['od_id'],8);
            break;
        default:
            $disp_od_id = substr($row['od_id'],0,6).'-'.substr($row['od_id'],6);
            break;
    }

    $list[$i]['od_num'] = $disp_od_id;

    // 매출
    $netsale = $row['pt_sale'] - $row['pt_commission'] - $row['pt_point'] + $row['pt_incentive'];
    $list[$i]['netsale'] = $netsale;
    $list[$i]['net'] = $row['pt_net'];
    $list[$i]['vat'] = ($netsale - $row['pt_net']);

    // 옵션
	if ($list[$i]['fromtable'] == "shop_cart") {
    	$list[$i]['option'] = $row['ct_option'];
	} else {
		$list[$i]['option'] = $row['ct_option'];
	}

	// 계약일수
	if ($list[$i]['fromtable'] == "shop_cart") {
        $order_hours = apms_contract_hours_from_day_hour((int)$row['ct_qty'], (int)$row['ct_qty_hour']);
        $list[$i]['order_date'] = apms_contract_hours_text($order_hours);
	} else {
        $order_hours = apms_contract_hours_from_day_hour((int)$row['ct_qty_for_extension_of_period'], (int)$row['ct_qty_hour_for_extension_of_period']);
        $list[$i]['order_date'] = apms_contract_hours_text($order_hours);
	}

    if($row['pt_msg1']) {
        $list[$i]['option'] .= '<div>'.get_text($row['pt_msg1']).'</div>';
    }
    if($row['pt_msg2']) {
        $list[$i]['option'] .= '<div>'.get_text($row['pt_msg2']).'</div>';
    }
    if($row['pt_msg3']) {
        $list[$i]['option'] .= '<div>'.get_text($row['pt_msg3']).'</div>';
    }

    // 구매회원
    $list[$i]['buyer'] = '비회원';
    if($row['mb_id']) {
        $mb = get_member($row['mb_id'], 'mb_nick, mb_email, mb_homepage');
        if($mb['mb_nick']) {
            $list[$i]['buyer'] = apms_sideview($row['mb_id'], $mb['mb_nick'], $mb['mb_email'], $mb['wr_homepage']);
        }
    }

    $list[$i]['vpn_id_conflict_count'] = 0;
    $list[$i]['vpn_id_conflict_last'] = '';
    $list[$i]['vpn_id_conflict_last_pair'] = '';
}

if (count($list) > 0) {
    $od_ids = array();
    foreach ($list as $tmp_row) {
        $tmp_od_id = trim((string)($tmp_row['od_id'] ?? ''));
        if ($tmp_od_id === '') {
            continue;
        }
        $od_ids[$tmp_od_id] = true;
    }

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

        $conflict_map = array();

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

        $res_last = sql_query("SELECT h.od_id, h.original_user_id, h.resolved_user_id
                                 FROM app_ikev2_id_conflict_history h
                                 INNER JOIN (
                                     SELECT od_id, MAX(conflict_id) AS max_conflict_id
                                       FROM app_ikev2_id_conflict_history
                                                                            WHERE od_id IN (" . $in_sql . ")" . $vpn_conflict_date_sql . "
                                      GROUP BY od_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_od_id = trim((string)($lrow['od_id'] ?? ''));
                if ($tmp_od_id === '') {
                    continue;
                }
                $pair = trim((string)($lrow['original_user_id'] ?? '')) . ' -> ' . trim((string)($lrow['resolved_user_id'] ?? ''));
                if (!isset($conflict_map[$tmp_od_id])) {
                    $conflict_map[$tmp_od_id] = array('cnt' => 0, 'last_at' => '', 'last_pair' => $pair);
                } else {
                    $conflict_map[$tmp_od_id]['last_pair'] = $pair;
                }
            }
        }

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

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

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