<?php

/**
 * @package		UserPoints for Joomla 4.x
 * @copyright	Copyright (C) 2015-2016. All rights reserved.
 * @license		GNU/GPL, see LICENSE.php
 * Joomla! is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 * See COPYRIGHT.php for copyright notices and details.
 */
namespace BlackSheepResearch\Component\UserPoints\Site\Modules;

// no direct access
defined('_JEXEC') or die('Restricted access');

use Joomla\CMS\Factory;
use Joomla\CMS\Helper\ModuleHelper;
use BlackSheepResearch\Component\UserPoints\Site\View;
use BlackSheepResearch\Component\UserPoints\Site\Problems\SQL;

class Mostactiveusers extends View {

    static protected $viewpath = '';

    public function __construct($controller) {
        Factory::getApplication()->getLanguage()->load('mod_userpoints_mostactiveusers', JPATH_SITE);
        parent::__construct($controller);
    }

    public function render($params) {
        $list = $this->getList($params);
        require(ModuleHelper::getLayoutPath('mod_userpoints_mostactiveusers'));
    }

    private function getList($params) {
        $db = SQL::getInstance();
        $count = intval($params->get('count', 5));
        $usrname = trim($params->get('usrname', 'name'));
        $exclude_users = $params->get('exclude_users', array());
        $usergroup_filter = $params->get('usergroup_filter', '');

        $q = "SELECT a.userid, a.points, a.$usrname AS usrname, a.referreid FROM #__alpha_userpoints_combined AS a ";
        if ($usergroup_filter) {
            $filters = implode(',', array_map('\\intval', $usergroup_filter));
            $where[] = "(SELECT COUNT(*) FROM #__user_usergroup_map AS m WHERE m.group_id IN ($filters) AND m.user_id = a.userid) = 0";
        }
        if ($exclude_users) {
            $filters = implode(',', array_map('\\intval', $exclude_users));
            $where[] = "a.userid NOT IN ($filters)";
        }
        $where[] = "a.published != 0";
        $q .= ' WHERE ' . implode(' AND ', $where) . " ORDER BY a.points DESC, a.$usrname ASC LIMIT $count";
        $db->setQuery($q);
        return $db->loadObjectList();
    }
}
