<?php

/*
 * @component UserPoints
 * @copyright Copyright (C) 2015-2022 Bernard Gilly - Adrien Roussel - Martin Brampton
 * @license : GNU/GPL
 * @Website : https://remository.com
 */
namespace BlackSheepResearch\Component\UserPoints\Site\Models;

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

use Joomla\CMS\Factory;
use BlackSheepResearch\Component\UserPoints\Site\Problems\PointsUser;

class Latestactivity extends UserModel {

    function __construct() {
        parent::__construct();
    }

    function getLatestActivity() {//$params
        $app = Factory::getApplication();
        $now = PointsUser::datetimeSQL();

        $format = $app->input->get('format');

        $menus = $app->getMenu();
        $menu = $menus->getActive();
        $menuid = $menu->id;
        $params = $menus->getParams($menuid);
        $rsscount = $params->get('count',5); // rss feed limt

        if ($format == 'feed' && (!$menuid || !$rsscount)) {
            $msg = 'Missing or incorect Itemid for Latest Activity Feed ! Aborting for security reason.';
            $this->redirect('/index.php', $msg, 'warning');
        }

        $activity = $params->get('activity', 0);

        $typeActivity = "";

        if ($activity == 1) {
            $typeActivity = " AND a.points >= 1";
        }
        elseif ($activity == 2) {
            $typeActivity = " AND a.points <= 0";
        }

        list($limitstart, $limit) = PointsUser::getLimitsFromRequest('feed' == $format ? $rsscount : 0);
        $q = "SELECT a.insert_date, a.referreid, a.points AS last_points, a.datareference, 
		u." . $params->get('usrname', 'username') . " AS usrname, 
		r.rule_name, r.plugin_function, r.category"
                . " FROM #__alpha_userpoints_details AS a, #__alpha_userpoints AS aup, #__users AS u, #__alpha_userpoints_rules AS r"
                . " WHERE aup.referreid=a.referreid AND aup.userid=u.id AND r.displayactivity='1' AND aup.published='1' 
		AND a.approved='1' AND a.enabled='1' 
		AND (a.expire_date>='" . $now . "' OR a.expire_date='1000-01-01 00:00:00') AND a.rule_id=r.plugin_function"
                . $typeActivity
                . " ORDER BY a.insert_date DESC";
        $total = $this->_getListCount($q);
        $result = $this->_getList($q, $limitstart, $limit);
        return array($result, $total, $limit, $limitstart);
    }

}
