<?php
/**
 * MARKETOOLS 退款通知API接口程序
 * ============================================================================
 * 版权所有 2007-2010 海南推广易科技有限公司，并保留所有权利。
 * 网站地址: http://www.marketools.cn；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: easelify $
 * $Id: bindingclient.php 2011/3/30 easelify $
 */

/*
    [tm_userid] => e702caa1
    [affiliatename] => XXX
    [tm_campaignid] => cliksale
    [tm_campaignname] => 默认项目
    [tm_transtype] => 128
    [tm_totalcost] => 0
    [tm_orderid] =>
    [tm_productid] =>
    [tm_data1] =>
    [tm_data2] =>
    [tm_data3] =>
    [tm_commission] => -0.01
    [tm_rstatus] => 2
    [tm_createtype] => manual
    [tid] => bddba67a
    [commited] => yes
    [md] => Affiliate_Merchants_Views_TransactionManager
    [action] => createrefundchargeback
    [postaction] => create
*/

require_once('global.php');


if(empty($_REQUEST['orderid'])) {
    die('params error.');
}

//token 签名认证
$oToken = QUnit_Global::newObj('Affiliate_API_Bl_Token');
if(!$oToken->check($_REQUEST['token'])) {
    die('access deny.');
}


$query = 'select `value` from `wd_g_settings` where `code`="Aff_api_refund_notify_ttl" and `rtype`=3';
$ts = $GLOBALS['db']->Query($query);
if(!$ts || $ts->EOF) {
    $ttl = 0;   //默认无限制
} else {
    $ttl = $ts->fields['value'];
}
$ttl *= 86400;

$query = 'select `transid`, `affiliateid`, `orderid`, `totalcost`, `productid`, `commission`,`dateinserted`,`Data2`,`Data3` from `wd_pa_transactions` where `rstatus`=2 and `transtype`=4 and `orderid`="'.$_REQUEST['orderid'].'" limit 1';
$rs = $GLOBALS['db']->Query($query);
if(!$rs || $rs->EOF) {
    die('order not find or commission not approved.');
}

if($ttl)
if(strtotime($rs->fields['dateinserted'])+$ttl<time()) {
    die('order has been too long.');
}

$_POST['postaction'] = 'create';
$_POST['tm_createtype'] = 'manual';
$_POST['tm_transtype'] = 128;
$_POST['tm_commission'] = -1 * $rs->fields['commission'];
$_POST['tm_rstatus'] = 2;
$_POST['tid'] = $rs->fields['transid'];

$_POST['tm_userid'] = $rs->fields['affiliateid'];
$_POST['tm_campaignid'] = 'cliksale';

$_POST['tm_totalcost'] = -1 * $rs->fields['totalcost'];
$_POST['tm_orderid'] = $rs->fields['orderid'];
$_POST['tm_productid'] = $rs->fields['productid'];
$_POST['tm_data1'] = $_POST['token'];
$_POST['tm_data2'] = $rs->fields['Data2'];
$_POST['tm_data3'] = $rs->fields['Data3'];

$oTM = QUnit_Global::newObj('Affiliate_Merchants_Views_TransactionManager');
$oTM->processCreateTransaction(false);
?>