<?php

/*
 * @component AltaUserPoints
 * @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 Joomla\CMS\Language\Text;
use BlackSheepResearch\Component\UserPoints\Site\UserPoints;
use BlackSheepResearch\Component\UserPoints\Site\Utils\Session;
use BlackSheepResearch\Component\UserPoints\Site\Problems\PointsUser;
use BlackSheepResearch\Component\UserPoints\Site\Problems\SQL;

class Userpoint extends UserModel {

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

    function _getParamsAUP() {

        // Get the parameters of the active menu item
        $app = Factory::getApplication();
        $menus = $app->getMenu();
        $menu = $menus->getActive();
        $menuid = $menu->id;
        $params = $menus->getParams($menuid);

        return $params;
    }

    function _get_last_points($referrerid, $limit = 10) {
        $db = SQL::getInstance();

        if ($limit == 'all') {
            // Get the pagination request variables
            list($limitstart, $limit) = PointsUser::getLimitsFromRequest();
            $q = "SELECT a.*, r.rule_name, r.plugin_function FROM #__alpha_userpoints_details AS a, #__alpha_userpoints_rules as r "
                    . "\nWHERE a.referreid = {$db->quote($referrerid)} AND a.rule_id=r.plugin_function AND r.displayactivity='1' AND a.enabled='1' "
                    . "\nORDER BY a.insert_date DESC";
            $total = $this->_getListCount($q);
            $result = $this->_getList($q, $limitstart, $limit);
            return array($result, $total, $limit, $limitstart);
        } elseif ($limit == 'nolimit') {  // used for export CSV
            $q = "SELECT a.*, r.rule_name, r.plugin_function FROM #__alpha_userpoints_details AS a, #__alpha_userpoints_rules as r "
                    . "\nWHERE a.referreid = {$db->quote($referrerid)} AND a.rule_id=r.plugin_function AND r.displayactivity='1' AND a.enabled='1' "
                    . "\nORDER BY a.insert_date DESC";
            $db->setQuery($q);
            $rowslastpoints = $db->loadObjectList();
            return $rowslastpoints;
        } else {
            $limit = "LIMIT " . $limit;
            $q = "SELECT a.*, r.rule_name, r.plugin_function FROM #__alpha_userpoints_details AS a, #__alpha_userpoints_rules as r "
                    . "\nWHERE a.referreid = {$db->quote($referrerid)} AND a.rule_id=r.plugin_function AND r.displayactivity='1' AND a.enabled='1' "
                    . "\nORDER BY a.insert_date DESC $limit";
            $db->setQuery($q);
            $rowslastpoints = $db->loadObjectList();
            return array($rowslastpoints, null, null, null);
        }
    }

    function _get_referrees($referrerid) {

        $db = SQL::getInstance();
        $now = SQL::datetimeSQL();
        $q = "SELECT a.id AS rid, a.userid, a.referreid, a.upnid, SUM(d.points) AS points, a.last_update, "
                . "a.referraluser, a.referrees, a.blocked, a.avatar, a.levelrank, a.leveldate, "
                . " a.profileviews, a.shareinfos, u.username, u.name FROM #__alpha_userpoints AS a "
                . " INNER JOIN #__users AS u ON a.userid = u.id "
                . " INNER JOIN #__alpha_userpoints_details AS d ON a.referreid =  d.referreid"
                . " WHERE a.referreid = {$db->quote($referrerid)} AND "
                . " d.approved='1' AND (d.expire_date > '$now' OR d.expire_date = '1000-01-01 00:00:00') AND `enabled`='1' "
                . " HAVING SUM(d.points) IS NOT NULL";
        $db->setQuery($q);
        $rowsreferrees = (array) $db->loadObjectList();
        return $rowsreferrees;
    }

    function _extractEmailsFromString($sChaine) {
        if (false !== preg_match_all('`\w(?:[-_.]?\w)*@\w(?:[-_.]?\w)*\.(?:[a-z]{2,4})`', $sChaine, $aEmails)) {
            if (is_array($aEmails[0]) && sizeof($aEmails[0]) > 0) {
                return array_unique($aEmails[0]);
            }
        }
        return null;
    }

    function _checkUser() {
        $app = Factory::getApplication();

        // active user
        $user = UserPoints::getUser();

        // check referre ID
        $referrerid = Session::get('referrerid');

        if (!$user->id || !$referrerid) {
            // TODO may need a redirect
            $app->enqueueMessage(Text::_('AUP_ALERT_NOT_AUTH'));
        } else {
            return $referrerid;
        }
    }

    function _getReferreid() {

        // check referre ID
        $referrerid = Session::get('referrerid');

        return $referrerid;
    }

    function _getUsersList() {

        $app = Factory::getApplication();

        $filter_order = $app->getUserStateFromRequest("com_userpoints.filter_order", 'filter_order', 'points', 'cmd');
        $filter_order_Dir = $app->getUserStateFromRequest("com_userpoints.filter_order_Dir", 'filter_order_Dir', 'desc', 'word');

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

        $db = SQL::getInstance();
        $orderby = " ORDER BY {$db->escape($filter_order)} $filter_order_Dir";

        $q = "SELECT id AS rid, points, referreid, last_update, referraluser, `name` AS usr_name, username AS usr_username, levelrank "
            . " FROM #__alpha_userpoints_combined WHERE published != 0 $orderby";

        $total = $this->_getListCount($q);
        $rows = $this->_getList($q, $limitstart, $limit);

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

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

    function _getArticleDescription($idArticle) {

        $db = SQL::getInstance();

        $q = "SELECT id, title, introtext FROM #__content WHERE id = {$db->quote($idArticle)}";
        $db->setQuery($q);
        $result = $db->loadObjectList();

        return $result;
    }

    function _pointsearned() { // function for TOP 10 in statistics tab
        $db = SQL::getInstance();

        $q = "SELECT a.referreid, SUM(a.points) AS sumpoints, u.username AS username, u.name AS name"
                . " FROM #__alpha_userpoints_details AS a, #__alpha_userpoints AS aup, #__users AS u"
                . " WHERE aup.referreid=a.referreid AND aup.userid=u.id AND a.approved='1' AND a.status='1' AND a.enabled='1' AND aup.published='1'"
                . " GROUP BY a.referreid"
                . " ORDER BY sumpoints DESC"
                . " LIMIT 10"
        ;

        $db->setQuery($q);
        $result = $db->loadObjectList();

        return $result;
    }

    function _totalpoints() {

        $db = SQL::getInstance();

        $q = "SELECT SUM(a.points)"
                . " FROM #__alpha_userpoints_details AS a"
                . " WHERE a.approved='1' AND a.status='1' AND a.enabled='1'"
        ;

        $db->setQuery($q);
        $result = $db->loadResult();

        return $result;
    }

    function _mypointsearned($referreid) {

        $db = SQL::getInstance();

        $q = "SELECT SUM(a.points)"
                . " FROM #__alpha_userpoints_details AS a"
                . " WHERE a.approved='1' AND a.status='1' AND a.enabled='1' AND a.points>=1 AND a.referreid = {$db->quote($referreid)}";

        $db->setQuery($q);
        $result = $db->loadResult();

        return $result;
    }

    function _mypointsspent($referreid) {

        $db = SQL::getInstance();

        $q = "SELECT SUM(a.points)"
                . " FROM #__alpha_userpoints_details AS a"
                . " WHERE a.approved='1' AND a.status='1' AND a.enabled='1' AND a.points<0 AND a.referreid = {$db->quote($referreid)}";

        $db->setQuery($q);
        $result = $db->loadResult();

        return $result;
    }

    function _mypointsearnedthismonth($referreid) {

        $db = SQL::getInstance();

        $curmonth = date("Y-m-", SQL::unixtime());

        $q = "SELECT SUM(a.points)"
                . " FROM #__alpha_userpoints_details AS a"
                . " WHERE a.approved='1' AND a.status='1' AND a.enabled='1' AND a.points>=1 AND a.referreid = {$db->quote($referreid)} AND insert_date LIKE '{$curmonth}%'";

        $db->setQuery($q);
        $result = $db->loadResult();

        return $result;
    }

    function _mypointsspentthismonth($referreid) {

        $db = SQL::getInstance();

        $curmonth = date("Y-m-", SQL::unixtime());

        $q = "SELECT SUM(a.points)"
                . " FROM #__alpha_userpoints_details AS a"
                . " WHERE a.approved='1' AND a.status='1' AND a.enabled='1' AND a.points<0 AND a.referreid = {$db->quote($referreid)} AND insert_date LIKE '{$curmonth}%'";

        $db->setQuery($q);
        $result = $db->loadResult();

        return $result;
    }

    function _mypointsearnedthisday($referreid) {

        $db = SQL::getInstance();

        $curday = date("Y-m-d", SQL::unixtime());

        $q = "SELECT SUM(a.points)"
                . " FROM #__alpha_userpoints_details AS a"
                . " WHERE a.approved='1' AND a.status='1' AND a.enabled='1' AND a.points>=1 AND a.referreid = {$db->quote($referreid)} AND insert_date LIKE '{$curday}%'";

        $db->setQuery($q);
        $result = $db->loadResult();

        return $result;
    }

    function _mypointsspentthisday($referreid) {

        $db = SQL::getInstance();

        $curday = date("Y-m-d", SQL::unixtime());

        $q = "SELECT SUM(a.points)"
                . " FROM #__alpha_userpoints_details AS a"
                . " WHERE a.approved='1' AND a.status='1' AND a.enabled='1' AND a.points<0 AND a.referreid = {$db->quote($referreid)} AND insert_date LIKE '{$curday}%'";

        $db->setQuery($q);
        $result = $db->loadResult();

        return $result;
    }

    function _save_profile() {
        $app = Factory::getApplication();
        //$post	= $app->input->post->get('post');
        $post = $app->input->post->getArray();

        if ($post['referreid'] == '') {
            echo "<script>window.history.go(-1);</script>\n";
            exit();
        }

        $row = new PointsUser();
        $row->save($post);

        $app->enqueueMessage(Text::_('AUP_CHANGE_SAVED'));
    }

    function checkNewTotal($referreid, $rule_id) {
        $db = SQL::getInstance();
        $now = PointsUser::datetimeSQL();

        /* recalculate for this user
        $q = "SELECT SUM(points) FROM #__alpha_userpoints_details WHERE `referreid`=" . $db->quote($referreid) . " AND `approved`='1' AND (`expire_date`>'$now' OR `expire_date`='1000-01-01 00:00:00') AND `enabled`='1'";
        $db->setQuery($q);
        $newtotal = $db->loadResult();
         *
         */

        $q = "UPDATE #__alpha_userpoints SET `last_update`='$now' WHERE `referreid` = {$db->quote($referreid)}";
        $db->setQuery($q);
        $db->execute();

        // update Ranks / Medals if necessary
        UserPoints::checkRankMedal($referreid, $rule_id);
    }

    function _getMyCouponCode($referreid) {
        $db = SQL::getInstance();
        $q = "SELECT d.* FROM #__alpha_userpoints_details AS d, #__alpha_userpoints_rules AS r
                WHERE d.referreid={$db->quote($referreid)} AND d.enabled='1' AND d.rule_id=r.plugin_function
		AND r.plugin_function='sysplgup_couponpointscodes'";
        $db->setQuery($q);
        $resultCoupons = $db->loadObjectList();
        return $resultCoupons;
    }

}
