<?php
/* ====================
[BEGIN_COT_EXT]
Hooks=admin.home.mainpanel
Order=1
[END_COT_EXT]
==================== */

defined('COT_CODE') or die('Wrong URL');

require_once cot_incfile('bstat', 'plug');

$tt = new XTemplate(cot_tplfile('bstat.admin.home.mainpanel', 'plug'));

if(!empty($cfg['plugin']['bstat']['period']))
{
	switch ($cfg['plugin']['bstat']['period']){
		case 'week':
			$mindate = $sys['now'] - 7*24*60*60;
			break;
		
		case 'month':
			$mindate = $sys['now'] - 30*24*60*60;
			break;
		
		case 'year':
			$mindate = $sys['now'] - 365*24*60*60;
			break;
		
		default :
			$mindate = $db->query("SELECT pay_adate FROM $db_payments WHERE pay_status='done' AND pay_area='balance' ORDER BY pay_adate ASC")->fetchColumn();
	}

	$mindate = mktime( 0, 0, 0, cot_date('m', $mindate), cot_date('d', $mindate), cot_date('Y', $mindate) );

	$maxdate = $sys['now'];
	$maxdate = mktime( 23, 59, 59, cot_date('m', $maxdate), cot_date('d', $maxdate), cot_date('Y', $maxdate) );

	$day = $mindate;
	while($day <= $maxdate){
		$nextday = $day + 24*60*60;
		$paysumm[$day]['debet'] = $db->query("SELECT SUM(pay_summ) FROM $db_payments WHERE pay_status='done' AND pay_area='balance' AND pay_desc='Пополнение счета' AND pay_summ>0 AND pay_adate >= ".$day." AND pay_adate < ".$nextday)->fetchColumn();
		$paysumm[$day]['credit'] = $db->query("SELECT SUM(pay_summ) FROM $db_payments WHERE pay_status='done' AND pay_area='balance' AND pay_summ<0 AND pay_adate >= ".$day." AND pay_adate < ".$nextday)->fetchColumn();
		$day = $nextday;
	}

	if(is_array($paysumm)){
		foreach($paysumm AS $day => $summ){
			$tt->assign(array(
				'PAY_ROW_DEBET_SUMM' => (!empty($summ['debet'])) ? $summ['debet'] : 0,
				'PAY_ROW_CREDIT_SUMM' => (!empty($summ['credit'])) ? abs($summ['credit']) : 0,
				'PAY_ROW_DAY' => $day,
			));
			$tt->parse('MAIN.PAY_ROW');
		}
	}
}

$sql = $db->query("SELECT SUM(pay_summ) AS summ, p.*, u.* FROM $db_payments AS p
	LEFT JOIN $db_users AS u ON u.user_id=p.pay_userid
	WHERE p.pay_area='balance' AND p.pay_status='done' GROUP BY p.pay_userid HAVING SUM(p.pay_summ) > 0 ORDER BY summ DESC");

$jj = 0;
$summ = 0;

while($bal = $sql->fetch()){
	$jj++;

	$tt->assign(cot_generate_usertags($bal, 'BAL_ROW_USER_'));
	$tt->assign(array(
		'BAL_ROW_SUMM' => $bal['summ'],
		"BAL_ROW_ODDEVEN" => cot_build_oddeven($jj)
	));

	$summ += $bal['summ'];

	$tt->parse('MAIN.BAL_ROW');
}

$tt->assign('BAL_SUMM', $summ);

$tt->parse('MAIN');
$line = $tt->text('MAIN');
