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

$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']);

if( !$member['mb_id'] ) {
    exit;
}

if( $paypal['payment_status'] != 'Completed' ) {
    $sql = "insert into {$lo['paypal_fail_table']} set
                mb_id             = '{$member['mb_id']}',
                pf_response       = '{$raw_post_data}',
                pf_payment_status = '{$paypal['payment_status']}',
                pf_datetime       = '". G5_TIME_YMDHIS ."'
           ";
    sql_query($sql);
    exit;
}

// $cash = $product[$paypal['item_number']]['cash'];
// if( !$cash ) {
//     exit;
// }


// Build the body of the verification post request, adding the _notify-validate command.
$req = 'cmd=_notify-validate';
$get_magic_quotes_exists = false;
if (function_exists('get_magic_quotes_gpc')) {
    $get_magic_quotes_exists = true;
}
foreach ($paypal as $key => $value) {
    if ($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
        $value = urlencode(stripslashes($value));
    } else {
        $value = urlencode($value);
    }
    $req .= "&$key=$value";
}

// Post the data back to PayPal, using curl. Throw exceptions if errors occur.
$ch = curl_init("https://{$ipnpb_hostname}/cgi-bin/webscr");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSLVERSION, 6);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'User-Agent: PHP-IPN-Verification-Script',
    'Connection: Close',
));

$res = curl_exec($ch);

if( !($res) ) {
    $errno = curl_errno($ch);
    $errstr = curl_error($ch);
} else {
    $info = curl_getinfo($ch);
    $http_code = $info['http_code'];
    if( $http_code == 200 ) {
        if( $res == 'VERIFIED' ) {
            $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);

            $lp_id = sql_insert_id();

            $cash = (int)$paypal['mc_gross'];
            $cr_content = '캐시충전 $'. (int)$paypal['mc_gross'];
            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;
            } else if ($cash == 175) {
                $bouns_point = $point_val + 28.0;
                $add_point = 28;
            } else if ($cash == 70) {
                $bouns_point = $point_val + 7.0;
                $add_point = 7;
            } 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;
            }
            $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);
			}
        }
    }
}

curl_close($ch);
?>