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

require_once cot_incfile('payments', 'module');

$pid = cot_import('pid', 'G', 'INT');

$billservice = cot_import('billservice', 'G', 'TXT');
$paymentType = cot_import('paymentType', 'G', 'TXT');

$pay_type = cot_import('pay_type', 'G', 'TXT');
$action_type = cot_import('action_type', 'G', 'TXT');
$from_type = cot_import('from_type', 'G', 'TXT');
$payment_id = cot_import('payment_id', 'G', 'INT');
$summ = cot_import('sum', 'G', 'NUM');

if(empty($billservice)) $billservice = $pay_type;

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

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

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

$summ = round($summ,0);

if(empty($pid))
{
  if($from_type == 'balance') {
		/* === Hook === */
		foreach (cot_getextplugins('payments.balance.billing.import') as $pl)
		{
			include $pl;
		}
		/* ===== */

		cot_check(empty($summ), 'payments_balance_billing_error_emptysumm');
		cot_check(!empty($summ) && $summ < 0, 'payments_balance_billing_error_wrongsumm');

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

		if (!cot_error_found())
		{
			$options['desc'] = $L['payments_balance_billing_desc'];
			$options['code'] = $pid;

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

      $pid = cot_payments_create_order('balance', $summ, $options, $billservice);
			if($pid > 0) {
        cot_redirect(cot_url('payments', 'm=billing&pid=' . $pid . '&billservice=' . $billservice  . '&paymentType=' . $paymentType, '', true));
        exit;
      }
    }
  }

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

  if($pid > 0)
  {
  	cot_redirect(cot_url('payments', 'm=billing&pid='.$pid, '', true));
  } else {
    cot_redirect(cot_url('payments', 'm=error&msg=2', '', true));
  }
}

// Получаем информацию о заказе
if ($pinfo = cot_payments_payinfo($pid))
{
	// Блокируем доступ к несобственным платежкам
	cot_block($usr['id'] == $pinfo['pay_userid']);

  $isbalance = true;

	// Если счета пользователей	 включены, то проверяем баланс
	if ($cfg['payments']['balance_enabled'] && $pinfo['pay_area'] != 'balance' && $usr['id'] > 0)
	{
		$ubalance = cot_payments_getuserbalance($usr['id'], ($pinfo['pay_paydodji'] == 1));
		if ($ubalance >= $pinfo['pay_summ'])
		{
			if (cot_payments_updatestatus($pid, 'paid'))
			{
	      cot_payments_updateuserbalance($usr['id'], -$pinfo['pay_summ'], $pid, ($pinfo['pay_paydodji'] == 1));

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

				if(!empty($pinfo['pay_redirect'])){
					$pinfo['pay_redirect'] = str_replace($cfg['mainurl'] . '/', '', $pinfo['pay_redirect']);
          $pinfo['pay_redirect'] = str_replace($cfg['mainurl'], '', $pinfo['pay_redirect']);
					cot_redirect($pinfo['pay_redirect']);
				}else{ 
          cot_redirect(cot_url('payments', 'm=balance'));
				}
			}
      $isbalance = false;
		}
  }

	if($isbalance){
    if($pinfo['pay_paydodji'] == 1) {
      cot_redirect(cot_url('payments', 'm=error&msg=2', '', true));
    } else {
    	// Выводим подключенные платежные системы
    	if ($cot_billings)
    	{
    		if (count($cot_billings) == 1 || (!empty($billservice) && is_array($cot_billings[$billservice])))
    		{
    			foreach ($cot_billings as $bname => $bill)
    			{
    				if(count($cot_billings) == 1 || $billservice == $bname) cot_redirect(cot_url('plug', 'e=' . $bill['plug'] . '&pid=' . $pid . '&paymentType=' . $paymentType, '', true));
    			}
    		}
    		else
    		{
    			/* === Hook === */
    			$extp = cot_getextplugins('payments.billing.loop');
    			/* ===== */

    			foreach ($cot_billings as $bill)
    			{
    				$t->assign(array(
    					'BILL_ROW_TITLE' => $bill['title'],
    					'BILL_ROW_ICON' => $bill['icon'],
    					'BILL_ROW_URL' => cot_url('plug', 'e=' . $bill['plug'] . '&pid=' . $pid . '&paymentType=' . $paymentType),
    				));

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

    				$t->parse('MAIN.BILLINGS.BILL_ROW');
    			}
    			$t->parse('MAIN.BILLINGS');
    		}
    	}
    	else
    	{
    		/* === Hook === */
    		foreach (cot_getextplugins('payments.billing.empty') as $pl)
    		{
    			include $pl;
    		}
    		/* ===== */

    		$t->parse('MAIN.EMPTYBILLINGS');
    	}
    }
	}
}
else
{
	cot_redirect(cot_url('payments', 'm=error&msg=2', '', true));
}

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

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