<?php

/**
 * [Discuz!] (C)2001-2099 Discuz! Team
 * This is NOT a freeware, use is subject to license terms
 * https://license.discuz.vip
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}
if(empty($_GET['op'])) $_GET['op'] = 'base';
if(in_array($_GET['op'], ['transfer', 'exchange'])) {
	$taxpercent = sprintf('%1.2f', $_G['setting']['creditstax'] * 100).'%';
}
if($_GET['op'] == 'base') {
	$loglist = $extcredits_exchange = [];
	if(!empty($_G['setting']['extcredits'])) {
		foreach($_G['setting']['extcredits'] as $key => $value) {
			if($value['allowexchangein'] || $value['allowexchangeout']) {
				$extcredits_exchange['extcredits'.$key] = ['title' => $value['title'], 'unit' => $value['unit']];
			}
		}
	}

	$count = table_common_credit_log::t()->count_by_uid($_G['uid']);
	if($count) {
		loadcache(['magics']);
		foreach(table_common_credit_log::t()->fetch_all_by_uid($_G['uid'], 0, 10) as $log) {
			$credits = $ac_credits = [];
			$havecredit = $haveaccredit = false;
			$maxid = $minid = 0;
			for($id = 1; $id <= 8;$id++) {
				if(isset($log['ac_extcredits'.$id]) && $log['ac_extcredits'.$id]) {
					$haveaccredit = true;
				}
			}
			foreach($_G['setting']['extcredits'] as $id => $credit) {
				if($log['extcredits'.$id]) {
					$havecredit = true;
					if($log['operation'] == 'RPZ') {
						$credits[] = $credit['title'].lang('spacecp', 'credit_update_reward_clean');
					} else {
						$credits[] = $credit['title'].' <span class="'.($log['extcredits'.$id] > 0 ? 'xi1' : 'xg1').'">'.($log['extcredits'.$id] > 0 ? '+' : '').$log['extcredits'.$id].'</span>';
					}
					if($log['operation'] == 'CEC' && !empty($log['extcredits'.$id])) {
						if($log['extcredits'.$id] > 0) {
							$log['maxid'] = $id;
						} elseif($log['extcredits'.$id] < 0) {
							$log['minid'] = $id;
						}
					}
					if($haveaccredit && isset($log['ac_extcredits'.$id])) {
						$ac_credits[] = $credit['title'].' '.$log['ac_extcredits'.$id];
					}
				}
			}
			if(!$havecredit) {
				continue;
			}
			$log['credit'] = implode('<br/>', $credits);
			$log['ac_credit'] = implode('<br/>', $ac_credits);
			if(in_array($log['operation'], ['RTC', 'RAC', 'STC', 'BTC', 'ACC', 'RCT', 'RCA', 'RCB'])) {
				$tids[$log['relatedid']] = $log['relatedid'];
			} elseif(in_array($log['operation'], ['SAC', 'BAC'])) {
				$aids[$log['relatedid']] = $log['relatedid'];
			} elseif(in_array($log['operation'], ['PRC', 'RSC'])) {
				$pids[$log['relatedid']] = $log['relatedid'];
			} elseif(in_array($log['operation'], ['TFR', 'RCV'])) {
				$uids[$log['relatedid']] = $log['relatedid'];
			} elseif($log['operation'] == 'TRC') {
				$taskids[$log['relatedid']] = $log['relatedid'];
			}

			$loglist[] = $log;
		}
		$otherinfo = getotherinfo($aids, $pids, $tids, $taskids, $uids);

	}

	$navtitle = lang('core', 'title_credit');
	$creditsformulaexp = str_replace('*', '&times;', $_G['setting']['creditsformulaexp']);
	$creditsformulaexp = preg_replace_callback('/\{(credits_\w+)\}/', function($r) {
		return lang('credit', $r[1]);
	}, $creditsformulaexp);

	$upgroup_credits = 0;
	$upgroup_creditsformulaexp = $upgroup_name = '';
	$upgroupid = $_G['cache']['usergroup_'.$_G['groupid']]['upgroupid'];
	if($_G['cache']['usergroup_'.$_G['groupid']]['grouptype'] == 'special' && !empty($upgroupid)) {
		$upgroup_credits = (new credit())->countcredit_usergroup($_G['uid'], $upgroupid);
		loadcache('usergroup_'.$upgroupid);
		if($_G['cache']['usergroup_'.$upgroupid]['creditsformula'] && !empty($_G['setting']['upgroup_name'][$upgroupid])) {
			$upgroup_creditsformulaexp = $_G['cache']['usergroup_'.$upgroupid]['creditsformulaexp'];
			$upgroup_name = $_G['setting']['upgroup_name'][$upgroupid];
		}
	}

} elseif($_GET['op'] == 'buy') {
	if((!$_G['setting']['ec_ratio'] || !$is_enable_pay) && !$_G['setting']['card']['open']) {
		showmessage('action_closed', NULL);
	}

	if(submitcheck('addfundsbuyform')) {
		$amount = intval($_GET['addfundamount']);
		if(!$amount) {
			showmessage('memcp_credits_addfunds_msg_incorrect', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
		}
		$language = lang('forum/misc');
		if(($_G['setting']['ec_mincredits'] && $amount < $_G['setting']['ec_mincredits']) || ($_G['setting']['ec_maxcredits'] && $amount > $_G['setting']['ec_maxcredits'])) {
			showmessage('credits_addfunds_amount_invalid', '', ['ec_maxcredits' => $_G['setting']['ec_maxcredits'], 'ec_mincredits' => $_G['setting']['ec_mincredits']], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
		}

		if($_G['setting']['ec_maxcreditspermonth']) {
			if(table_forum_order::t()->sum_amount_by_uid_submitdate_status($_G['uid'], $_G['timestamp'] - 2592000, [2, 3]) + $amount > $_G['setting']['ec_maxcreditspermonth']) {
				showmessage('credits_addfunds_toomuch', '', ['ec_maxcreditspermonth' => $_G['setting']['ec_maxcreditspermonth']], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
			}
		}

		$price = round(($amount / $_G['setting']['ec_ratio'] * 100) / 100, 2);

		$credits = $_G['setting']['extcredits'][$_G['setting']['creditstrans']];

		$return_url = $_G['siteurl'].'home.php?mod=spacecp&ac=credit&op=base';
		$pay_url = payment::create_order(
			'payment_credit',
			$_G['setting']['bbname'].' - '.lang('forum/misc', 'credit_payment'),
			trim(lang('forum/misc', 'credit_forum_payment').' '.$credits['title'].' '.$amount.' '.$credits['unit']),
			$price * 100,
			$return_url,
			[
				'index' => $_G['setting']['creditstrans'],
				'value' => $amount,
				'ip' => $_G['clientip'],
				'port' => $_G['remoteport']
			]
		);

		include isset($_REQUEST['inajax']) ? template('common/header_ajax') : template('common/header');
		echo '<script type="text/javascript" reload="1">window.location.href = \''.$pay_url.'\';</script>';
		include isset($_REQUEST['inajax']) ? template('common/footer_ajax') : template('common/footer');
		dexit();
	} elseif(submitcheck('addfundscardsubmit')) {
		list($seccodecheck, $secqaacheck) = seccheck('card');
		if($seccodecheck) {
			if(!check_seccode($_GET['seccodeverify'], $_GET['seccodehash'])) {
				showmessage('submit_seccode_invalid', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
			}
		}
		if($secqaacheck) {
			if(!check_secqaa($_GET['secanswer'], $_GET['secqaahash'])) {
				showmessage('submit_secqaa_invalid', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
			}
		}

		if(!$_POST['cardid']) {
			showmessage('memcp_credits_card_msg_cardid_incorrect', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
		}
		if(!($card = table_common_card::t()->fetch($_POST['cardid']))) {
			showmessage('memcp_credits_card_msg_card_unfined', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true, 'extrajs' => '<script type="text/javascript">updateseccode("'.$_GET['sechash'].'");</script>']);
		} else {
			if($card['status'] == 2) {
				showmessage('memcp_credits_card_msg_used', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
			}
			if($card['cleardateline'] < TIMESTAMP) {
				showmessage('memcp_credits_card_msg_cleardateline_early', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
			}
			if(table_common_card::t()->update_to_used($card['id'])) {
				updatemembercount($_G['uid'], [$card['extcreditskey'] => $card['extcreditsval']], true, 'CDC', 1);
				showmessage('memcp_credits_card_msg_succeed', 'home.php?mod=spacecp&ac=credit&op=base', ['extcreditstitle' => $_G['setting']['extcredits'][$card['extcreditskey']]['title'], 'extcreditsval' => $card['extcreditsval']], ['showdialog' => 1, 'alert' => 'right', 'showmsg' => true, 'locationtime' => true]);
			} else {
				showmessage('memcp_credits_card_msg_used', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
			}
		}
	} else {
		if($_G['setting']['card']['open']) {
			list($seccodecheck, $secqaacheck) = seccheck('card');
		}

		$active = [];
		if($_G['setting']['ec_ratio'] && $is_enable_pay) {
			$active['rmb'] = 1;
		} elseif($_G['setting']['card']['open']) {
			$active['card'] = 1;
		}
	}
} elseif($_GET['op'] == 'transfer') {
	if(!empty($_G['setting']['submitlock']) && discuz_process::islocked('transferlock_'.$_G['uid'], 0, 1)) {
		showmessage('credits_transfer_msg_locked', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
	}

	if(!($_G['setting']['transferstatus'] && $_G['group']['allowtransfer'])) {
		showmessage('action_closed', NULL);
	}

	if(submitcheck('transfersubmit')) {
		if($_GET['to'] == $_G['username']) {
			showmessage('memcp_credits_transfer_msg_self_incorrect', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
		}
		$amount = intval($_GET['transferamount']);
		if($amount <= 0) {
			showmessage('credits_transaction_amount_invalid', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
		} elseif(getuserprofile('extcredits'.$_G['setting']['creditstransextra'][9]) - $amount < ($minbalance = $_G['setting']['transfermincredits'])) {
			showmessage('credits_transfer_balance_insufficient', '', ['title' => $_G['setting']['extcredits'][$_G['setting']['creditstransextra'][9]]['title'], 'minbalance' => $minbalance], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
		} elseif(!($netamount = floor($amount * (1 - $_G['setting']['creditstax'])))) {
			showmessage('credits_net_amount_iszero', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
		}
		$to = table_common_member::t()->fetch_by_username($_GET['to']);
		if(!$to) {
			showmessage('memcp_credits_transfer_msg_user_incorrect', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
		}

		loaducenter();
		$ucresult = uc_user_login(addslashes($_G['member']['loginname']), $_GET['password']);
		list($tmp['uid']) = $ucresult;

		if($tmp['uid'] <= 0) {
			showmessage('credits_password_invalid', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
		}

		updatemembercount($_G['uid'], [$_G['setting']['creditstransextra'][9] => -$amount], 1, 'TFR', $to['uid']);
		updatemembercount($to['uid'], [$_G['setting']['creditstransextra'][9] => $netamount], 1, 'RCV', $_G['uid']);

		if(!empty($_GET['transfermessage'])) {
			$transfermessage = dhtmlspecialchars($_GET['transfermessage']);
			notification_add($to['uid'], 'credit', 'transfer', ['credit' => $_G['setting']['extcredits'][$_G['setting']['creditstransextra'][9]]['title'].' '.$netamount.' '.$_G['setting']['extcredits'][$_G['setting']['creditstransextra'][9]]['unit'], 'transfermessage' => $transfermessage]);
		}
		showmessage('credits_transfer_succeed', 'home.php?mod=spacecp&ac=credit&op=transfer', [], ['showdialog' => 1, 'showmsg' => true, 'locationtime' => true]);
	}

} elseif($_GET['op'] == 'exchange') {

	if(!$_G['setting']['exchangestatus']) {
		showmessage('action_closed', NULL);
	}
	$_CACHE['creditsettings'] = [];
	if(file_exists(DISCUZ_ROOT.'/data/cache/creditsettings.php')) {
		include_once(DISCUZ_ROOT.'/data/cache/creditsettings.php');
	}

	if(submitcheck('exchangesubmit')) {
		if($_G['setting']['submitlock'] && discuz_process::islocked('exchangelock_'.$_G['uid'], 0, 1)) {
			showmessage('memcp_credits_exchange_msg_locked', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
		}

		$tocredits = $_GET['tocredits'];
		$fromcredits = $_GET['fromcredits'];
		$exchangeamount = $_GET['exchangeamount'];
		$outexange = strexists($tocredits, '|');
		if($outexange && !empty($_GET['outi'])) {
			$fromcredits = $_GET['fromcredits_'.$_GET['outi']];
		}

		if($fromcredits == $tocredits) {
			showmessage('memcp_credits_exchange_msg_num_invalid', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
		}
		if($outexange) {
			$netamount = floor($exchangeamount * $_CACHE['creditsettings'][$tocredits]['ratiosrc'][$fromcredits] / $_CACHE['creditsettings'][$tocredits]['ratiodesc'][$fromcredits]);
		} else {
			if($_G['setting']['extcredits'][$tocredits]['ratio'] < $_G['setting']['extcredits'][$fromcredits]['ratio']) {
				$netamount = ceil($exchangeamount * $_G['setting']['extcredits'][$tocredits]['ratio'] / $_G['setting']['extcredits'][$fromcredits]['ratio'] * (1 + $_G['setting']['creditstax']));
			} else {
				$netamount = floor($exchangeamount * $_G['setting']['extcredits'][$tocredits]['ratio'] / $_G['setting']['extcredits'][$fromcredits]['ratio'] * (1 + $_G['setting']['creditstax']));
			}
		}
		if(!$outexange && !$_G['setting']['extcredits'][$tocredits]['ratio']) {
			showmessage('credits_exchange_invalid', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
		}
		if(!$outexange && !$_G['setting']['extcredits'][$fromcredits]['allowexchangeout']) {
			showmessage('extcredits_disallowexchangeout', '', ['credittitle' => $_G['setting']['extcredits'][$fromcredits]['title']], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
		}
		if(!$outexange && !$_G['setting']['extcredits'][$tocredits]['allowexchangein']) {
			showmessage('extcredits_disallowexchangein', '', ['credittitle' => $_G['setting']['extcredits'][$tocredits]['title']], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
		}
		if(!$netamount) {
			showmessage('memcp_credits_exchange_msg_balance_insufficient', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
		} elseif($exchangeamount <= 0) {
			showmessage('credits_transaction_amount_invalid', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
		} elseif(getuserprofile('extcredits'.$fromcredits) - $netamount < ($minbalance = $_G['setting']['exchangemincredits'])) {
			showmessage('credits_exchange_balance_insufficient', '', ['title' => $_G['setting']['extcredits'][$fromcredits]['title'], 'minbalance' => $minbalance], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
		}

		loaducenter();
		$ucresult = uc_user_login(addslashes($_G['member']['loginname']), $_GET['password']);
		list($tmp['uid']) = $ucresult;

		if($tmp['uid'] <= 0) {
			showmessage('credits_password_invalid', '', [], ['showdialog' => 1, 'showmsg' => true, 'closetime' => true]);
		}

		if(!$outexange) {
			updatemembercount($_G['uid'], [$fromcredits => -$netamount, $tocredits => $exchangeamount], 1, 'CEC', $_G['uid']);
		} else {
			if(!array_key_exists($fromcredits, $_CACHE['creditsettings'][$tocredits]['creditsrc'])) {
				showmessage('extcredits_dataerror', NULL);
			}
			list($toappid, $tocredits) = explode('|', $tocredits);
			$ucresult = uc_credit_exchange_request($_G['uid'], $fromcredits, $tocredits, $toappid, $exchangeamount);
			if(!$ucresult) {
				showmessage('extcredits_dataerror', NULL);
			}
			updatemembercount($_G['uid'], [$fromcredits => -$netamount], 1, 'ECU', $_G['uid']);
			$netamount = $amount;
			$amount = $tocredits = 0;
		}

		showmessage('credits_transaction_succeed', 'home.php?mod=spacecp&ac=credit&op=exchange', [], ['showdialog' => 1, 'showmsg' => true, 'locationtime' => true]);
	}
} else {
	$wheresql = '';
	$list = $sub_list = [];
	$rid = intval($_GET['rid']);
	if($_GET['rid']) {
		$wheresql = " AND rid='$rid'";
	}
	require_once libfile('function/forumlist');
	$select = forumselect(false, 0, $_GET['fid']);
	$keys = array_keys($_G['setting']['extcredits']);
	foreach(table_common_credit_rule::t()->fetch_all_by_rid($rid) as $value) {
		if(!helper_access::check_module('doing') && $value['action'] == 'doing') {
			continue;
		} elseif(!helper_access::check_module('blog') && $value['action'] == 'publishblog') {
			continue;
		} elseif(!helper_access::check_module('wall') && in_array($value['action'], ['guestbook', 'getguestbook'])) {
			continue;
		}
		list($action, $sub) = explode('/', $value['action']);
		if($sub) {
			$sub_list[$action][$value['action']] = $value;
		} else {
			if(empty($_GET['fid']) || in_array($value['action'], ['digest', 'post', 'reply', 'getattach', 'postattach'])) {
				if(checkvalue($value, $keys)) {
					$list[$value['action']] = $value;
				}
			}
		}
	}
	if(!empty($_GET['fid'])) {
		$_GET['fid'] = intval($_GET['fid']);
		$foruminfo = table_forum_forumfield::t()->fetch($_GET['fid']);
		$flist = dunserialize($foruminfo['creditspolicy']);
		foreach($flist as $action => $value) {
			list($action, $sub) = explode('/', $value['action']);
			if($sub) {
				$sub_list[$action][$value['action']] = $value;
			} else {
				$list[$value['action']] = $value;
			}

		}
	}

	$listNew = [];
	foreach($list as $action => $row) {
		$listNew[$action] = $row;
		if(isset($sub_list[$action])) {
			foreach($sub_list[$action] as $subRow) {
				$listNew[$subRow['action']] = $row;
				$listNew[$subRow['action']]['rulename'] = '';
				$listNew[$subRow['action']]['rid'] = $subRow['rid'];
				$listNew[$subRow['action']]['cycletype'] = $subRow['cycletype'];
				$listNew[$subRow['action']]['cycletime'] = $subRow['cycletime'];
				$listNew[$subRow['action']]['rewardnum'] = $subRow['rewardnum'];
			}
		}
	}
	$list = $listNew;
}
include_once template('home/spacecp_credit_base');

function checkvalue($value, $creditids) {
	$havevalue = false;
	foreach($creditids as $key) {
		if($value['extcredits'.$key]) {
			$havevalue = true;
			break;
		}
	}
	return $havevalue;
}

