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

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

define("_ORDERINQUIRY_", true);

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_shoppoint_order4withdraw where mb_id = '{$member_mb_id_esc}' ";
}
else if ($od_id && $od_pwd) // 비회원인 경우 포인트 출금신청서번호와 비밀번호가 넘어왔다면
{
    $sql_common = " from g5_shoppoint_order4withdraw where od_id = '{$od_id_esc}' and od_pwd = '{$od_pwd_esc}' ";
}
else // 그렇지 않다면 로그인으로 가기
{
    goto_url(G5_BBS_URL.'/login.php?url='.urlencode(G5_URL.'/shoppoint/orderinquiry4withdraw.php'));
}

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

// 비회원 포인트 출금신청확인시 비회원의 모든 포인트 출금신청이 다 출력되는 오류 수정
// 조건에 맞는 포인트 출금신청서가 없다면
if ($total_count == 0)
{
    $orderinquiry_toast_msg = '포인트 출금신청이 존재하지 않습니다.';
}

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

// 비회원 포인트 출금신청확인의 경우 바로 포인트 출금신청서 상세조회로 이동
if (!$is_member)
{
    $sql = " select od_id, od_time, od_ip from g5_shoppoint_order4withdraw where od_id = '{$od_id_esc}' and od_pwd = '{$od_pwd_esc}' ";
    $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);
        goto_url(G5_URL.'/shoppoint/orderinquiryview4withdraw.php?od_id='.$row['od_id'].'&amp;uid='.$uid);
    }
}

$list = array();

if ($is_member) {
    $limit = " limit $from_record, $rows ";
    $sql = " select *
           from g5_shoppoint_order4withdraw
          where mb_id = '{$member_mb_id_esc}'
          order by od_id 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']);

	switch($row['od_status']) {
		case '출금신청':
		case '신청':
			$od_status = '출금신청';
			break;
		case '출금':
			$od_status = '출금완료';
			break;
		case '준비':
			$od_status = '상품준비중';
			break;
		case '배송':
			$od_status = '상품배송';
			break;
		case '완료':
			$od_status = '배송완료';
			break;
		default:
			$od_status = '출금취소';
			break;
	}

    $od_fx_type = $row['od_fx_type'];
    $target_currency = substr($od_fx_type,3,3);
    $od_fx_rate = $row['od_fx_rate'];
    $od_fx_amount = $row['od_fx_amount'];
    $od_settle_case = $row['od_settle_case'];
    $od_time = $row['od_time'];
    $od_bank_account = $row['od_bank_account'];
    $od_deposit_name = $row['od_deposit_name'];
    $od_misu = $row['od_misu'];
    $od_receipt_price = $row['od_receipt_price'];

    switch ($target_currency) {
        case 'KRW':
            $target_nation_flag_img = "<img src='".G5_DATA_URL."/item/img_nation_flag/svg/kr.svg' class='nation_flag_img2'>";
            $od_fx_amount_display = number_format($od_fx_amount,0);
            $od_receipt_price_display = number_format($od_receipt_price * $od_fx_rate,0);
            $od_misu_display = number_format($od_misu * $od_fx_rate,0);
            break;
        case 'USD':
            $target_nation_flag_img = "<img src='".G5_DATA_URL."/item/img_nation_flag/svg/us.svg' class='nation_flag_img1'>";
            $od_fx_amount_display = number_format($od_fx_amount,2);
            $od_receipt_price_display = number_format($od_receipt_price * $od_fx_rate,2);
            $od_misu_display = number_format($od_misu * $od_fx_rate,2);
            break;
        case 'EUR':
            $target_nation_flag_img = "<img src='".G5_DATA_URL."/item/img_nation_flag/svg/eu.svg' class='nation_flag_img1'>";
            $od_fx_amount_display = number_format($od_fx_amount,2);
            $od_receipt_price_display = number_format($od_receipt_price * $od_fx_rate,2);
            $od_misu_display = number_format($od_misu * $od_fx_rate,2);
            break;
        case 'CNY':
            $target_nation_flag_img = "<img src='".G5_DATA_URL."/item/img_nation_flag/svg/cn.svg' class='nation_flag_img1'>";
            $od_fx_amount_display = number_format($od_fx_amount,2);
            $od_receipt_price_display = number_format($od_receipt_price * $od_fx_rate,2);
            $od_misu_display = number_format($od_misu * $od_fx_rate,2);
            break;
        case 'JPY':
            $target_nation_flag_img = "<img src='".G5_DATA_URL."/item/img_nation_flag/svg/jp.svg' class='nation_flag_img2'>";
            $od_fx_amount_display = number_format($od_fx_amount,0);
            $od_receipt_price_display = number_format($od_receipt_price * $od_fx_rate,0);
            $od_misu_display = number_format($od_misu * $od_fx_rate,0);
            break;
        case 'VND':
            $target_nation_flag_img = "<img src='".G5_DATA_URL."/item/img_nation_flag/svg/vn.svg' class='nation_flag_img1'>";
            $od_fx_amount_display = number_format($od_fx_amount,0);
            $od_receipt_price_display = number_format($od_receipt_price * $od_fx_rate,0);
            $od_misu_display = number_format($od_misu * $od_fx_rate,0);
            break;
    }

        $list[$i] = $row;
        $list[$i]['od_raw_status'] = $row['od_status'];
        $list[$i]['od_href'] = G5_URL.'/shoppoint/orderinquiryview4withdraw.php?od_id='.$row['od_id'].'&amp;uid='.$uid;
        $list[$i]['od_total_price'] = $row['od_cart_price'] + $row['od_send_cost'] + $row['od_send_cost2'] + $row['od_withdraw_fee'];
        $list[$i]['od_withdraw_fee'] = $row['od_withdraw_fee'];
        $list[$i]['od_withdraw_fee_display'] = number_format($list[$i]['od_withdraw_fee'], 0) . ' Point';
        $list[$i]['od_status'] = $od_status;
    $list[$i]['od_fx_amount_display'] = $target_nation_flag_img . $od_fx_amount_display . ' ' . $target_currency;
    $list[$i]['od_receipt_price_display'] = $target_nation_flag_img . $od_receipt_price_display . ' ' . $target_currency;
    $list[$i]['od_misu_display'] = $target_nation_flag_img . $od_misu_display . ' ' . $target_currency;
        $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 = ($ext_paid_point > 0) ? 1 : 0;
        $list[$i]['extension_summary_text'] = ($ext_paid_point > 0)
            ? ('연장주문 ' . number_format($ext_order_count) . '건 / +' . number_format($ext_paid_point) . ' Point')
            : '';

        $_pend = in_array($row['od_status'], array('출금신청', '신청'));
        if (!$_pend && $row['od_status'] === '출금') {
            $list[$i]['od_total_price_display'] = number_format($list[$i]['od_total_price'], 0) . ' Point<br><div class="oi-status-badge oi-status-done" style="font-size:0.8em;background:#eee;color:#6699ff;">출금완료 되었습니다</div>';
        } else if ($_pend) {
            $list[$i]['od_total_price_display'] = number_format($list[$i]['od_total_price'], 0) . ' Point<br><div class="oi-status-badge oi-status-pending" style="font-size:0.8em;background:#eee;color:#000;">출금신청이 접수되었습니다</div>';
        } else {
            $list[$i]['od_total_price_display'] = number_format($list[$i]['od_total_price'], 0) . ' Point';
        }
	}

    // notify_count 배치 조회 (출금 확인 요청 횟수)
    if ($is_member && count($list) > 0) {
        $wn_dn_ids = array();
        foreach ($list as $wn_item) {
            $wn_dn_ids[] = "'" . sql_escape_string($wn_item['od_id']) . "'";
        }
        $wn_nc_sql = "SELECT od_id, COUNT(*) AS cnt FROM g5_withdraw_notify
                      WHERE mb_id='{$member_mb_id_esc}' AND od_id IN (" . implode(',', $wn_dn_ids) . ")
                      GROUP BY od_id";
        $wn_nc_res = sql_query($wn_nc_sql, false);
        $wn_notify_counts = array();
        while ($wn_nc_row = sql_fetch_array($wn_nc_res)) {
            $wn_notify_counts[$wn_nc_row['od_id']] = (int)$wn_nc_row['cnt'];
        }
        for ($wn_j = 0; $wn_j < count($list); $wn_j++) {
            $list[$wn_j]['notify_count'] = isset($wn_notify_counts[$list[$wn_j]['od_id']])
                ? $wn_notify_counts[$list[$wn_j]['od_id']] : 0;
        }
    }
}

$write_pages = G5_IS_MOBILE ? $config['cf_mobile_pages'] : $config['cf_write_pages'];
	$_cqs = trim(preg_replace('/(&amp;|&)?page=\d*/', '', $qstr), '&;');
	$_eqs = $_cqs ? $_cqs . '&amp;' : '';
	$list_page = $_SERVER['SCRIPT_NAME'] . '?' . $_eqs . 'page=';

// Page ID
$pid = ($pid) ? $pid : 'withdrawalinquiry';
$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'] = '포인트 출금신청 내역조회';

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.skin4shoppoint4withdraw.php');

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');
}
?>