<?php

/**
 * Payments module
 *
 * @package payments
 * @version 1.1.2
 * @author CMSWorks Team
 * @copyright Copyright (c) CMSWorks.ru
 * @license BSD
 */
defined('COT_CODE') or die('Wrong URL.');

list($usr['auth_read'], $usr['auth_write'], $usr['isadmin']) = cot_auth('payments', 'any', 'RWA');
cot_block($usr['auth_write']);

require_once cot_incfile('forms');

$n = cot_import('n', 'G', 'ALP');
$pid = cot_import('pid', 'G', 'INT');
$rsumm = cot_import('rsumm', 'G', 'NUM');

if (empty($n))
{
	$n = 'history';
}

/* === Hook === */
foreach (cot_getextplugins('payments.balance.first') as $pl)
{
	include $pl;
}
/* ===== */

$t = new XTemplate(cot_tplfile('payments.balance', 'module'));

/* === Hook === */
foreach (cot_getextplugins('payments.balance.main') as $pl)
{
	include $pl;
}
/* ===== */

$t->assign(array(
	'BALANCE_SUMM' => round(cot_payments_getuserbalance($usr['id']), 0),
  'BALANCE_SUMM_DODJI' => round(cot_payments_getuserbalance($usr['id'], true), 0),
	'BALANCE_BILLING_URL' => cot_url('payments', 'm=balance&n=billing'),
	'BALANCE_HISTORY_URL' => cot_url('payments', 'm=balance&n=history'),
	'BALANCE_PAYOUT_URL' => cot_url('payments', 'm=balance&n=payouts'),
	'BALANCE_TRANSFER_URL' => cot_url('payments', 'm=balance&n=transfers'),
  'BALANCE_PROFILE_PAYMENT_YANDEX' => $usr['profile']['user_payment_yandex'],
	'BALANCE_PROFILE_PAYMENT_QIWI' => $usr['profile']['user_payment_qiwi'],
  'BALANCE_PROFILE_PAYMENT_WM' => $usr['profile']['user_payment_wm'],
  'BALANCE_PROFILE_PAYMENT_CARD_FN' => $usr['profile']['user_payment_card_fn'],
  'BALANCE_PROFILE_PAYMENT_CARD_LN' => $usr['profile']['user_payment_card_ln'],
  'BALANCE_PROFILE_PAYMENT_CARD_NUM' => $usr['profile']['user_payment_card_num'],
  'BALANCE_PROFILE_PAYMENT_YANDEX_SECURE' => (!empty($usr['profile']['user_payment_yandex']) ? preg_replace('/([0-9]{3})(.*)([0-9]{4})/ism', "$1****$3", $usr['profile']['user_payment_yandex']) : ''),
	'BALANCE_PROFILE_PAYMENT_QIWI_SECURE' => (!empty($usr['profile']['user_payment_qiwi']) ? preg_replace('/([0-9]{3})(.*)([0-9]{4})/ism', "$1****$3", $usr['profile']['user_payment_qiwi']) : ''),
  'BALANCE_PROFILE_PAYMENT_WM_SECURE' => (!empty($usr['profile']['user_payment_wm']) ? preg_replace('/([A-z0-9]{3})([0-9]+)([0-9]{4})/ism', "$1****$3", $usr['profile']['user_payment_wm']) : ''),
  'BALANCE_PROFILE_PAYMENT_CARD_NUM_SECURE' => (!empty($usr['profile']['user_payment_card_num']) ? preg_replace('/([0-9]{4})([0-9]+)([0-9]{4})/ism', "$1 **** **** $3", $usr['profile']['user_payment_card_num']) : ''),
));

if ($n == 'billing')
{
	$pid = cot_import('pid', 'G', 'INT');

	/* === Hook === */
	foreach (cot_getextplugins('payments.balance.billing.first') as $pl)
	{
		include $pl;
	}
	/* ===== */

	$rsumm = (!empty($rsumm)) ? $rsumm : $summ;

	$t->assign(array(
		'BALANCE_FORM_ACTION_URL' => cot_url('payments', 'm=balance&n=billing&a=buy&pid=' . $pid),
		'BALANCE_FORM_SUMM' => cot_inputbox('text', 'summ', $rsumm),
	));

	/* === Hook === */
	foreach (cot_getextplugins('payments.balance.billing.tags') as $pl)
	{
		include $pl;
	}
	/* ===== */

	$t->parse('MAIN.BILLINGFORM');
}

if ($n == 'payouts')
{
	cot_block($cfg['payments']['payouts_enabled']);

  $payout_type = cot_import('payout_type', 'P', 'TXT');
  $action_type = cot_import('action_type', 'P', 'TXT');
  $funds_sum = cot_import('funds_sum', 'P', 'NUM');
	
	/* === Hook === */
	foreach (cot_getextplugins('payments.balance.payouts.first') as $pl)
	{
		include $pl;
	}
	/* ===== */

	if ($action_type == 'withdraw' && in_array($payout_type, array('yandex', 'qiwi', 'wm', 'card')))
  {
    $payout_wallet = $usr['profile']['user_payment_'.$payout_type];
    $payout_wallet_text = $payout_wallet;
    if($payout_type == 'card') {
      $payout_wallet = $usr['profile']['user_payment_card_num'];
      $payout_wallet_text = $usr['profile']['user_payment_card_num'].', владелец карты "'.$usr['profile']['user_payment_card_ln'].' '.$usr['profile']['user_payment_card_fn'].'"';
    }

		$details = 'Реквизиты пользователя: '.$cfg['payments']['payout_types_arr'][$payout_type].' '.$payout_wallet_text;

    $total = $funds_sum;

		/* === Hook === */
		foreach (cot_getextplugins('payments.balance.payouts.import') as $pl)
		{
			include $pl;
		}
		/* ===== */

		$ubalance = cot_payments_getuserbalance($usr['id']);
			
    cot_check(empty($payout_wallet), 'Укажите реквизиты "'.$cfg['payments']['payout_types_arr'][$payout_type].'" в настройках профиля');
		cot_check(empty($funds_sum), 'payments_balance_payout_error_emptysumm');
		cot_check(!empty($funds_sum) && $funds_sum < 0, 'payments_balance_payout_error_wrongsumm');
		cot_check($total > $ubalance, 'payments_balance_payout_error_balance');	

    if(is_array($cfg['payments']['payout_tax'][$payout_type])) {
      cot_check($cfg['payments']['payout_tax'][$payout_type]['minsum'] > 0 && $funds_sum < $cfg['payments']['payout_tax'][$payout_type]['minsum'], sprintf($L['payments_balance_payout_error_min'], $cfg['payments']['payout_tax'][$payout_type]['minsum'], $cfg['payments']['valuta']));
      cot_check($cfg['payments']['payout_tax'][$payout_type]['maxsum'] > 0 && $funds_sum > $cfg['payments']['payout_tax'][$payout_type]['maxsum'], sprintf($L['payments_balance_payout_error_max'], $cfg['payments']['payout_tax'][$payout_type]['maxsum'], $cfg['payments']['valuta']));
    } else {
      cot_check(true, 'Выплата по данной платежной системе не доступна. Обратитесь в службу поддержки.');
    }

    cot_check(($usr['profile']['user_payoutsblock'] > 0 && $usr['profile']['user_payoutsblock'] > $sys['now']), 'В целях безопасности, вы сможете отправить заявку на вывод после '.cot_date('d.m.Y H:i', $usr['profile']['user_payoutsblock']));

		/* === Hook === */
		foreach (cot_getextplugins('payments.balance.payouts.validate') as $pl)
		{
			include $pl;
		}
		/* ===== */

		if(!cot_error_found())
		{
      $rpayout['out_date'] = $sys['now'];
			$rpayout['out_userid'] = $usr['id'];
			$rpayout['out_summ'] = $total;
			$rpayout['out_details'] = $details;
			$rpayout['out_status'] = 'moderation';

      $rpayout['out_type'] = $payout_type;
      $rpayout['out_wallet'] = $payout_wallet;

			/* === Hook === */
			foreach (cot_getextplugins('payments.balance.payouts.options') as $pl)
			{
				include $pl;
			}
			/* ===== */

			if($db->insert($db_payments_outs, $rpayout)){
				$oid = $db->lastInsertId();

				$payinfo['pay_userid'] = $usr['id'];
				$payinfo['pay_area'] = 'payout';
				$payinfo['pay_code'] = $oid;
				$payinfo['pay_summ'] = $total;
				$payinfo['pay_cdate'] = $sys['now'];
				$payinfo['pay_pdate'] = $sys['now'];
				$payinfo['pay_adate'] = $sys['now'];
				$payinfo['pay_status'] = 'done';
				$payinfo['pay_desc'] = $L['payments_balance_payout_desc'];

				$db->insert($db_payments, $payinfo);
				$pid = $db->lastInsertId();

        $db->update($db_payments_outs, array('out_payid' => $pid), 'out_id='.$oid);

				cot_payments_updateuserbalance($usr['id'], -$total, $pid);

				// Отправка уведомления админу о новой заявке на вывод
				$subject = $L['payments_balance_payout_admin_subject'];
				$body = sprintf($L['payments_balance_payout_admin_body'], $usr['name'], $funds_sum.' '.$cfg['payments']['valuta'], $oid, cot_date('d.m.Y в H:i', $sys['now']), $details);
				cot_mail($cfg['adminemail'], $subject, $body);
				
				/* === Hook === */
				foreach (cot_getextplugins('payments.balance.payouts.done') as $pl)
				{
					include $pl;
				}
				/* ===== */
			}
		}
		cot_redirect(cot_url('payments', 'm=balance&n=payouts', '', true));
	}
	

	$payouts = $db->query("SELECT * FROM $db_payments_outs AS o
		LEFT JOIN $db_payments AS p ON p.pay_code=o.out_id AND p.pay_area='payout'
		WHERE out_userid=" . $usr['id'] . "
		ORDER BY pay_cdate DESC")->fetchAll();

	if(count($payouts) > 0)
	{
		/* === Hook === */
		$extp = cot_getextplugins('payments.balance.payouts.loop');
		/* ===== */

		foreach ($payouts as $payout)
		{
			$t->assign(array(
				'PAYOUT_ROW_ID' => $payout['out_id'],
				'PAYOUT_ROW_SUMM' => $payout['out_summ'],
				'PAYOUT_ROW_CDATE' => $payout['pay_cdate'],
				'PAYOUT_ROW_DATE' => $payout['out_date'],
				'PAYOUT_ROW_STATUS' => $payout['out_status'],
				'PAYOUT_ROW_LOCALSTATUS' => $L['payments_balance_payout_status_'.$payout['out_status']],
			));

			/* === Hook - Part2 : Include === */
			foreach ($extp as $pl)
			{
				include $pl;
			}
			/* ===== */
				
			$t->parse('MAIN.PAYOUTS.PAYOUT_ROW');
		}
	}
	$t->parse('MAIN.PAYOUTS');

	/* === Hook === */
	foreach (cot_getextplugins('payments.balance.payouts.form') as $pl)
	{
		include $pl;
	}
	/* ===== */

	$t->parse('MAIN.PAYOUTFORM');
}

if ($n == 'history')
{
	list($pg, $d, $durl) = cot_import_pagenav('d', $cfg['maxrowsperpage']);

  $from = cot_import('from', 'G', 'TXT');
  $to = cot_import('to', 'G', 'TXT');
  $operation = cot_import('operation', 'G', 'ARR');

  $list_row_url = array('m' => 'balance', 'from' => $from, 'to' => $to, 'operation' => $operation);

  $where = array();

  if(!empty($from)) {
    $tmpval = cot_date2stamp($from, 'd.m.Y');
    if($tmpval > 0) {
      $where['date_from'] = 'pay_pdate>'.$tmpval;
    }
  }
  if(!empty($to)) {
    $tmpval = cot_date2stamp($to, 'd.m.Y');
    if($tmpval > 0) {
      $where['date_to'] = 'pay_pdate<'.$tmpval;
    }
  }

  $where['pay_area'] = array();

	/* === Hook === */
	foreach (cot_getextplugins('payments.balance.history.query') as $pl)
	{
		include $pl;
	}
	/* ===== */

  if(in_array('refill', $operation)) {  //Пополнение баланса
     $where['pay_area'][] = "pay_area='balance'";
  }
  if(in_array('withdraw', $operation)) {  //Вывод
     $where['pay_area'][] = "pay_area='payout'";
  }
  if(count($where['pay_area']) > 0) {
    $where['pay_area'] = '('.implode(' OR ', $where['pay_area']).')';
  } else {
    unset($where['pay_area']);
  }

  $where = (count($where) > 0) ? ' AND '.implode(' AND ', $where) : '';

	$totallines = $db->query("SELECT COUNT(*) FROM $db_payments 
		WHERE pay_userid=" . $usr['id'] . " AND pay_status='done' AND (pay_summ>0 OR pay_dodji>0) $where")->fetchColumn();
	$pays = $db->query("SELECT * FROM $db_payments 
		WHERE pay_userid=" . $usr['id'] . " AND pay_status='done' AND (pay_summ>0 OR pay_dodji>0) $where
		ORDER BY pay_pdate DESC LIMIT $d, ".$cfg['maxrowsperpage'])->fetchAll();

	$pagenav = cot_pagenav('payments', $list_row_url, $d, $totallines, $cfg['maxrowsperpage']);

	$t->assign(array(
		'HISTORY_COUNT' => $totallines,
		'PAGENAV_PAGES' => $pagenav['main'],
		'PAGENAV_PREV' => $pagenav['prev'],
		'PAGENAV_NEXT' => $pagenav['next'],
		'PAGENAV_CURRENTPAGE' => $pagenav['current'],
	));

	/* === Hook === */
	$extp = cot_getextplugins('payments.balance.history.loop');
	/* ===== */

	foreach ($pays as $pay)
	{
    $t->assign(cot_generate_paytags($pay, 'HIST_ROW_'));

		/* === Hook - Part2 : Include === */
		foreach ($extp as $pl)
		{
			include $pl;
		}
		/* ===== */

		$t->parse('MAIN.HISTORY.HIST_ROW');
	}
	$t->parse('MAIN.HISTORY');
}

/* === Hook === */
foreach (cot_getextplugins('payments.balance.tags') as $pl)
{
	include $pl;
}
/* ===== */

cot_display_messages($t, 'MAIN');

$t->parse('MAIN');
$module_body = $t->text('MAIN');

?>