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

$member_mb_id_esc = sql_escape_string($member['mb_id']);
$od_id = oi_clean_id($od_id);
$it_id = oi_clean_id($it_id);
$uid = oi_clean_uid($uid);
$check_code2 = trim((string)$check_code2);
$ExtendPeriod_amount = (int)$ExtendPeriod_amount;
$ExtendPeriod_days = (int)$ExtendPeriod_days;
$ExtendPeriod_hours = (int)$ExtendPeriod_hours;
$ExtendPeriod_pricing_unit = isset($_POST['ExtendPeriod_pricing_unit']) ? trim((string)$_POST['ExtendPeriod_pricing_unit']) : 'hour';
$ExtendPeriod_pricing_count = isset($_POST['ExtendPeriod_pricing_count']) ? (int)$_POST['ExtendPeriod_pricing_count'] : 0;
$od_id_esc = oi_sql($od_id);
$it_id_esc = oi_sql($it_id);
$error_redirect_url = ($od_id !== '' && $uid !== '')
    ? (G5_SHOP_URL . "/orderinquiryview.php?od_id={$od_id}&uid={$uid}")
    : G5_SHOP_URL;
$popup_log_fail_options = array('log' => true, 'log_tag' => 'order_extend_fail');
$popup_log_success_options = array('log' => true, 'log_tag' => 'order_extend_success');
$extend_tx_started = false;
$extend_idempotency_key = isset($_POST['idempotency_key']) ? trim((string)$_POST['idempotency_key']) : '';
$extend_idem_session_key = '';
if ($extend_idempotency_key !== '' && preg_match('/^[a-f0-9]{32}$/', $extend_idempotency_key)) {
    $extend_idem_session_key = 'oi_idem_extend_' . $extend_idempotency_key;
}

$extend_fail = function($message, $detail = '') use (&$extend_tx_started, $error_redirect_url, $popup_log_fail_options, &$extend_idem_session_key) {
    if ($extend_tx_started) {
        sql_query("ROLLBACK", false);
        $extend_tx_started = false;
    }
    if ($extend_idem_session_key !== '') {
        set_session($extend_idem_session_key, '');
    }
    oi_fail_popup($message, $detail, $error_redirect_url, '요청 처리 실패', '확인', '요청이 중단되었습니다.', $popup_log_fail_options);
};

if ($od_id === '' || $it_id === '') {
    $extend_fail('잘못된 요청입니다.', '주문정보를 다시 확인해 주세요. (ERR-REQ)');
}

// 세션에 저장된 토큰과 폼으로 넘어온 토큰을 비교하여 틀리면 에러
if ($token && get_session("ss_token") == $token) {
    // 맞으면 세션을 지워 다시 입력폼을 통해서 들어오도록 한다.
    set_session("ss_token", "");
} else {
    set_session("ss_token", "");
    $extend_fail('토큰 에러가 발생했습니다.', '페이지를 새로고침 후 다시 시도해 주세요. (ERR-TOKEN)');
}

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

$extend_idem_state = get_session($extend_idem_session_key);
if ($extend_idem_state === 'done') {
    oi_success_popup('이미 처리된 계약연장 요청입니다.', array(
        "주문번호 : {$od_id}",
        "상품명 : " . $row_item_pricing['it_name'],
        '중복 제출이 감지되어 추가 처리는 수행하지 않았습니다.'
    ), $error_redirect_url, '계약연장 결제 완료', '확인', '이미 처리된 요청입니다.', $popup_log_success_options);
}
if ($extend_idem_state === 'pending') {
    $extend_fail('동일 요청이 처리 중입니다.', '잠시 후 다시 확인해 주세요. (ERR-IDEMPENDING)');
}
set_session($extend_idem_session_key, 'pending');

sql_query("START TRANSACTION");
$extend_tx_started = true;

// name="od_id"  value="<?php echo $od['od_id'];
// name="it_id"  value="<?php echo $item[$i]['it_id'];
// name="ExtendPeriod_amount" id="ExtendPeriod_amount_<?php echo $od_id . "_" . $item[$i]['it_id'];
// name="ExtendPeriod_datetime" id="ExtendPeriod_datetime_<?php echo $od_id . "_" . $item[$i]['it_id'];


$row_member = sql_fetch("SELECT mb_point, mb_today_login FROM {$g5['member_table']} WHERE mb_id = '{$member_mb_id_esc}' FOR UPDATE ");

if (!$row_member || !isset($row_member['mb_today_login'])) {
    $extend_fail('회원정보 조회에 실패했습니다.', '계정정보를 다시 확인해 주세요. (ERR-MEMBER)');
}

$new_check_code2 = md5(md5(md5(md5(md5($it_id."Ž".$member['mb_id']."Ž".$row_member['mb_today_login'])))));

if ($new_check_code2 != $check_code2) {
    $extend_fail('보안 검증에 실패했습니다.', '다시 로그인 후 재시도해 주세요. (ERR-CFLAG)');
}

if (trim($od_id) != "" && trim($it_id) != "" && trim($member['mb_id']) != "" && trim($ExtendPeriod_datetime) != "" && trim($ExtendPeriod_datetime) != "0000-00-00 00:00:00" && (($ExtendPeriod_days > 0 || $ExtendPeriod_hours > 0) || $ExtendPeriod_pricing_count > 0)) {
    $row_order_history = sql_fetch(" SELECT * FROM {$g5['g5_shop_order_table']} WHERE od_id = '{$od_id_esc}' AND mb_id = '{$member_mb_id_esc}' FOR UPDATE ");
    if (!$row_order_history || !isset($row_order_history['od_id'])) {
        $extend_fail('주문번호 확인에 실패했습니다.', '주문번호가 일치하지 않습니다. (ERR-ORDER)');
    }

    $row_cart_history = sql_fetch(" SELECT * FROM {$g5['g5_shop_cart_table']} WHERE od_id = '{$od_id_esc}' AND it_id = '{$it_id_esc}' AND mb_id = '{$member_mb_id_esc}' FOR UPDATE ");
    if (!$row_cart_history || !isset($row_cart_history['od_id'])) {
        $extend_fail('장바구니 주문정보 확인에 실패했습니다.', '주문번호가 일치하지 않습니다. (ERR-CART)');
    }
    $ct_status_locked = isset($row_cart_history['ct_status']) ? trim((string)$row_cart_history['ct_status']) : '';
    if ($ct_status_locked !== '입금' && $ct_status_locked !== '완료') {
        $extend_fail('연장 가능한 주문상태가 아닙니다.', '입금/완료 상태에서만 연장결제가 가능합니다. (ERR-STATUS)');
    }

    // 날짜 재계산하여 변조가 있었을 경우 에러처리
    $row_it_spec_to_datetime = sql_fetch("SELECT it_spec_to_datetime, it_spec_to_datetime_org FROM {$g5['g5_shop_item_table']} WHERE it_id = '{$it_id_esc}' AND it_spec_buyer_mb_id = '{$member_mb_id_esc}' FOR UPDATE ");

    if (!$row_it_spec_to_datetime || trim((string)$row_it_spec_to_datetime['it_spec_to_datetime']) === '') {
        $extend_fail('계약정보 조회에 실패했습니다.', '계약 종료일 정보를 확인할 수 없습니다. (ERR-CONTRACT)');
    }

    $current_expire_datetime = trim((string)$row_it_spec_to_datetime['it_spec_to_datetime']);
    $current_expire_ts = strtotime($current_expire_datetime);
    $payment_base_ts = strtotime(G5_TIME_YMDHIS);
    if ($payment_base_ts === false || $payment_base_ts <= 0) {
        $payment_base_ts = time();
    }
    $extend_base_ts = ($current_expire_ts !== false && $current_expire_ts >= $payment_base_ts)
        ? $current_expire_ts
        : $payment_base_ts;

    $ExtendPeriod_datetime = date("Y-m-d H:i:s", strtotime('+' . (int)$ExtendPeriod_days . ' days +' . (int)$ExtendPeriod_hours . ' hours', $extend_base_ts));

    // shop_item 테이블의 it_id_history 컬럼에 기존 자료 뒤에 줄바꿈한 후 결제일시 주문기간 결제금액 기록 추가
    /*
    $row_it_id_history = sql_fetch("SELECT it_id_history FROM {$g5['g5_shop_item_table']} WHERE it_id = '{$it_id}' AND it_spec_buyer_mb_id = '{$member['mb_id']}' ");
    $new_it_id_history = $row_it_id_history['it_id_history'] . "\n" . G5_TIME_YMDHIS . "|계약연장 {$row_it_spec_to_datetime['it_spec_to_datetime']} + {$ExtendPeriod_days}일|" . $ExtendPeriod_amount;
    sql_query(" UPDATE {$g5['g5_shop_item_table']} SET it_id_history = '{$new_it_id_history}' WHERE it_id = '{$it_id}' AND it_spec_buyer_mb_id = '{$member['mb_id']}' ");
    */

    // 연장 결제금액은 상품상세와 동일하게 이용권 단위/수량 기준으로 서버 재계산
    $row_item_pricing = sql_fetch("SELECT * FROM {$g5['g5_shop_item_table']} WHERE it_id = '{$it_id_esc}' FOR UPDATE ");
    $allowed_units = apms_allowed_pricing_units_from_item($row_item_pricing);
    $valid_units = array('hour', 'day', 'month', 'year');
    if (!in_array($ExtendPeriod_pricing_unit, $valid_units, true) || empty($allowed_units[$ExtendPeriod_pricing_unit])) {
        $ExtendPeriod_pricing_unit = 'hour';
        if (empty($allowed_units['hour'])) {
            foreach ($valid_units as $candidate_unit) {
                if (!empty($allowed_units[$candidate_unit])) {
                    $ExtendPeriod_pricing_unit = $candidate_unit;
                    break;
                }
            }
        }
    }
    if ($ExtendPeriod_pricing_count < 1) {
        $ExtendPeriod_pricing_count = 1;
    }

    // POST 에서 받은 실제 구매 총 일수/시간 저장 (pricing 재계산 전)
    $actual_extend_days  = (int)$ExtendPeriod_days;
    $actual_extend_hours = (int)$ExtendPeriod_hours;
    list($ExtendPeriod_days, $ExtendPeriod_hours) = apms_day_hour_from_pricing_unit($ExtendPeriod_pricing_unit, $ExtendPeriod_pricing_count);
    $extend_total_hours = apms_contract_hours_from_day_hour((int)$ExtendPeriod_days, (int)$ExtendPeriod_hours);
    if ($extend_total_hours < 1) {
        $extend_total_hours = 1;
    }

    $auto_extend_unit = apms_best_pricing_unit_for_hours($row_item_pricing, $extend_total_hours, $ExtendPeriod_pricing_unit);
    if (!in_array($auto_extend_unit, $valid_units, true) || empty($allowed_units[$auto_extend_unit])) {
        $auto_extend_unit = $ExtendPeriod_pricing_unit;
    }

    $auto_extend_count = apms_pricing_count_from_day_hour((int)floor($extend_total_hours / 24), (int)($extend_total_hours % 24), $auto_extend_unit);
    if ($auto_extend_count < 1) {
        $auto_extend_count = 1;
    }

    $extend_hourly_base = apms_item_hourly_base_price($row_item_pricing);
    $extend_package_price = apms_pricing_unit_package_price_by_item($row_item_pricing, $auto_extend_unit, $extend_hourly_base);
    $expected_extend_amount = round((float)$extend_package_price * (int)$auto_extend_count, 0);
    $ExtendPeriod_amount = (int)$expected_extend_amount;
    // 기록용: 실제 구매 일수/시간 복원 (결제금액은 위에서 정확하게 계산됨)
    $ExtendPeriod_days  = $actual_extend_days;
    $ExtendPeriod_hours = $actual_extend_hours;

    if ($ExtendPeriod_amount <= 0) {
        $extend_fail('연장 결제금액이 올바르지 않습니다.', '요금 계산 정보를 다시 확인해 주세요. (ERR-AMOUNT)');
    }

    if ($row_member['mb_point'] < $ExtendPeriod_amount) {
        $extend_fail('잔액이 부족합니다.', '포인트를 충전한 뒤 다시 시도해 주세요. (ERR-MFLAG)');
    }

    // 결제금액만큼 포인트 차감
    insert_point($member['mb_id'], $ExtendPeriod_amount * (-1), "계약연장 주문번호 {$od_id} " . $row_item_pricing['it_name'] . " 기존 {$row_it_spec_to_datetime['it_spec_to_datetime']} 에서 {$ExtendPeriod_days}일{$ExtendPeriod_hours}시간 추가요금 결제 (이용자: {$member['mb_id']} / {$member['mb_name']})", "@shopExtendPeriod"."|".time(), $member['mb_id']."|".$member['mb_id'], $od_id."|".$it_id);

    // shop_item 에서 종료일을 연장일수 만큼 추가
    sql_query(" UPDATE {$g5['g5_shop_item_table']} SET it_spec_to_datetime = '{$ExtendPeriod_datetime}' WHERE it_id = '{$it_id_esc}' AND it_spec_buyer_mb_id = '{$member_mb_id_esc}' ");

    if (trim($row_cart_history['extension_of_period_date']) == "") {
        $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;
        $ct_1_exists = sql_fetch(" SHOW COLUMNS FROM {$g5['g5_shop_cart_table']} LIKE 'ct_1' ");
        if ($ct_1_exists && isset($row_cart_history['ct_1'])) {
            $base_ct1_price = (float)$row_cart_history['ct_1'];
        }
        $base_contract_amount = round(($base_opt_price * $base_total_hours) + $base_install_price + $base_ct1_price, 0);
        $extension_of_period_date = $row_order_history['od_receipt_time'] . "\n" . G5_TIME_YMDHIS;
        $extension_of_period_to_datetime = $row_it_spec_to_datetime['it_spec_to_datetime_org'] . "\n" . $ExtendPeriod_datetime;
        $extension_of_period_days = $row_cart_history['ct_qty'] . "\n" . $ExtendPeriod_days;
        $extension_of_period_hours = $row_cart_history['ct_qty_hour'] . "\n" . $ExtendPeriod_hours;
        $extension_of_period_price = $base_contract_amount . "\n" . $ExtendPeriod_amount;
        $od_receipt_point_for_extension_of_period = $row_order_history['od_receipt_point_for_extension_of_period'] + $ExtendPeriod_amount;
        $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']."시간) " . $row_item_pricing['it_name'] . " 결제 " .  number_format($extension_of_period_price) ." Point" . " (이용자: " . $member['mb_id'] . " / " . $member['mb_name'] .") ");
    } else {
        $extension_of_period_date = $row_cart_history['extension_of_period_date'] . "\n" . G5_TIME_YMDHIS;
        $extension_of_period_to_datetime = $row_cart_history['extension_of_period_to_datetime'] . "\n" . $ExtendPeriod_datetime;
        $extension_of_period_days = $row_cart_history['extension_of_period_days'] . "\n" . $ExtendPeriod_days;
        $extension_of_period_hours = $row_cart_history['extension_of_period_hours'] . "\n" . $ExtendPeriod_hours;
        $extension_of_period_price = $row_cart_history['extension_of_period_price'] . "\n" . $ExtendPeriod_amount;
        $od_receipt_point_for_extension_of_period = $row_order_history['od_receipt_point_for_extension_of_period'] + $ExtendPeriod_amount;
        $od_mod_history = trim($row_order_history['od_mod_history'] . "\n" . G5_TIME_YMDHIS . " 계약연장 ({$ExtendPeriod_days}일{$ExtendPeriod_hours}시간) " . $row_item_pricing['it_name'] . " 결제 " .  number_format($ExtendPeriod_amount) ." Point" . " (이용자: " . $member['mb_id'] . " / " . $member['mb_name'] .") ");
    }

    $ct_qty_for_extension_of_period = $row_cart_history['ct_qty_for_extension_of_period'] + $ExtendPeriod_days;
    $ct_qty_hour_for_extension_of_period = $row_cart_history['ct_qty_hour_for_extension_of_period'] + $ExtendPeriod_hours;
    $ct_price_for_extension_of_period = $row_cart_history['ct_price_for_extension_of_period'] + $ExtendPeriod_amount;

    // 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}', ct_qty_for_extension_of_period = '{$ct_qty_for_extension_of_period}', ct_qty_hour_for_extension_of_period = '{$ct_qty_hour_for_extension_of_period}', ct_price_for_extension_of_period = '{$ct_price_for_extension_of_period}' WHERE od_id = '{$od_id_esc}' AND it_id = '{$it_id_esc}' AND mb_id = '{$member_mb_id_esc}' ");

    //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 = '{$it_id}' AND mb_id = '{$member['mb_id']}' ");


    /////// 연장구매 전용 shop_cart에 기록 추가 {
    // Commission = Sale * Commission Rate
    $pt_commission = $ExtendPeriod_amount * ($row_cart_history['pt_commission_rate'] / 100);

    // Point
    $extend_total_hours = apms_contract_hours_from_day_hour((int)$ExtendPeriod_days, (int)$ExtendPeriod_hours);
    $pt_point = ($row_cart_history['ct_point'] * $extend_total_hours) / 24;

    // Incentive = (Sale - Commission - Point) * Incentive Rate
	$pt_incentive = ($ExtendPeriod_amount - $pt_commission - $pt_point) * ($row_cart_history['pt_incentive_rate'] / 100);

    // Net = Sale - Commission - Point + Incentive
	$account_amount = $ExtendPeriod_amount - $pt_commission - $pt_point + $pt_incentive;

    if($row_cart_history['ct_notax']) {
		$account_net = $account_amount;
		$account_vat = 0;
	} else {

        $is_minus = ($account_amount > 0) ? false : true;

        $account_amount = abs($account_amount);
        $account_net = round($account_amount / 1.1);
        $account_vat = $account_amount - $account_net;

        if($is_minus) {
            $account_net = $account_net * (-1);
            $account_vat = $account_vat * (-1);
        }
	}
    /////// 연장구매 전용 shop_cart에 기록 추가 }

    // 연장되는 원래 품번의 it_name, ct_option 추출함
    $row_it_org_info = sql_fetch(" SELECT it_name, ct_option FROM {$g5['g5_shop_cart_table']} WHERE it_id = '{$it_id_esc}' ");

    sql_query(" INSERT {$g5['g5_shop_cart_for_extension_of_period_table']} SET ct_id = '{$row_cart_history['ct_id']}', od_id = '{$od_id_esc}', it_id = '{$it_id_esc}', it_name = '{$row_it_org_info['it_name']}', ct_option = '{$row_it_org_info['ct_option']}', mb_id = '{$member_mb_id_esc}', ct_point = '{$row_cart_history['ct_point']}', ct_point_use = '{$row_cart_history['ct_point_use']}', pt_it = '{$row_cart_history['pt_it']}', extension_of_period_date = '" . G5_TIME_YMDHIS . "', extension_of_period_to_datetime = '{$ExtendPeriod_datetime}', extension_of_period_days = '{$ExtendPeriod_days}', extension_of_period_hours = '{$ExtendPeriod_hours}', extension_of_period_price = '{$ExtendPeriod_amount}', ct_qty_for_extension_of_period = '{$ExtendPeriod_days}', ct_qty_hour_for_extension_of_period = '{$ExtendPeriod_hours}', ct_price_for_extension_of_period = '{$ExtendPeriod_amount}', ct_price = '{$row_cart_history['ct_price']}', ct_status = '입금', pt_id = '{$row_cart_history['pt_id']}', ct_select = '1', ct_stock_use = '{$row_cart_history['ct_stock_use']}', io_id = '{$row_cart_history['io_id']}', io_type = '{$row_cart_history['io_type']}', pt_datetime = '" . G5_TIME_YMDHIS . "', pt_commission_rate = '{$row_cart_history['pt_commission_rate']}', pt_sale = '{$ExtendPeriod_amount}', pt_commission = '{$pt_commission}', pt_point = '{$pt_point}', pt_incentive_rate = '{$row_cart_history['pt_incentive_rate']}', pt_incentive = '{$pt_incentive}', ct_notax = '{$row_cart_history['ct_notax']}', pt_net = '{$account_net}' ");

    // shop_order 에 연장금액 누적합산금액 업데이트
    sql_query(" UPDATE {$g5['g5_shop_order_table']} SET od_receipt_point_for_extension_of_period = '{$od_receipt_point_for_extension_of_period}', od_mod_history = '{$od_mod_history}' WHERE od_id = '{$od_id_esc}' AND mb_id = '{$member_mb_id_esc}' ");

    $ExtendPeriod_amount_disp = number_format($ExtendPeriod_amount);

} else {
    $extend_fail('요청값이 올바르지 않습니다.', '연장기간 또는 종료일시를 확인해 주세요. (ERR-PARAM)');
}


// 각종 인센티브 계산
///////////////////
global $g5, $member, $is_guest;

// APMS
$mk_id = '';
$mk_brate = 0;
if(USE_PARTNER) {
    $apms = sql_fetch(" select * from {$g5['apms']} ", false);
    $od_mk =($is_guest && defined('APMS_MKT') && APMS_MKT) ? APMS_MKT : $member['mb_recommend']; //비회원주문 처리

    if($od_mk) { // 추천인 아이디가 있으면
        $mk = apms_marketer($od_mk);
        if($mk['pt_id']) {
            $mk_id = $mk['pt_id'];
            $lvl = (isset($mk['pt_level']) && $mk['pt_level'] > 0) ? $mk['pt_level'] : 1;
            $mk_lvrate = (isset($apms['apms_benefit'.$lvl]) && $apms['apms_benefit'.$lvl] > 0) ? $apms['apms_benefit'.$lvl] : 0;
            $mk_brate = ($mk_lvrate + $mk['pt_benefit']);
        }
    }
}

$row_cart_for_extension = sql_fetch(" SELECT * FROM {$g5['g5_shop_cart_for_extension_of_period_table']} WHERE od_id = '{$od_id_esc}' AND it_id = '{$it_id_esc}' AND mb_id = '{$member_mb_id_esc}' AND pt_datetime = '" . G5_TIME_YMDHIS ."' ORDER BY pt_datetime DESC LIMIT 1 ");

$od_ok = ($row_cart_for_extension['ct_status'] == "입금") ? true : false;
if(!$row_cart_for_extension['od_id']) {
    $extend_fail('연장 처리 대상을 찾을 수 없습니다.', '연장처리 기록 조회에 실패했습니다. (ERR-EXTROW)');
}

$arr_it_id = array();
$arr_no_auto = array();
$account = array();

$now = G5_TIME_YMDHIS;
$ptxt = aslang('log', 'delivery_point');

$it = apms_it($row_cart_for_extension['it_id']); //상품정보

$query = "";
if($od_ok && in_array($it['pt_it'], $g5['apms_automation'])) { //자동처리 상품일 때 입금상태이면 재고반영, 포인트반영, 결제완료 처리함

    //상태변경
    $ct_status = '완료';

    // 장바구니 업데이트
    $query .= ", ct_status = '$ct_status'";

    // 판매량 반영
    $arr_it_id[] = $row_cart_for_extension['it_id'];

    // 재고량 반영
    if(!$row_cart_for_extension['ct_stock_use']) {
        //YC5 관리자용 차용
        apms_stock($row_cart_for_extension['it_id'], $row_cart_for_extension['ct_qty_for_extension_of_period'], $row_cart_for_extension['io_id'], $row_cart_for_extension['io_type']);
        $query .= ", ct_stock_use = '1'";
    }

    // 포인트 반영 - 컨텐츠 상품은 설정일과 상관없이 반영함
    if($row_cart_for_extension['mb_id'] && $row_cart_for_extension['ct_point'] > 0 && !$row_cart_for_extension['ct_point_use'] && in_array($row_cart_for_extension['pt_it'], $g5['apms_automation'])) {
		$extension_contract_days = apms_contract_days_from_day_hour($row_cart_for_extension['ct_qty_for_extension_of_period'], $row_cart_for_extension['ct_qty_hour_for_extension_of_period']);
		$po_point = round($row_cart_for_extension['ct_point'] * $extension_contract_days);
        $po_content = astxt($ptxt, array($od_id, $row_cart_for_extension['it_id'], $row_cart_for_extension['ct_id'])) . " 계약연장 {$now}"; //주문번호 $od_id ($row_cart_for_extension['it_id'] : $row_cart_for_extension['ct_id']) 구매완료
        insert_point($row_cart_for_extension['mb_id'], $po_point, $po_content, "@delivery", $row_cart_for_extension['mb_id'], "{$od_id},{$row_cart_for_extension['ct_id']},{$now}");
        $query .= ", ct_point_use = '1'";
    }
    // 정산일 반영
    $query .= ", pt_datetime = '$now'";

    // 히스토리에 남김 - 히스토리에 남길때는 작업|아이디|시간|IP|그리고 나머지 자료
    $ct_history="\n$ct_status|automation|$now|";
    $query .= ", ct_history = CONCAT(ct_history,'$ct_history')";

    // 멤버쉽 아이템 체크 - 멤버쉽 함수가 있을 때만 작동
    if (function_exists('apms_membership_order')) {
        apms_membership_order($row_cart_for_extension, $ct_status, $now);
    }
} else {
    // 자동처리 아닌 상품
    $arr_no_auto[] = $row_cart_for_extension['it_id'];
}

//커미션, 인센티브
if(USE_PARTNER) {
    if($it['pt_id']) { // 판매자
        list($commission, $incentive) = apms_pt_rate($apms, $it['pt_it'], $it['pt_id'], $it['pt_commission'], $it['pt_incentive']);
        $row_cart_for_extension['pt_commission_rate'] = ($commission) ? $commission : 0;
        $row_cart_for_extension['pt_incentive_rate'] = ($incentive) ? $incentive : 0;

        // 가정산
        $account = apms_account_for_extension_of_period($row_cart_for_extension);

        $query .= " , pt_id = '{$it['pt_id']}'
                    , pt_commission_rate = '{$row_cart_for_extension['pt_commission_rate']}'
                    , pt_incentive_rate = '{$row_cart_for_extension['pt_incentive_rate']}'
                    , pt_sale = '{$account['sale']}'
                    , pt_commission = '{$account['commission']}'
                    , pt_point = '{$account['point']}'
                    , pt_incentive = '{$account['incentive']}'
                    , pt_net = '{$account['net']}' ";
    }

    if($mk_id && isset($it['pt_marketer']) && $it['pt_marketer'] > 0) { // 추천인

        $mk_prate = ($it['pt_marketer'] / 100);

        $extension_contract_days = apms_contract_days_from_day_hour($row_cart_for_extension['ct_qty_for_extension_of_period'], $row_cart_for_extension['ct_qty_hour_for_extension_of_period']);
        if($row_cart_for_extension['io_type']) {
    			$mk_amount = round($row_cart_for_extension['io_price'] * $extension_contract_days);
        } else {
    			$mk_amount = round(($row_cart_for_extension['ct_price'] + $row_cart_for_extension['io_price']) * $extension_contract_days);
        }

        if($row_cart_for_extension['ct_notax']) {
            $mk_net = $mk_amount;
        } else {
            list($mk_net) = apms_vat($mk_amount);
        }

        $mk_profit = floor($mk_net * $mk_prate);
        if($mk_profit > 0) {
            $mk_benefit = floor($mk_profit * ($mk_brate / 100));
            $query .= " , mk_id = '{$mk_id}'
                        , mk_profit = '{$mk_profit}'
                        , mk_benefit = '{$mk_benefit}'
                        , mk_profit_rate = '{$it['pt_marketer']}'
                        , mk_benefit_rate = '{$mk_brate}' ";
        }
    }

}

if($query) {
    $sql = " UPDATE {$g5['g5_shop_cart_for_extension_of_period_table']}
                SET pt_it = '{$it['pt_it']}'
                    $query
                WHERE od_id = '{$od_id_esc}'
                AND ct_id = '{$row_cart_for_extension['ct_id']}'
                AND it_id = '{$it_id_esc}'
                AND mb_id = '{$member_mb_id_esc}'
                AND pt_datetime = '" . G5_TIME_YMDHIS ."'
            ";
    sql_query($sql);
}


////////////////////////////


if ($extend_tx_started) {
    sql_query("COMMIT");
    $extend_tx_started = false;
}

if (function_exists('vpnlink_vpnid_sync_upsert_by_order')) {
    $vpnid_sync_ret = vpnlink_vpnid_sync_upsert_by_order($od_id, $it_id, 'shop_order_extend');
    if (empty($vpnid_sync_ret['ok']) && function_exists('vpnlink_ikev2_log')) {
        vpnlink_ikev2_log('shop/orderinquiryExtendPeriod vpnid sync failed: od_id='.$od_id.' it_id='.$it_id.' error='.(isset($vpnid_sync_ret['error']) ? $vpnid_sync_ret['error'] : 'unknown'));
    }
}

if (function_exists('vpnlink_ikev2_queue_order')) {
    $ikev2_requeue_ret = vpnlink_ikev2_queue_order($od_id, 'shop_order_extend_requeue');
    if (empty($ikev2_requeue_ret['ok']) && function_exists('vpnlink_ikev2_log')) {
        vpnlink_ikev2_log('shop/orderinquiryExtendPeriod ikev2 requeue failed: od_id='.$od_id.' it_id='.$it_id.' error='.(isset($ikev2_requeue_ret['error']) ? $ikev2_requeue_ret['error'] : 'unknown'));
    }
}

set_session($extend_idem_session_key, 'done');


$redirect_url = G5_SHOP_URL . "/orderinquiryview.php?od_id={$od_id}&uid={$uid}";
oi_success_popup('계약종료일을 연장하였습니다.', array(
    "주문번호 : {$od_id}",
    "상품명 : " . $row_item_pricing['it_name'],
    "계약연장일수 : " . (int)$ExtendPeriod_days . "일" . (int)$ExtendPeriod_hours . "시간",
    "결제(포인트 차감)금액 : {$ExtendPeriod_amount_disp} Point",
    "계약연장전 종료일시 : {$row_it_spec_to_datetime['it_spec_to_datetime']}",
    "계약연장후 종료일시 : {$ExtendPeriod_datetime}"
), $redirect_url, '계약연장 결제 완료', '확인', '처리 내역을 확인해 주세요.', $popup_log_success_options);
?>