<?php
include_once('./_common.php');
include_once(G5_LIB_PATH.'/mailer.lib.php');
include_once(G5_PATH.'/mylib/ikev2_provision.lib.php');

//이니시스 lpay 요청으로 왔다면 $default['de_pg_service'] 값을 이니시스로 변경합니다.
if( $od_settle_case == 'lpay' ){
    $default['de_pg_service'] = 'inicis';
}

if(($od_settle_case != '무통장' && $od_settle_case != '포인트' && $od_settle_case != 'KAKAOPAY') && $default['de_pg_service'] == 'lg' && !$_POST['LGD_PAYKEY'])
	alert('결제등록 요청 후 주문해 주십시오.');

// 장바구니가 비어있는가?
if (get_session("ss_direct"))
    $tmp_cart_id = get_session('ss_cart_direct');
else
    $tmp_cart_id = get_session('ss_cart_id');

if (get_cart_count($tmp_cart_id) == 0)// 장바구니에 담기
    alert('장바구니가 비어 있습니다.\\n\\n이미 주문하셨거나 장바구니에 담긴 상품이 없는 경우입니다.', G5_SHOP_URL.'/cart.php');

$page_return_url = G5_SHOP_URL.'/orderform.php';
if(get_session('ss_direct'))
    $page_return_url .= '?sw_direct=1';

$posted_order_token = isset($_POST['order_token']) ? trim((string)$_POST['order_token']) : '';
$session_order_token = (string)get_session('ss_order_token');
$is_valid_order_token = false;
if ($posted_order_token !== '' && $session_order_token !== '') {
    if (function_exists('hash_equals')) {
        $is_valid_order_token = hash_equals($session_order_token, $posted_order_token);
    } else {
        $is_valid_order_token = ($session_order_token === $posted_order_token);
    }
}
if (!$is_valid_order_token) {
    alert('토큰 에러가 발생했습니다. 페이지를 새로고침 후 다시 시도해 주세요. (ERR-TOKEN)', $page_return_url);
}
set_session('ss_order_token', '');

$checkout_idempotency_key = isset($_POST['idempotency_key']) ? trim((string)$_POST['idempotency_key']) : '';
$checkout_idem_session_key = '';
if ($checkout_idempotency_key !== '' && preg_match('/^[a-f0-9]{32}$/', $checkout_idempotency_key)) {
    $checkout_idem_session_key = 'oi_idem_checkout_' . $checkout_idempotency_key;
}

if ($checkout_idem_session_key === '') {
    alert('요청 식별키가 올바르지 않습니다.\\n페이지를 새로고침 후 다시 시도해 주세요. (ERR-IDEM)', $page_return_url);
}

$checkout_idem_state = get_session($checkout_idem_session_key);
if ($checkout_idem_state === 'done') {
    alert('이미 처리된 주문요청입니다.', G5_SHOP_URL.'/orderinquiry.php');
}
if ($checkout_idem_state === 'pending') {
    alert('동일 주문요청이 처리 중입니다. 잠시 후 다시 시도해 주세요. (ERR-IDEMPENDING)', $page_return_url);
}

$error = "";
// 장바구니 상품 재고 검사
$sql = " select it_id,
                ct_qty,
                it_name,
                io_id,
                io_type,
                ct_option
           from {$g5['g5_shop_cart_table']}
          where od_id = '$tmp_cart_id'
            and ct_select = '1' ";
$result = sql_query($sql);
for ($i=0; $row=sql_fetch_array($result); $i++)
{
    if(function_exists('is_item_permanently_locked') && is_item_permanently_locked($row['it_id'])) {
        if(function_exists('sync_item_permanent_soldout')) {
            sync_item_permanent_soldout($row['it_id']);
        }
        $error .= "{$row['it_name']} 은(는) 결제완료 이력이 있는 고유 식별상품으로 재판매할 수 없습니다.\\n\\n";
        alert($error, $page_return_url);
    }

    // 상품에 대한 현재고수량
    if($row['io_id']) {
        $it_stock_qty = (float)get_option_stock_qty($row['it_id'], $row['io_id'], $row['io_type']);
    } else {
        $it_stock_qty = (float)get_it_stock_qty($row['it_id']);
    }
    // 장바구니 수량이 재고수량보다 많다면 오류
    if ($row['ct_qty'] > $it_stock_qty) {
        $error .= "{$row['ct_option']} 의 재고수량이 부족합니다. 현재고수량 : $it_stock_qty 개\\n\\n";
        alert($error, $page_return_url);
    }
}

if($i == 0)
    alert('장바구니가 비어 있습니다.\\n\\n이미 주문하셨거나 장바구니에 담긴 상품이 없는 경우입니다.', G5_SHOP_URL.'/cart.php');

if ($error != "")
{
    $error .= "다른 고객님께서 {$od_name}님 보다 먼저 주문하신 경우입니다. 불편을 끼쳐 죄송합니다.";
    alert($error, $page_return_url);
}

$i_price     = round($_POST['od_price']);
$i_send_cost  = round($_POST['od_send_cost']);
$i_send_cost2  = round($_POST['od_send_cost2']);
$i_send_coupon  = abs(round($_POST['od_send_coupon']));
$i_temp_point = round($_POST['od_temp_point']);

$post_cp_id_list = (isset($_POST['cp_id']) && is_array($_POST['cp_id'])) ? array_map('intval', $_POST['cp_id']) : array();
$post_it_id_list = array();
if (isset($_POST['it_id']) && is_array($_POST['it_id'])) {
    foreach ($_POST['it_id'] as $v) {
        $post_it_id_list[] = preg_replace('/[^A-Za-z0-9_\-]/', '', (string)$v);
    }
}
$post_od_cp_id = isset($_POST['od_cp_id']) ? (int)$_POST['od_cp_id'] : 0;
$post_sc_cp_id = isset($_POST['sc_cp_id']) ? (int)$_POST['sc_cp_id'] : 0;

$contract_days_expr = "(ct_qty + (ct_qty_hour / 24))";
$contract_hours_expr = "((ct_qty * 24) + ct_qty_hour)";
$ct_1_exists = sql_fetch(" SHOW COLUMNS FROM {$g5['g5_shop_cart_table']} LIKE 'ct_1' ");
$contract_extra_expr = $ct_1_exists ? " + IFNULL(ct_1, 0)" : "";


// 주문금액이 상이함
$sql = "SELECT
            COALESCE(SUM(
                IF(io_type = 1,
					(IFNULL(io_price, 0) * {$contract_hours_expr}) + IFNULL(ct_install_price, 0){$contract_extra_expr},
					((IFNULL(ct_price, 0) + IFNULL(io_price, 0)) * {$contract_hours_expr}) + IFNULL(ct_install_price, 0){$contract_extra_expr}
                )
            ), 0) AS od_price,
            COUNT(DISTINCT it_id) AS cart_count
        FROM {$g5['g5_shop_cart_table']}
        WHERE od_id = '$tmp_cart_id'
          AND ct_select = '1'";

$row = sql_fetch($sql);
$row['od_price'] = round($row['od_price']); // 소수점 이하 반올림 하기 위해 round 처리 JSLEE
$tot_ct_price = $row['od_price'];
$cart_count = $row['cart_count'];
$tot_od_price = $tot_ct_price;

// 쿠폰금액계산
$tot_cp_price = 0;
if($is_member) {
    // 상품쿠폰
    $tot_it_cp_price = $tot_od_cp_price = 0;
    $it_cp_cnt = count($post_cp_id_list);
    $arr_it_cp_prc = array();
    for($i=0; $i<$it_cp_cnt; $i++) {
        $cid = (int)$post_cp_id_list[$i];
        $it_id = isset($post_it_id_list[$i]) ? $post_it_id_list[$i] : '';
        if ($it_id === '') {
            continue;
        }
        $sql = " select cp_id, cp_method, cp_target, cp_type, cp_price, cp_trunc, cp_minimum, cp_maximum
                    from {$g5['g5_shop_coupon_table']}
                    where cp_id = '$cid'
                      and mb_id IN ( '{$member['mb_id']}', '전체회원' )
                      and cp_start <= '".G5_TIME_YMD."'
                      and cp_end >= '".G5_TIME_YMD."'
                      and cp_method IN ( 0, 1 ) ";
        $cp = sql_fetch($sql);
        if(!$cp['cp_id'])
            continue;

        // 사용한 쿠폰인지
        if(is_used_coupon($member['mb_id'], $cp['cp_id']))
            continue;

        // 분류할인인지
        if($cp['cp_method']) {
            $sql2 = " select it_id, ca_id, ca_id2, ca_id3
                        from {$g5['g5_shop_item_table']}
                        where it_id = '$it_id' ";
            $row2 = sql_fetch($sql2);

            if(!$row2['it_id'])
                continue;

            if($row2['ca_id'] != $cp['cp_target'] && $row2['ca_id2'] != $cp['cp_target'] && $row2['ca_id3'] != $cp['cp_target'])
                continue;
        } else {
            if($cp['cp_target'] != $it_id)
                continue;
        }

        // 상품금액
        $sql = "SELECT COALESCE(SUM(
                            IF(io_type = '1',
								(IFNULL(io_price, 0) * {$contract_hours_expr}) + IFNULL(ct_install_price, 0){$contract_extra_expr},
								((IFNULL(ct_price, 0) + IFNULL(io_price, 0)) * {$contract_hours_expr}) + IFNULL(ct_install_price, 0){$contract_extra_expr}
                            )
                        ), 0) AS sum_price
                        FROM {$g5['g5_shop_cart_table']}
                        WHERE od_id = '$tmp_cart_id'
                            AND it_id = '$it_id'
                            AND ct_select = '1'";
        $ct = sql_fetch($sql);
        $item_price = $ct['sum_price'];

        if($cp['cp_minimum'] > $item_price)
            continue;

        $dc = 0;
        if($cp['cp_type']) {
            $dc = floor(($item_price * ($cp['cp_price'] / 100)) / $cp['cp_trunc']) * $cp['cp_trunc'];
        } else {
            $dc = $cp['cp_price'];
        }

        if($cp['cp_maximum'] && $dc > $cp['cp_maximum'])
            $dc = $cp['cp_maximum'];

        if($item_price < $dc)
            continue;

        $tot_it_cp_price += $dc;
        $arr_it_cp_prc[$it_id] = $dc;
    }

    $tot_od_price -= $tot_it_cp_price;

    // 주문쿠폰
        if($post_od_cp_id > 0) {
        $sql = " select cp_id, cp_type, cp_price, cp_trunc, cp_minimum, cp_maximum
                    from {$g5['g5_shop_coupon_table']}
                                        where cp_id = '{$post_od_cp_id}'
                      and mb_id IN ( '{$member['mb_id']}', '전체회원' )
                      and cp_start <= '".G5_TIME_YMD."'
                      and cp_end >= '".G5_TIME_YMD."'
                      and cp_method = '2' ";
        $cp = sql_fetch($sql);

        // 사용한 쿠폰인지
        $cp_used = is_used_coupon($member['mb_id'], $cp['cp_id']);

        $dc = 0;
        if(!$cp_used && $cp['cp_id'] && ($cp['cp_minimum'] <= $tot_od_price)) {
            if($cp['cp_type']) {
                $dc = floor(($tot_od_price * ($cp['cp_price'] / 100)) / $cp['cp_trunc']) * $cp['cp_trunc'];
            } else {
                $dc = $cp['cp_price'];
            }

            if($cp['cp_maximum'] && $dc > $cp['cp_maximum'])
                $dc = $cp['cp_maximum'];

            if($tot_od_price < $dc)
                die('Order coupon error.');

            $tot_od_cp_price = $dc;
            $tot_od_price -= $tot_od_cp_price;
        }
    }

    $tot_cp_price = $tot_it_cp_price + $tot_od_cp_price;
}

if (round(($row['od_price'] - $tot_cp_price),6) !== round($i_price,6)) {
    die("Error.|"."od_price=".$row['od_price']."|tot_cp_price=".$tot_cp_price."|i_price=".$i_price);
}

// 배송비가 상이함
$send_cost = get_sendcost($tmp_cart_id);

$tot_sc_cp_price = 0;
if($is_member && $send_cost > 0) {
    // 배송쿠폰
        if($post_sc_cp_id > 0) {
        $sql = " select cp_id, cp_type, cp_price, cp_trunc, cp_minimum, cp_maximum
                    from {$g5['g5_shop_coupon_table']}
                                        where cp_id = '{$post_sc_cp_id}'
                      and mb_id IN ( '{$member['mb_id']}', '전체회원' )
                      and cp_start <= '".G5_TIME_YMD."'
                      and cp_end >= '".G5_TIME_YMD."'
                      and cp_method = '3' ";
        $cp = sql_fetch($sql);

        // 사용한 쿠폰인지
        $cp_used = is_used_coupon($member['mb_id'], $cp['cp_id']);

        $dc = 0;
        if(!$cp_used && $cp['cp_id'] && ($cp['cp_minimum'] <= $tot_od_price)) {
            if($cp['cp_type']) {
                $dc = floor(($send_cost * ($cp['cp_price'] / 100)) / $cp['cp_trunc']) * $cp['cp_trunc'];
            } else {
                $dc = $cp['cp_price'];
            }

            if($cp['cp_maximum'] && $dc > $cp['cp_maximum'])
                $dc = $cp['cp_maximum'];

            if($dc > $send_cost)
                $dc = $send_cost;

            $tot_sc_cp_price = $dc;
        }
    }
}

if (round((float)($send_cost - $tot_sc_cp_price),6) !== round((float)($i_send_cost - $i_send_coupon),6)) {
    die("Error..");
}

// 추가배송비가 상이함
$od_b_zip   = preg_replace('/[^0-9]/', '', $od_b_zip);
$od_b_zip1  = substr($od_b_zip, 0, 3);
$od_b_zip2  = substr($od_b_zip, 3);
$zipcode = $od_b_zip;
$sql = " select sc_id, sc_price from {$g5['g5_shop_sendcost_table']} where sc_zip1 <= '$zipcode' and sc_zip2 >= '$zipcode' ";
$tmp = sql_fetch($sql);
if(!$tmp['sc_id'])
    $send_cost2 = 0;
else
    $send_cost2 = (float)$tmp['sc_price'];
if(round($send_cost2,6) !== round($i_send_cost2,6))
    die("Error...");

// 결제포인트가 상이함
// 회원이면서 포인트사용이면
$temp_point = 0;
if ($is_member && $config['cf_use_point'])
{
    if($member['mb_point'] >= $default['de_settle_min_point']) {
        $temp_point = (float)$default['de_settle_max_point'];

        if($temp_point > (float)$tot_od_price)
            $temp_point = (float)$tot_od_price;

        if($temp_point > (float)$member['mb_point'])
            $temp_point = (float)$member['mb_point'];

        $point_unit = (float)$default['de_settle_point_unit'];
        $temp_point = (float)((float)($temp_point / $point_unit) * $point_unit);
    }
}

if ($od_settle_case == "포인트")
{
	$temp_order_point = round($i_price + $i_send_cost + $i_send_cost2 - $i_send_coupon,0);
	if($temp_order_point != $i_temp_point)
        alert('결제하실 금액과 포인트가 일치하지 않습니다!'."i_price=" . $i_price .".i_send_cost=" . $i_send_cost . ".i_send_cost2=" . $i_send_cost2 . "-i_send_coupon" . $i_send_coupon . " [temp_order_point]=" . $temp_order_point . " [i_temp_point]=" . $i_temp_point, $page_return_url);

} else {
	if (($i_temp_point > (float)$temp_point || $i_temp_point < 0) && $config['cf_use_point'])
		die("Error....");
}

if ($od_temp_point)
{
    if ($member['mb_point'] < $od_temp_point)
        alert('회원님의 포인트가 부족하여 포인트로 결제 할 수 없습니다.', $page_return_url);
}

$i_price = round($i_price + $i_send_cost + $i_send_cost2 - $i_temp_point - $i_send_coupon,0);
$order_price = round($tot_od_price + $send_cost + $send_cost2 - $tot_sc_cp_price - $od_temp_point,0);

$od_status = '주문';
$od_tno    = '';
if ($od_settle_case == "무통장" || $od_settle_case == "포인트")
{
    $od_receipt_point   = $i_temp_point;
    $od_receipt_price   = 0;
    $od_misu            = $i_price - $od_receipt_price;
    if($od_misu == 0) {
        $od_status      = '입금';
        $od_receipt_time = G5_TIME_YMDHIS;
    }
}
else if ($od_settle_case == "계좌이체")
{
    switch($default['de_pg_service']) {
        case 'lg':
            include G5_SHOP_PATH.'/lg/xpay_result.php';
            break;
        case 'inicis':
            include G5_SHOP_PATH.'/inicis/inistdpay_result.php';
            break;
		default:
            include G5_SHOP_PATH.'/kcp/pp_ax_hub.php';
            $bank_name  = iconv("cp949", "utf-8", $bank_name);
            break;
    }

    $od_tno             = $tno;
    $od_receipt_price   = $amount;
    $od_receipt_point   = $i_temp_point;
    $od_receipt_time    = preg_replace("/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/", "\\1-\\2-\\3 \\4:\\5:\\6", $app_time);
    $od_bank_account    = $od_settle_case;
    $od_deposit_name    = $od_name;
    $od_bank_account    = $bank_name;
    $pg_price           = $amount;
    $od_misu            = $i_price - $od_receipt_price;
    if($od_misu == 0)
        $od_status      = '입금';
}
else if ($od_settle_case == "가상계좌")
{
    switch($default['de_pg_service']) {
        case 'lg':
            include G5_SHOP_PATH.'/lg/xpay_result.php';
            break;
        case 'inicis':
            include G5_SHOP_PATH.'/inicis/inistdpay_result.php';
			$od_app_no = $app_no;
            break;
		default:
            include G5_SHOP_PATH.'/kcp/pp_ax_hub.php';
            $bankname   = iconv("cp949", "utf-8", $bankname);
            $depositor  = iconv("cp949", "utf-8", $depositor);
            break;
    }

    $od_receipt_point   = $i_temp_point;
    $od_tno             = $tno;
	$od_receipt_price   = 0;
    $od_bank_account    = $bankname.' '.$account;
    $od_deposit_name    = $depositor;
    $pg_price           = $amount;
    $od_misu            = $i_price - $od_receipt_price;
}
else if ($od_settle_case == "휴대폰")
{
    switch($default['de_pg_service']) {
        case 'lg':
            include G5_SHOP_PATH.'/lg/xpay_result.php';
            break;
        case 'inicis':
            include G5_SHOP_PATH.'/inicis/inistdpay_result.php';
            break;
		default:
            include G5_SHOP_PATH.'/kcp/pp_ax_hub.php';
            break;
    }

    $od_tno             = $tno;
    $od_receipt_price   = $amount;
    $od_receipt_point   = $i_temp_point;
    $od_receipt_time    = preg_replace("/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/", "\\1-\\2-\\3 \\4:\\5:\\6", $app_time);
    $od_bank_account    = $commid . ($commid ? ' ' : '').$mobile_no;
    $pg_price           = $amount;
    $od_misu            = $i_price - $od_receipt_price;
    if($od_misu == 0)
        $od_status      = '입금';
}
else if ($od_settle_case == "신용카드")
{
    switch($default['de_pg_service']) {
        case 'lg':
            include G5_SHOP_PATH.'/lg/xpay_result.php';
            break;
        case 'inicis':
            include G5_SHOP_PATH.'/inicis/inistdpay_result.php';
            break;
		default:
            include G5_SHOP_PATH.'/kcp/pp_ax_hub.php';
            $card_name  = iconv("cp949", "utf-8", $card_name);
            break;
    }

    $od_tno             = $tno;
    $od_app_no          = $app_no;
    $od_receipt_price   = $amount;
    $od_receipt_point   = $i_temp_point;
    $od_receipt_time    = preg_replace("/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/", "\\1-\\2-\\3 \\4:\\5:\\6", $app_time);
    $od_bank_account    = $card_name;
    $pg_price           = $amount;
    $od_misu            = $i_price - $od_receipt_price;
    if($od_misu == 0)
        $od_status      = '입금';
}
else if ($od_settle_case == "간편결제" || ($od_settle_case == "lpay" && $default['de_pg_service'] === 'inicis') )
{
    switch($default['de_pg_service']) {
        case 'lg':
            include G5_SHOP_PATH.'/lg/xpay_result.php';
            break;
        case 'inicis':
            include G5_SHOP_PATH.'/inicis/inistdpay_result.php';
            break;
		default:
            include G5_SHOP_PATH.'/kcp/pp_ax_hub.php';
            $card_name  = iconv("cp949", "utf-8", $card_name);
            break;
    }

    $od_tno             = $tno;
    $od_app_no          = $app_no;
    $od_receipt_price   = $amount;
    $od_receipt_point   = $i_temp_point;
    $od_receipt_time    = preg_replace("/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/", "\\1-\\2-\\3 \\4:\\5:\\6", $app_time);
    $od_bank_account    = $card_name;
    $pg_price           = $amount;
    $od_misu            = $i_price - $od_receipt_price;
    if($od_misu == 0)
        $od_status      = '입금';
}
else if ($od_settle_case == "KAKAOPAY")
{
    include G5_SHOP_PATH.'/kakaopay/kakaopay_result.php';

    $od_tno             = $tno;
    $od_app_no          = $app_no;
    $od_receipt_price   = $amount;
    $od_receipt_point   = $i_temp_point;
    $od_receipt_time    = preg_replace("/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/", "\\1-\\2-\\3 \\4:\\5:\\6", $app_time);
    $od_bank_account    = $card_name;
    $pg_price           = $amount;
    $od_misu            = $i_price - $od_receipt_price;
    if($od_misu == 0)
        $od_status      = '입금';
}
else
{
    die("od_settle_case Error!!!");
}

$od_pg = $default['de_pg_service'];
if($od_settle_case == 'KAKAOPAY')
    $od_pg = 'KAKAOPAY';

// 주문금액과 결제금액이 일치하는지 체크
if($tno) {
    if((float)$order_price !== (float)$pg_price) {
        $cancel_msg = '결제금액 불일치';
        switch($od_pg) {
            case 'lg':
                include G5_SHOP_PATH.'/lg/xpay_cancel.php';
                break;
            case 'inicis':
                include G5_SHOP_PATH.'/inicis/inipay_cancel.php';
                break;
            case 'KAKAOPAY':
                $_REQUEST['TID']               = $tno;
                $_REQUEST['Amt']               = $amount;
                $_REQUEST['CancelMsg']         = $cancel_msg;
                $_REQUEST['PartialCancelCode'] = 0;
                include G5_SHOP_PATH.'/kakaopay/kakaopay_cancel.php';
                break;
			default:
                include G5_SHOP_PATH.'/kcp/pp_ax_hub_cancel.php';
                break;
        }

        die("Receipt Amount Error");
    }
}

if ($is_member)
    $od_pwd = $member['mb_password'];
else
    $od_pwd = get_encrypt_string($_POST['od_pwd']);

// 주문번호를 얻는다.
$od_id = get_session('ss_order_id');
if(!$od_id) {
    alert('주문번호가 없습니다. 다시 시도해 주세요. (ERR-ODID)', $page_return_url);
}

set_session($checkout_idem_session_key, 'pending');
$checkout_tx_started = false;
sql_query("START TRANSACTION");
$checkout_tx_started = true;
sql_query(" SELECT ct_id FROM {$g5['g5_shop_cart_table']} WHERE od_id = '$tmp_cart_id' AND ct_select = '1' FOR UPDATE ", false);
if ($is_member && isset($member['mb_id']) && $member['mb_id'] !== '') {
    $mb_id_lock = sql_escape_string($member['mb_id']);
    sql_fetch(" SELECT mb_id FROM {$g5['member_table']} WHERE mb_id = '{$mb_id_lock}' FOR UPDATE ");
}

$od_escrow = 0;
if($escw_yn == 'Y')
    $od_escrow = 1;

// 복합과세 금액
$od_tax_mny = round($i_price / 1.1);
$od_vat_mny = $i_price - $od_tax_mny;
$od_free_mny = 0;
if($default['de_tax_flag_use']) {
    $od_tax_mny = (float)$_POST['comm_tax_mny'];
    $od_vat_mny = (float)$_POST['comm_vat_mny'];
    $od_free_mny = (float)$_POST['comm_free_mny'];
}

$od_email         = get_email_address($od_email);
$od_name          = clean_xss_tags($od_name);
$od_tel           = clean_xss_tags($od_tel);
$od_hp            = clean_xss_tags($od_hp);
$od_sns_name      = clean_xss_tags($od_sns_name);
$od_sns_id        = clean_xss_tags($od_sns_id);
$od_zip           = preg_replace('/[^0-9]/', '', $od_zip);
$od_zip1          = substr($od_zip, 0, 3);
$od_zip2          = substr($od_zip, 3);
$od_addr1         = clean_xss_tags($od_addr1);
$od_addr2         = clean_xss_tags($od_addr2);
$od_addr3         = clean_xss_tags($od_addr3);
$od_addr_jibeon   = preg_match("/^(N|R)$/", $od_addr_jibeon) ? $od_addr_jibeon : '';
$od_b_name        = clean_xss_tags($od_b_name);
$od_b_tel         = clean_xss_tags($od_b_tel);
$od_b_hp          = clean_xss_tags($od_b_hp);
$od_b_addr1       = clean_xss_tags($od_b_addr1);
$od_b_addr2       = clean_xss_tags($od_b_addr2);
$od_b_addr3       = clean_xss_tags($od_b_addr3);
$od_b_addr_jibeon = preg_match("/^(N|R)$/", $od_b_addr_jibeon) ? $od_b_addr_jibeon : '';
$od_memo          = clean_xss_tags($od_memo);
$od_deposit_name  = clean_xss_tags($od_deposit_name);
$od_tax_flag      = $default['de_tax_flag_use'];

// 주문서에 입력
$sql = " insert {$g5['g5_shop_order_table']}
            set od_id             = '$od_id',
                mb_id             = '{$member['mb_id']}',
                od_pwd            = '$od_pwd',
                od_name           = '$od_name',
                od_email          = '$od_email',
                od_tel            = '$od_tel',
                od_hp             = '$od_hp',
                od_sns_name       = '$od_sns_name',
                od_sns_id         = '$od_sns_id',
                od_zip1           = '$od_zip1',
                od_zip2           = '$od_zip2',
                od_addr1          = '$od_addr1',
                od_addr2          = '$od_addr2',
                od_addr3          = '$od_addr3',
                od_addr_jibeon    = '$od_addr_jibeon',
                od_b_name         = '$od_b_name',
                od_b_tel          = '$od_b_tel',
                od_b_hp           = '$od_b_hp',
                od_b_zip1         = '$od_b_zip1',
                od_b_zip2         = '$od_b_zip2',
                od_b_addr1        = '$od_b_addr1',
                od_b_addr2        = '$od_b_addr2',
                od_b_addr3        = '$od_b_addr3',
                od_b_addr_jibeon  = '$od_b_addr_jibeon',
                od_deposit_name   = '$od_deposit_name',
                od_memo           = '$od_memo',
                od_cart_count     = '$cart_count',
                od_cart_price     = '$tot_ct_price',
                od_cart_coupon    = '$tot_it_cp_price',
                od_send_cost      = '$od_send_cost',
                od_send_coupon    = '$tot_sc_cp_price',
                od_send_cost2     = '$od_send_cost2',
                od_coupon         = '$tot_od_cp_price',
                od_receipt_price  = '$od_receipt_price',
                od_receipt_point  = '$od_receipt_point',
                od_bank_account   = '$od_bank_account',
                od_receipt_time   = '$od_receipt_time',
                od_misu           = '$od_misu',
                od_pg             = '$od_pg',
                od_tno            = '$od_tno',
                od_app_no         = '$od_app_no',
                od_escrow         = '$od_escrow',
                od_tax_flag       = '$od_tax_flag',
                od_tax_mny        = '$od_tax_mny',
                od_vat_mny        = '$od_vat_mny',
                od_free_mny       = '$od_free_mny',
                od_status         = '$od_status',
                od_shop_memo      = '',
                od_hope_date      = '$od_hope_date',
                od_time           = '".G5_TIME_YMDHIS."',
                od_ip             = '$REMOTE_ADDR',
                od_settle_case    = '$od_settle_case',
                od_test           = '{$default['de_card_test']}'
                ";
$result = sql_query($sql, false);

if($result && function_exists('mark_order_items_permanent_soldout')) {
    mark_order_items_permanent_soldout($od_id);
}

// 주문정보 입력 오류시 결제 취소
if(!$result) {
    if($checkout_tx_started) {
        sql_query("ROLLBACK", false);
        $checkout_tx_started = false;
    }
    set_session($checkout_idem_session_key, '');
    if($tno) {
        $cancel_msg = '주문정보 입력 오류';
        switch($od_pg) {
            case 'lg':
                include G5_SHOP_PATH.'/lg/xpay_cancel.php';
                break;
            case 'inicis':
                include G5_SHOP_PATH.'/inicis/inipay_cancel.php';
                break;
            case 'KAKAOPAY':
                $_REQUEST['TID']               = $tno;
                $_REQUEST['Amt']               = $amount;
                $_REQUEST['CancelMsg']         = $cancel_msg;
                $_REQUEST['PartialCancelCode'] = 0;
                include G5_SHOP_PATH.'/kakaopay/kakaopay_cancel.php';
                break;
			default:
                include G5_SHOP_PATH.'/kcp/pp_ax_hub_cancel.php';
                break;
        }
    }

    // 관리자에게 오류 알림 메일발송
    $error = 'order';
    include G5_SHOP_PATH.'/ordererrormail.php';

    die('<p>고객님의 주문 정보를 처리하는 중 오류가 발생해서 주문이 완료되지 않았습니다.</p><p>'.strtoupper($od_pg).'를 이용한 전자결제(신용카드, 계좌이체, 가상계좌 등)은 자동 취소되었습니다.');
}

// 장바구니 상태변경
// 신용카드로 주문하면서 신용카드 포인트 사용하지 않는다면 포인트 부여하지 않음
$cart_status = $od_status;
$sql_card_point = "";
if ($od_receipt_price > 0 && !$default['de_card_point']) {
    $sql_card_point = " , ct_point = '0' ";
}

$sql = "update {$g5['g5_shop_cart_table']}
set od_id = '$od_id',
    ct_status = '$cart_status'
    $sql_card_point
where od_id = '$tmp_cart_id'
and ct_select = '1' ";
$result = sql_query($sql, false);

// 주문정보 입력 오류시 결제 취소
if(!$result) {
    if($checkout_tx_started) {
        sql_query("ROLLBACK", false);
        $checkout_tx_started = false;
    }
    set_session($checkout_idem_session_key, '');
    if($tno) {
        $cancel_msg = '주문상태 변경 오류';
        switch($od_pg) {
            case 'lg':
                include G5_SHOP_PATH.'/lg/xpay_cancel.php';
                break;
            case 'inicis':
                include G5_SHOP_PATH.'/inicis/inipay_cancel.php';
                break;
            case 'KAKAOPAY':
                $_REQUEST['TID']               = $tno;
                $_REQUEST['Amt']               = $amount;
                $_REQUEST['CancelMsg']         = $cancel_msg;
                $_REQUEST['PartialCancelCode'] = 0;
                include G5_SHOP_PATH.'/kakaopay/kakaopay_cancel.php';
                break;
			default:
                include G5_SHOP_PATH.'/kcp/pp_ax_hub_cancel.php';
                break;
        }
    }

    // 관리자에게 오류 알림 메일발송
    $error = 'status';
    include G5_SHOP_PATH.'/ordererrormail.php';

    // 주문삭제
    sql_query(" delete from {$g5['g5_shop_order_table']} where od_id = '$od_id' ");

    die('<p>고객님의 주문 정보를 처리하는 중 오류가 발생해서 주문이 완료되지 않았습니다.</p><p>'.strtoupper($od_pg).'를 이용한 전자결제(신용카드, 계좌이체, 가상계좌 등)은 자동 취소되었습니다.');
}

// 회원이면서 포인트를 사용했다면 테이블에 사용을 추가
if ($is_member && $od_receipt_point)
    insert_point($member['mb_id'], (-1) * $od_receipt_point, "주문번호 $od_id 결제");

$od_memo = nl2br(htmlspecialchars2(stripslashes($od_memo))) . "&nbsp;";

// 쿠폰사용내역기록
if($is_member) {
    $it_cp_cnt = count($post_cp_id_list);
    for($i=0; $i<$it_cp_cnt; $i++) {
        $cid = (int)$post_cp_id_list[$i];
        $cp_it_id = isset($post_it_id_list[$i]) ? $post_it_id_list[$i] : '';
        if ($cp_it_id === '') {
            continue;
        }
        $cp_prc = (float)$arr_it_cp_prc[$cp_it_id];

        if(trim($cid)) {
            $sql = " insert into {$g5['g5_shop_coupon_log_table']}
                        set cp_id       = '$cid',
                            mb_id       = '{$member['mb_id']}',
                            od_id       = '$od_id',
                            cp_price    = '$cp_prc',
                            cl_datetime = '".G5_TIME_YMDHIS."' ";
            sql_query($sql);
        }

        // 쿠폰사용금액 cart에 기록
        $cp_prc = (float)$arr_it_cp_prc[$cp_it_id];
        $sql = " update {$g5['g5_shop_cart_table']}
                    set cp_price = '$cp_prc'
                    where od_id = '$od_id'
                      and it_id = '$cp_it_id'
                      and ct_select = '1'
                    order by ct_id asc
                    limit 1 ";
        sql_query($sql);
    }

    if($post_od_cp_id > 0) {
        $sql = " insert into {$g5['g5_shop_coupon_log_table']}
                    set cp_id       = '{$post_od_cp_id}',
                        mb_id       = '{$member['mb_id']}',
                        od_id       = '$od_id',
                        cp_price    = '$tot_od_cp_price',
                        cl_datetime = '".G5_TIME_YMDHIS."' ";
        sql_query($sql);
    }

    if($post_sc_cp_id > 0) {
        $sql = " insert into {$g5['g5_shop_coupon_log_table']}
                    set cp_id       = '{$post_sc_cp_id}',
                        mb_id       = '{$member['mb_id']}',
                        od_id       = '$od_id',
                        cp_price    = '$tot_sc_cp_price',
                        cl_datetime = '".G5_TIME_YMDHIS."' ";
        sql_query($sql);
    }
}

// APMS : 주문처리 - 2014.07.21
apms_order($od_id, $od_status, $member['mb_recommend']);

// 쿠폰업데이트
apms_coupon_update($member['mb_id']);

if($checkout_tx_started) {
    sql_query("COMMIT");
    $checkout_tx_started = false;
}
set_session($checkout_idem_session_key, 'done');

// VPN(IKEv2-Client) provisioning queue + immediate attempt
if ($od_status == '입금' && function_exists('vpnlink_ikev2_queue_order')) {
    $ikev2_ret = vpnlink_ikev2_queue_order($od_id, 'shop_orderformupdate');
    if (!$ikev2_ret['ok']) {
        vpnlink_ikev2_log('shop/orderformupdate queue failed: od_id='.$od_id.' error='.(isset($ikev2_ret['error']) ? $ikev2_ret['error'] : 'unknown'));
    }
}

// Paid vpnid_list sync queue + immediate attempt (independent from provisioning result)
if ($od_status == '입금' && function_exists('vpnlink_vpnid_sync_upsert_by_order')) {
    $vpnid_sync_ret = vpnlink_vpnid_sync_upsert_by_order($od_id, '', 'shop_orderformupdate_paid');
    if (empty($vpnid_sync_ret['ok'])) {
        vpnlink_ikev2_log('shop/orderformupdate vpnid sync failed: od_id='.$od_id.' error='.(isset($vpnid_sync_ret['error']) ? $vpnid_sync_ret['error'] : 'unknown'));
    }
}

include_once(G5_SHOP_PATH.'/ordermail1.inc.php');
include_once(G5_SHOP_PATH.'/ordermail2.inc.php');

// SMS BEGIN --------------------------------------------------------
// 주문고객과 쇼핑몰관리자에게 SMS 전송
if($config['cf_sms_use'] && ($default['de_sms_use2'] || $default['de_sms_use3'])) {
    $is_sms_send = false;

    // 충전식일 경우 잔액이 있는지 체크
    if($config['cf_icode_id'] && $config['cf_icode_pw']) {
        $userinfo = get_icode_userinfo($config['cf_icode_id'], $config['cf_icode_pw']);

        if($userinfo['code'] == 0) {
            if($userinfo['payment'] == 'C') { // 정액제
                $is_sms_send = true;
            } else {
                $minimum_coin = 100;
                if(defined('G5_ICODE_COIN'))
                    $minimum_coin = intval(G5_ICODE_COIN);

                if((float)$userinfo['coin'] >= $minimum_coin)
                    $is_sms_send = true;
            }
        }
    }

    if($is_sms_send) {
        $sms_contents = array($default['de_sms_cont2'], $default['de_sms_cont3']);
        $recv_numbers = array($od_hp, $default['de_sms_hp']);
        $send_numbers = array($default['de_admin_company_tel'], $default['de_admin_company_tel']);

        $sms_count = 0;
        $sms_messages = array();

        for($s=0; $s<count($sms_contents); $s++) {
            $sms_content = $sms_contents[$s];
            $recv_number = preg_replace("/[^0-9]/", "", $recv_numbers[$s]);
            $send_number = preg_replace("/[^0-9]/", "", $send_numbers[$s]);

            $sms_content = str_replace("{이름}", $od_name, $sms_content);
            $sms_content = str_replace("{보낸분}", $od_name, $sms_content);
            $sms_content = str_replace("{받는분}", $od_b_name, $sms_content);
            $sms_content = str_replace("{주문번호}", $od_id, $sms_content);
            $sms_content = str_replace("{주문금액}", number_format($tot_ct_price + $od_send_cost + $od_send_cost2), $sms_content);
            $sms_content = str_replace("{회원아이디}", $member['mb_id'], $sms_content);
            $sms_content = str_replace("{회사명}", $default['de_admin_company_name'], $sms_content);

            $idx = 'de_sms_use'.($s + 2);

            if($default[$idx] && $recv_number) {
                $sms_messages[] = array('recv' => $recv_number, 'send' => $send_number, 'cont' => $sms_content);
                $sms_count++;
            }
        }

        // 무통장 입금 때 고객에게 계좌정보 보냄
        if($od_settle_case == '무통장' && $default['de_sms_use2'] && $od_misu > 0) {
            $sms_content = $od_name."님의 입금계좌입니다.\n금액:".number_format($od_misu)."원\n계좌:".$od_bank_account."\n".$default['de_admin_company_name'];

            $recv_number = preg_replace("/[^0-9]/", "", $od_hp);
            $send_number = preg_replace("/[^0-9]/", "", $default['de_admin_company_tel']);

            $sms_messages[] = array('recv' => $recv_number, 'send' => $send_number, 'cont' => $sms_content);
            $sms_count++;
        }

        // SMS 전송
        if($sms_count > 0) {
            if($config['cf_sms_type'] == 'LMS') {
                include_once(G5_LIB_PATH.'/icode.lms.lib.php');

                $port_setting = get_icode_port_type($config['cf_icode_id'], $config['cf_icode_pw']);

                // SMS 모듈 클래스 생성
                if($port_setting !== false) {
                    $SMS = new LMS;
                    $SMS->SMS_con($config['cf_icode_server_ip'], $config['cf_icode_id'], $config['cf_icode_pw'], $port_setting);

                    for($s=0; $s<count($sms_messages); $s++) {
                        $strDest     = array();
                        $strDest[]   = $sms_messages[$s]['recv'];
                        $strCallBack = $sms_messages[$s]['send'];
                        $strCaller   = iconv_euckr(trim($default['de_admin_company_name']));
                        $strSubject  = '';
                        $strURL      = '';
                        $strData     = iconv_euckr($sms_messages[$s]['cont']);
                        $strDate     = '';
                        $nCount      = count($strDest);

                        $res = $SMS->Add($strDest, $strCallBack, $strCaller, $strSubject, $strURL, $strData, $strDate, $nCount);

                        $SMS->Send();
                        $SMS->Init(); // 보관하고 있던 결과값을 지웁니다.
                    }
                }
            } else {
                include_once(G5_LIB_PATH.'/icode.sms.lib.php');

                $SMS = new SMS; // SMS 연결
                $SMS->SMS_con($config['cf_icode_server_ip'], $config['cf_icode_id'], $config['cf_icode_pw'], $config['cf_icode_server_port']);

                for($s=0; $s<count($sms_messages); $s++) {
                    $recv_number = $sms_messages[$s]['recv'];
                    $send_number = $sms_messages[$s]['send'];
                    $sms_content = iconv_euckr($sms_messages[$s]['cont']);

                    $SMS->Add($recv_number, $send_number, $config['cf_icode_id'], $sms_content, "");
                }

                $SMS->Send();
                $SMS->Init(); // 보관하고 있던 결과값을 지웁니다.
            }
        }
    }
}
// SMS END   --------------------------------------------------------

// orderview 에서 사용하기 위해 session에 넣고
$uid = md5($od_id.G5_TIME_YMDHIS.$REMOTE_ADDR);
set_session('ss_orderview_uid', $uid);

// 주문 정보 임시 데이터 삭제
if($od_pg == 'inicis') {
    $sql = " delete from {$g5['g5_shop_order_data_table']} where od_id = '$od_id' and dt_pg = '$od_pg' ";
    sql_query($sql);
}

// 주문번호제거
set_session('ss_order_id', '');

// 기존자료 세션에서 제거
if (get_session('ss_direct'))
    set_session('ss_cart_direct', '');

// 배송지처리 - 받는사람이 있으면 처리
if($is_member && $od_b_name) {
    $sql = " select * from {$g5['g5_shop_order_address_table']}
                where mb_id = '{$member['mb_id']}'
                  and ad_name = '$od_b_name'
                  and ad_tel = '$od_b_tel'
                  and ad_hp = '$od_b_hp'
                  and ad_zip1 = '$od_b_zip1'
                  and ad_zip2 = '$od_b_zip2'
                  and ad_addr1 = '$od_b_addr1'
                  and ad_addr2 = '$od_b_addr2'
                  and ad_addr3 = '$od_b_addr3' ";
    $row = sql_fetch($sql);

    // 기본배송지 체크
    if($ad_default) {
        $sql = " update {$g5['g5_shop_order_address_table']}
                    set ad_default = '0'
                    where mb_id = '{$member['mb_id']}' ";
        sql_query($sql);
    }

    $ad_subject = clean_xss_tags($ad_subject);

    if($row['ad_id']){
        $sql = " update {$g5['g5_shop_order_address_table']}
                      set ad_default = '$ad_default',
                          ad_subject = '$ad_subject',
                          ad_jibeon  = '$od_b_addr_jibeon'
                    where mb_id = '{$member['mb_id']}'
                      and ad_id = '{$row['ad_id']}' ";
    } else {
        $sql = " insert into {$g5['g5_shop_order_address_table']}
                    set mb_id       = '{$member['mb_id']}',
                        ad_subject  = '$ad_subject',
                        ad_default  = '$ad_default',
                        ad_name     = '$od_b_name',
                        ad_tel      = '$od_b_tel',
                        ad_hp       = '$od_b_hp',
                        ad_zip1     = '$od_b_zip1',
                        ad_zip2     = '$od_b_zip2',
                        ad_addr1    = '$od_b_addr1',
                        ad_addr2    = '$od_b_addr2',
                        ad_addr3    = '$od_b_addr3',
                        ad_jibeon   = '$od_b_addr_jibeon' ";
    }

    sql_query($sql);
}

// Push - 최고관리자에게 보냄 ---------------------------------------
	$mb_list = $config['cf_admin'].','.$config['as_admin'];
	$push = array(
		'use'=>'od',
		'flag'=>'new',
		'od_name'=>$od_name,
		'od_id'=>$od_id,
		'od_amount'=>($tot_ct_price + $od_send_cost + $od_send_cost2),
		'od_status'=>$od_status,
		'od_memo'=>$od_memo);
	apms_push($mb_list, $od_id, $od_id, G5_URL, $push);
// ------------------------------------------------------------------
?>

<?php
// ct_status 데이터값이 '입금'일때는 shop_item 테이블의 it_soldout 값을 1로 세팅하여 품절상태로 만들어서 다른 고객이 중복주문 하지 않도록 해 둠 JSLEE
if ($cart_status == "입금" || $cart_status == "완료") {

    // {$g5['g5_shop_cart_table']}의 컬럼명을 가져오는 쿼리
    $sql_columns = "SHOW COLUMNS FROM {$g5['g5_shop_cart_table']}";
    $result_columns = sql_query($sql_columns);

    // 컬럼명을 저장할 배열
    $columns = [];
    while ($row_column = sql_fetch_array($result_columns)) {
        $columns[] = $row_column['Field'];
    }

    $sql2z = "SELECT * FROM {$g5['g5_shop_cart_table']} WHERE od_id = '{$od_id}' AND mb_id = '{$member['mb_id']}' ";
    $result2z = sql_query($sql2z);
    for ($z = 0; $row2z = sql_fetch_array($result2z); $z++) {
        // 구매완료시에는 구매자를 shop_item 에 구매자 정보 기록해 둠
        $it_spec_from_datetime = G5_TIME_YMDHIS;
        //$it_spec_to_datetime = date('Y-m-d H:i:s', strtotime(G5_TIME_YMDHIS . ' +' . $row2z['ct_qty'] . ' days'));
        $it_spec_to_datetime = date('Y-m-d H:i:s', strtotime(G5_TIME_YMDHIS . ' +' . $row2z['ct_qty'] . ' days +' . $row2z['ct_qty_hour'] . ' hours'));
        $it_spec_buyer_mb_id = $row2z['mb_id'];

        $row_this_member = sql_fetch("SELECT mb_name FROM {$g5['member_table']} WHERE mb_id = '{$row2z['mb_id']}'");
        $it_spec_buyer_mb_name = $row_this_member['mb_name'];

        $sql3z = "UPDATE {$g5['g5_shop_item_table']} SET
                        it_soldout = 1,
                        it_spec_from_datetime = '$it_spec_from_datetime',
                        it_spec_from_datetime_org = CASE
                            WHEN it_spec_from_datetime_org IS NULL OR TRIM(it_spec_from_datetime_org) = '' OR it_spec_from_datetime_org = '0000-00-00 00:00:00'
                                THEN '$it_spec_from_datetime'
                            ELSE it_spec_from_datetime_org
                        END,
                        it_spec_to_datetime = '$it_spec_to_datetime',
                        it_spec_to_datetime_org = CASE
                            WHEN it_spec_to_datetime_org IS NULL OR TRIM(it_spec_to_datetime_org) = '' OR it_spec_to_datetime_org = '0000-00-00 00:00:00'
                                THEN '$it_spec_to_datetime'
                            ELSE it_spec_to_datetime_org
                        END,
                        it_spec_buyer_mb_id = '$it_spec_buyer_mb_id',
                        it_spec_buyer_mb_name = '$it_spec_buyer_mb_name'
                  WHERE it_id = '{$row2z['it_id']}'";
        sql_query($sql3z, false);

        // 주문연장카트에도 신규 주문 추가 JSLEE {
        // od_id와 it_id에 대한 존재 여부 확인
        $sql_check = "SELECT COUNT(*) AS cnt FROM {$g5['g5_shop_cart_for_extension_of_period_table']}
            WHERE od_id = '{$row2z['od_id']}' AND it_id = '{$row2z['it_id']}'";
        $row_check = sql_fetch($sql_check);

        if ($row_check['cnt'] > 0) {
            // 기존 레코드가 존재하면 UPDATE (동적 컬럼 업데이트)
            $update_fields = [];
            foreach ($columns as $col) {
                $update_fields[] = "$col = '{$row2z[$col]}'";
            }
            $sql_update = "UPDATE {$g5['g5_shop_cart_for_extension_of_period_table']}
                    SET " . implode(', ', $update_fields) . "
                    WHERE od_id = '{$row2z['od_id']}' AND it_id = '{$row2z['it_id']}'";
            sql_query($sql_update);
        } else {
            // 레코드가 없으면 INSERT (동적 컬럼 삽입)
            $insert_fields = [];
            $insert_values = [];
            foreach ($columns as $col) {
                $insert_fields[] = $col;
                $insert_values[] = "'{$row2z[$col]}'";
            }
            $sql_insert = "INSERT INTO {$g5['g5_shop_cart_for_extension_of_period_table']}
                    (" . implode(', ', $insert_fields) . ")
                    VALUES (" . implode(', ', $insert_values) . ")";
            sql_query($sql_insert);
        }
        // 주문연장카트에도 신규 주문 추가 JSLEE }

    }
}

?>


<?php
// shop_order 테이블의 od_mod_history 업데이트를 위함 JSLEE
// shop_cart 에 연장기록 추가
$result_cart_history = sql_query("SELECT * FROM {$g5['g5_shop_cart_table']} WHERE od_id = '{$od_id}' AND mb_id = '{$member['mb_id']}' AND (ct_status = '입금' OR ct_status = '완료') AND ct_select = '1' ");

for ($i=0; $row_cart_history=sql_fetch_array($result_cart_history); $i++) {

    $row_order_history = sql_fetch(" SELECT * FROM {$g5['g5_shop_order_table']} WHERE od_id = '{$od_id}' AND mb_id = '{$member['mb_id']}' ");
    // 결과가 없는 경우 continue
    if (!$row_order_history) {
        continue;
    }

    // 날짜 재계산하여 변조가 있었을 경우 에러처리
    $row_it_spec_to_datetime = sql_fetch("SELECT it_spec_from_datetime, it_spec_from_datetime_org, it_spec_to_datetime, it_spec_to_datetime_org FROM {$g5['g5_shop_item_table']} WHERE it_id = '{$row_cart_history['it_id']}' AND it_spec_buyer_mb_id = '{$member['mb_id']}' ");
    // 결과가 없는 경우 continue
    if (!$row_it_spec_to_datetime) {
        continue;
    }

    $extension_of_period_date = $row_it_spec_to_datetime['it_spec_from_datetime'];
    $extension_of_period_to_datetime = $row_it_spec_to_datetime['it_spec_to_datetime'];
    $extension_of_period_days = $row_cart_history['ct_qty'];
    $extension_of_period_hours = $row_cart_history['ct_qty_hour'];
    $base_total_hours = apms_contract_hours_from_day_hour((int)$row_cart_history['ct_qty'], (int)$row_cart_history['ct_qty_hour']);
    $base_opt_price = (float)$row_cart_history['ct_price'] + (float)$row_cart_history['io_price'];
    $base_install_price = (float)$row_cart_history['ct_install_price'];
    $base_ct1_price = 0;
    if ($ct_1_exists && isset($row_cart_history['ct_1'])) {
        $base_ct1_price = (float)$row_cart_history['ct_1'];
    }
    $extension_of_period_price = round(($base_opt_price * $base_total_hours) + $base_install_price + $base_ct1_price, 0);
    $od_mod_history = trim($row_order_history['od_mod_history'] . "\n" . G5_TIME_YMDHIS . " 신규계약 (".(int)$row_cart_history['ct_qty']."일".(int)$row_cart_history['ct_qty_hour']."시간) 상품명 RPC-" . $row_cart_history['it_id'] . " 결제 " .  number_format($extension_of_period_price) ." Point" . " (이용자: " . $member['mb_id'] . " / " . $member['mb_name'] .") ");

    // $ct_qty_for_extension_of_period = 0;
    // $ct_qty_hour_for_extension_of_period = 0;
    // $ct_price_for_extension_of_period = 0;

    // shop_cart 에 계약연장 관련기록들 업데이트
    sql_query(" UPDATE {$g5['g5_shop_cart_table']} SET extension_of_period_date = '{$extension_of_period_date}', extension_of_period_to_datetime = '{$extension_of_period_to_datetime}', extension_of_period_days = '{$extension_of_period_days}', extension_of_period_hours = '{$extension_of_period_hours}',  extension_of_period_price = '{$extension_of_period_price}' WHERE od_id = '{$od_id}' AND it_id = '{$row_cart_history['it_id']}' AND mb_id = '{$member['mb_id']}' ");

    // shop_order 에 od_mod_history 업데이트
    sql_query(" UPDATE {$g5['g5_shop_order_table']} SET od_mod_history = '{$od_mod_history}' WHERE od_id = '{$od_id}' AND mb_id = '{$member['mb_id']}' ");

}

?>


<?php
goto_url(G5_SHOP_URL.'/orderinquiryview.php?od_id='.$od_id.'&amp;uid='.$uid);
?>




<html>
    <head>
        <title>주문정보 기록</title>
        <script>
            // 결제 중 새로고침 방지 샘플 스크립트 (중복결제 방지)
            function noRefresh()
            {
                /* CTRL + N키 막음. */
                if ((event.keyCode == 78) && (event.ctrlKey == true))
                {
                    event.keyCode = 0;
                    return false;
                }
                /* F5 번키 막음. */
                if(event.keyCode == 116)
                {
                    event.keyCode = 0;
                    return false;
                }
            }

            document.onkeydown = noRefresh ;
        </script>
    </head>
</html>