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

check_device('both');

$req = 'cmd=_notify-synch';
$tx_token = $_REQUEST['uid'];
$req .= "&tx=$tx_token&at=$auth_token";

# 수신한 tx 값과 token 값을 paypal 서버로 전송
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://{$pp_hostname}/cgi-bin/webscr");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: {$pp_hostname}"));
$res = curl_exec($ch);

curl_close($ch);

# 최종 결과값 분석
if( !$res ) {
    $result_msg = "Paypal 서버 연동 오류가 발생했습니다.";
} else {
    // 결과값을 로그로 기록해 보기
    $lines = explode("\n", $res);
    $paypal = array();
    if (strcmp ($lines[0], "SUCCESS") == 0) {
        // 결제가 성공한 경우
        for ($i=1; $i<count($lines);$i++){
            list($key,$val) = explode("=", $lines[$i]);
            if( trim($key) != '' ) {
                $paypal[urldecode($key)] = iconv('euc-kr', 'utf-8', urldecode($val));
            }
        }

        $result_msg = "\"".number_format($paypal['mc_gross'])." 캐시\"가 충전 완료되었습니다!";
        
		// Move Cash Charge Logic Here, Don't know why ipn code is working.
        $raw_post_data = file_get_contents('php://input');
        $raw_post_array = explode('&', $raw_post_data);

        // $paypal = array();
        foreach ($raw_post_array as $keyval) {
            $keyval = explode('=', $keyval);
            if (count($keyval) == 2) {
                // Since we do not want the plus in the datetime string to be encoded to a space, we manually encode it.
                if ($keyval[0] === 'payment_date') {
                    if (substr_count($keyval[1], '+') === 1) {
                        $keyval[1] = str_replace('+', '%2B', $keyval[1]);
                    }
                }
                $paypal[$keyval[0]] = urldecode($keyval[1]);
            }
        }
        
        $member = get_member($paypal['custom']);

        $paypal['item_name'] = iconv('euc-kr', 'utf-8', $paypal['item_name']);
        $sql = "insert into {$lo['paypal_table']} set
                    mb_id           = '{$member['mb_id']}',
                    lp_tx           = '{$paypal['txn_id']}',
                    lp_payer_id     = '{$paypal['payer_id']}',
                    lp_payer_email  = '{$paypal['payer_email']}',
                    lp_first_name   = '{$paypal['first_name']}',
                    lp_last_name    = '{$paypal['last_name']}',
                    lp_mc_gross     = '{$paypal['mc_gross']}',
                    lp_item_name    = '{$paypal['item_name']}',
                    lp_item_number  = '{$paypal['item_number']}',
                    lp_quantity     = '{$paypal['quantity']}',
                    lp_business     = '{$paypal['business']}',
                    lp_receiver_id  = '{$paypal['receiver_id']}',
                    lp_payment_date = '{$paypal['payment_date']}',
                    lp_response     = '{$raw_post_data}',
                    lp_payed        = 'Y',
                    lp_datetime     = '". G5_TIME_YMDHIS ."'
               ";
        ////sql_query($sql);

        $cash = (int)$paypal['mc_gross'];
        $cr_content = '캐시충전 $'. (int)$paypal['mc_gross'];
        $uniqueNumber = time();
        $lp_id = strval($uniqueNumber);
        ////insert_cash($member['mb_id'], $cash, $cr_content, $lo['paypal_table'], $member['mb_id'], $lp_id.'-캐시충전');

        // 캐시충전 시 보너스 포인트 적용 by Billy at 10142024
        // Get Current Point.
        $select_sql = "select mb_point from {$g5['member_table']} where mb_id = '{$member['mb_id']}' ";
        $point_row = sql_fetch($select_sql);
        $point_val = (float)$point_row['mb_point'];
        $bouns_point = 0.0;
        $add_point = 0.0;
        if ($cash == 350) {
            $bouns_point = $point_val + 70.0;
            $add_point = 70.0;
        } else if ($cash == 175) {
            $bouns_point = $point_val + 28.0;
            $add_point = 28.0;
        } else if ($cash == 70) {
            $bouns_point = $point_val + 7.0;
            $add_point = 7.0;
        } else if ($cash == 35) {
            $bouns_point = $point_val + 3.5;
            $add_point = 3.5;
        } else if ($cash == 1) {
            $bouns_point = $point_val + 1;
            $add_point = 1.0;
        }
        $update_sql = " update {$g5['member_table']} set mb_point = '{$bouns_point}' where mb_id = '{$member['mb_id']}' ";
        sql_query($update_sql);

        // Add Point History
        if ($add_point > 0.0) {
            $t_rel_table = $lo['paypal_table'];
            $t_rel_id = $member['mb_id'];
            $t_rel_action = $lp_id.'-충전포인트';
            $po_cash_val = (double)$pointuse * -1;
            $sql = " insert into {$lo['point_table']}
                        set mb_id = '$t_rel_id',
                            po_datetime = '".G5_TIME_YMDHIS."',
                            po_content = 'PayPal포인트충전',
                            po_cash = '$add_point',
                            po_mb_point_before = '$point_val',
                            po_mb_point = '$bouns_point',
                            po_expired = '0',
                            po_expire_date = '9999-12-31',
                            po_rel_table = '$t_rel_table',
                            po_rel_id = '$t_rel_id',
                            po_rel_action = '$t_rel_action' ";
            sql_query($sql);
        }
		
    } else if (strcmp ($lines[0], "FAIL") == 0) {
        // 결제가 실패한 경우
        $result_msg = "결제오류가 발생했습니다!";
    }
}

$tmenu_ = "마이로또"; // theme.menu.php 에서 세팅한 이 페이지의 대메뉴명을 입력합니다.

$g5['title'] = "캐시충전결과";

include_once(G5_PATH.'/_head.php');

// add_stylesheet('css 구문', 출력순서); 숫자가 작을 수록 먼저 출력됨
add_stylesheet('<link rel="stylesheet" href="'.LOTTO_CSS_URL.'/charge.css?ver='.G5_TIME_YMDHIS.'">', 0);
?>
<section class="scontents">
    <div style="text-align:right"><a href="<?php echo LOTTO_URL ?>/my_cash.php" class="btn_b011 btn" title="나의 캐시"><i class="fas fa-list"></i> <span class="">나의 캐시</span></a></div>
    <br/>
    <div class="cash_box"><?php echo $result_msg ?></div>
    <div class="button_wrap">
        <ul class="">
            <li><a href="<?php echo LOTTO_URL ?>/number.php" class="btn_b011 btn" title="메가밀리언 구매"><i class="fas fa-arrow-right"></i> <span class="">메가밀리언 구매</span></a></li>
            <li><a href="<?php echo LOTTO_URL ?>/number.php?item=powerball" class="btn_b011 btn" title="파워볼 구매"><i class="fas fa-arrow-right"></i> <span class="">파워볼 구매</span></a></li>
        </ul>	
    </div>
</section>
<?php
include_once(G5_PATH.'/_tail.php');