<?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\Administrator\Models;

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\Component\ComponentHelper;
use BlackSheepResearch\Component\UserPoints\Administrator\Model;
use BlackSheepResearch\Component\UserPoints\Site\UserPoints;
use BlackSheepResearch\Component\UserPoints\Site\Problems\SQL;
use BlackSheepResearch\Component\UserPoints\Site\Problems\PointsUser;
use BlackSheepResearch\Component\UserPoints\Site\Problems\PointsDetails;

class Users extends Model {

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

    function _setmaxpoints() {
        die('Setting max points now in Options');
    }

    function _resetpoints() {
        PointsUser::refreshEveryUser();
        // load external plugins
        PluginHelper::importPlugin('userpoints');
        $this->triggerEvent('onResetGeneralPointsUserPoints', [date('Y-m-d H:i:s')]);
        return true;
    }

    function _recalculate_points() {
        $this->_purge_expires();
    }

    public function Recalc() {
        UserPoints::recalcPointsAndMedals();
    }

    public function Synchro() {
        PointsUser::recordNewUsers();
    }

    function _purge_expires() {
        PointsDetails::disableExpired();
        return true;
    }

    function _last_Activities() {

        $db = SQL::getInstance();
        $now = SQL::datetimeSQL();
        $nulldt = SQL::nulldatetimeSQL();
        $days = intval(ComponentHelper::getParams('com_userpoints')['latest_activities_days']);
        $query = "SELECT a.insert_date, a.referreid, a.points AS last_points, u.username AS usrname, u.name AS uname, aup.userid AS userID, r.rule_name"
                . " 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 aup.published='1' AND a.approved='1' AND a.enabled='1'"
                . " AND a.rule_id=r.plugin_function"
                . " AND (a.expire_date>= '$now' OR a.expire_date='$nulldt')"
                . " AND a.insert_date > DATE_SUB(NOW(), INTERVAL $days DAY) "
                . " ORDER BY a.insert_date DESC"
        ;
        $db->setQuery($query, 0, 10);
        $rows = $db->loadObjectList();

        return $rows;
    }

    function _load_activities() {

        $app = Factory::getApplication();

        $db = SQL::getInstance();

        $now = PointsUser::datetimeSQL();

        $filter_state = $app->getUserStateFromRequest('com_userpoints.filter_state', 'filter_state', '', 'string');
        $filter_order = $app->getUserStateFromRequest("com_userpoints.filter_order", 'filter_order', 'a.insert_date', 'cmd');
        $filter_order_Dir = $app->getUserStateFromRequest("com_userpoints.filter_order_Dir", 'filter_order_Dir', 'desc', 'word');
        $search = $app->getUserStateFromRequest("com_userpoints.search", 'search', '', 'string');

        // Get the pagination request variables
        list($limitstart, $limit) = PointsUser::getLimitsFromRequest();

        // check filter order
        if ($filter_order != 'a.insert_date' AND $filter_order != 'r.rule_name' AND $filter_order != 'u.name' AND $filter_order != 'u.username' AND $filter_order != 'a.points' AND $filter_order != 'a.approved') {
            $filter_order = 'a.insert_date';
        }

        if ($filter_state != '') {
            $filter = " AND a.approved={$db->quote($filter_state)} ";
        } else {
            $filter = " AND (a.approved='1' OR a.approved='0') ";
        }

        if ($search) {
            $where[] = 'LOWER(u.name) LIKE ' . $db->quote('%' . $db->escape($search, true) . '%');
            $where[] = 'LOWER(u.username) LIKE ' . $db->quote('%' . $db->escape($search, true) . '%');
            $where[] = 'LOWER(r.rule_name) LIKE ' . $db->quote('%' . $db->escape($search, true) . '%');
            $where[] = 'LOWER(a.insert_date) LIKE ' . $db->quote('%' . $db->escape($search, true) . '%');
        }
        $where = ( isset($where) ? " AND (" . implode(' OR ', $where) . ")" : "" );

        $orderby = " ORDER BY " . $filter_order . " " . $filter_order_Dir;

        $query = "SELECT a.id, a.insert_date, a.referreid, a.points AS last_points, a.approved, u.username AS usrname, u.name AS uname, aup.userid AS userID, r.rule_name"
                . " 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 aup.published='1'"
                . " AND a.rule_id=r.plugin_function"
                . " AND (a.expire_date>='$now' OR a.expire_date='1000-01-01 00:00:00')"
                . " AND a.enabled='1'"
                . $filter . $where
                . $orderby
        ;

        $total = @$this->_getListCount($query);
        $result = $this->_getList($query, $limitstart, $limit);

        $lists = array();
        $options[] = HTMLHelper::_('select.option', '', Text::_('AUP_ALL'));
        $options[] = HTMLHelper::_('select.option', '1', Text::_('AUP_APPROVED'));
        $options[] = HTMLHelper::_('select.option', '0', Text::_('AUP_UNAPPROVED'));
        $lists['filter_state'] = HTMLHelper::_('select.genericlist', $options, 'filter_state', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $filter_state);

        // table ordering
        $lists['order_Dir'] = $filter_order_Dir;
        $lists['order'] = $filter_order;
        // search filter
        $lists['search'] = $search;

        return array($result, $total, $limit, $limitstart, $lists);
    }

}
