<?php
include_once('../common.php');
require './rtpay.class.php';

$RTPay = new RTPay;

// POST 데이터 파일로 저장 (디버깅용) - 비활성화됨

//========================== 인증키값 설정 부분만 고쳐주세요. =======================
$RTPay->RTP_KEY="d7351fc5-89d7-4037-9f8f-xxxxxxxxxx";	//인증키값 설정
//========================== 인증키값 설정 부분만 고쳐주세요. =======================

$resultArray = array();
$resultArray['PCHK'] =  "NO";

if ($_POST['regPkey']==$RTPay->RTP_KEY) {
	if ($RTPay->checkCURL()) {
		if ($_POST['ugrd'] == '11') $RTPay->RTP_URL="https://rtpay.net/CheckPay/test_checkpay.php";
		else $RTPay->RTP_URL="https://rtpay.net/CheckPay/checkpay.php";

		$retRTP = $RTPay->getRTPay();

		if ($retRTP->RCODE=='200') {
			$pbank=$retRTP->RBANK;	//은행명
			$pname=$retRTP->RNAME;	//입금자명
			$pmoney=$retRTP->RPAY;	//입금금액
			$tall=$retRTP->RTEXT;	//전송 데이터 전문

			sql_query("insert into sp_rtpay (bank,bname,bpay,bcontent,wdate) values ('$pbank','$pname','$pmoney','$tall',now());");

			$sqry1 = "select count(*) as ucount from g5_shoppoint_order where od_settle_case='무통장' and od_deposit_name='$pname' and od_misu='$pmoney' and od_status='주문'";
			$row0 = sql_fetch($sqry1);
			$ucount = $row0['ucount'];
			$sqry2 = "select count(*) as scount from sp_rtpay where bname='$pname' and bpay='$pmoney' and bstate=0";
			$row2 = sql_fetch($sqry2);
			$scount = $row2['scount'];

			if (($ucount==1)&&($scount==1)) {
				$sql = "select od_id from g5_shoppoint_order where od_settle_case='무통장' and od_deposit_name='$pname' and od_misu='$pmoney' and od_status='주문'";
				$row = sql_fetch($sql);
				$odid = $row['od_id'];

				$sql1 = "update sp_rtpay set od_id='{$odid}',bstate=1 where bname='$pname' and bpay='$pmoney' and bstate=0 limit 1 ";
				sql_query($sql1);

				$sql2 = "update g5_shoppoint_order set od_receipt_price=od_misu,od_misu=0,od_receipt_time=now(),od_status='입금' where od_id = '{$odid}' ";
				sql_query($sql2);

				$resultArray['PCHK'] =  "OK";
			} else {
				$resultArray['PCHK'] =  "NO";
			}
		}

		$resultArray['RCODE'] = $retRTP->RCODE;
	} else {
		$resultArray['RCODE'] = "300";
	}
} else {
	if (!$_POST['regPkey']) {
		$_POST['regPkey']=$RTPay->RTP_KEY;
		$RTPay->RTP_URL="https://rtpay.net/CheckPay/setPurl.php";
		$retRTP = $RTPay->getRTPay();
		sql_query("CREATE TABLE IF NOT EXISTS `sp_rtpay` (`rt_id` bigint(20) NOT NULL AUTO_INCREMENT,`od_id` bigint(20) NOT NULL,`pp_id` bigint(20) NOT NULL,`bank` varchar(20) NOT NULL,`bname` varchar(50) NOT NULL,`bpay` int(11) NOT NULL,`bcontent` text NOT NULL,`bstate` int(5) NOT NULL DEFAULT '0',`wdate` datetime NOT NULL,PRIMARY KEY (`rt_id`)) default character set utf8 collate utf8_general_ci;");
	}
	$resultArray['RCODE'] = "400";
}

echo json_encode($resultArray);
?>