<?php

if ( !defined( 'SMARTY_DIR' ) ) {
	include_once( '../init.php' );
}

include ( 'sessioninc.php' );

define( 'PAGE_ID', 'affiliate_stats' );

if ( !checkAdminPermission( PAGE_ID ) ) {

	header( 'location: not_authorize.php' );
	exit;
}

if (!isset($_REQUEST['sortby']) && $_SESSION['sortby'] != '') {

	$sortby = $_SESSION['sortby'];

} else {

//Default Sorting
	if ($_REQUEST['sortby'] == 'refcnt') {
		$sortby = ' refcnt ';
	} elseif ($_REQUEST['sortby'] == 'refcnt') {
		$sortby = ' usercnt ';
	} else {
		$sortby = ' a.name ';
	}
}

if (!isset($sortby) or $sortby == '') $sortby = ' a.name ';

$_SESSION['sortby'] = trim($sortby);

if (!isset($_REQUEST['sortorder']) && $_SESSION['sortorder'] != '') {

	$sortorder = $_SESSION['sortorder'];

} else {

	$sortorder = checkSortType($_REQUEST['sortorder']);
}

$page_size = getPageSize();

$_SESSION['sortorder'] = $sortorder;

//Paging View style

$page = (int)$_GET['offset'];

if( $page == 0 ) $page = 1;

$upr = ($page)*$page_size - $page_size;

$lwr = ($page)*$page_size ;

$rs =& $osDB->getAll( 'SELECT a. * , count( b.id )  AS refcnt, sum( if(b.userid>0,1,0) )  AS usercnt FROM  !  AS a LEFT  JOIN ! AS b ON b.affid = a.id where a.status in (?, ?) GROUP  BY a.id '.' order by '.$sortby. ' ' . $sortorder, array( AFFILIATE_TABLE, AFFILIATE_REFERALS_TABLE, 'active', get_lang('status_act','active') ) );

$totalrecs = count($rs);

$pages = ceil($totalrecs / $page_size);

if ($pages > 1) {
	$rs = array_slice($rs, $upr, $page_size);
}
$data=array();

$t->assign('psize', $page_size);

$t->assign( 'upr', $upr );

$t->assign('pages', $pages);

$t->assign( 'sortorder', trim($sortorder) );

$t->assign( 'data', $rs );

unset($rs);

$t->assign('lang',$lang);

$t->assign('rendered_page', $t->fetch('admin/affiliatestats.tpl'));

$t->display( 'admin/index.tpl' );


?>