<?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\Plugin\PluginHelper;
use BlackSheepResearch\Component\UserPoints\Administrator\Model;
use BlackSheepResearch\Component\UserPoints\Site\UserPoints;
use BlackSheepResearch\Component\UserPoints\Site\Problems\PointsDetails;
use BlackSheepResearch\Component\UserPoints\Site\Problems\PointsUser;
use BlackSheepResearch\Component\UserPoints\Site\Problems\Rule;
use BlackSheepResearch\Component\UserPoints\Site\Problems\SQL;

class User extends Model {

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

    function _load_details_user() {

        $app = Factory::getApplication();
        $referreuserid = Factory::getApplication()->input->get('cid', '', 'username');
        if (!$referreuserid) {
            $referreuserid = Factory::getApplication()->input->get('c2id', '', 'username');
        }
        $db = SQL::getInstance();
        // Get the pagination request variables
        list($limitstart, $limit) = PointsUser::getLimitsFromRequest();

        $query = "SELECT * FROM #__alpha_userpoints_details_combined "
            . " WHERE referreid={$db->quote($referreuserid)} AND enabled = 1 ORDER BY insert_date DESC";
        $total = $this->_getListCount($query);
        $result = $this->_getList($query, $limitstart, $limit);

        $lists['order_Dir'] = '';
        $lists['order'] = '';
        $lists['search'] = '';

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

    function _load_details_user_edit_user($cid) {
        // $referreuserid = UserPoints::getAnyUserReferreID($cid);
        $pointsuser = PointsUser::withTableID($cid);
        $referreuserid = $pointsuser->referreid;
         if (!$referreuserid) {
            $referreuserid = Factory::getApplication()->input->get('c2id', '', 'username');
        }
        $db = SQL::getInstance();
        $orderby = " ORDER BY a.insert_date DESC";

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

        $where = " AND a.referreid={$db->quote($referreuserid)} AND a.enabled='1' ";
        $query = "SELECT a.*, r.rule_name FROM #__alpha_userpoints_details AS a, #__alpha_userpoints_rules AS r WHERE a.rule_id=r.plugin_function " . $where . $orderby;
        $total = $this->_getListCount($query);
        $result = $this->_getList($query, $limitstart, $limit);

        $lists['order_Dir'] = '';
        $lists['order'] = '';
        $lists['search'] = '';

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

    function _edit_pointsDetails() {
        $cid = Factory::getApplication()->input->get('cid', array(0), 'array');
        if (!is_array($cid)) {
            $cid = array(0);
        }
        return new PointsDetails($cid[0]);
    }

    function _get_rule_name($id) {
        return Rule::withRuleID($id)->rule_name;
    }

    function _save_user_details() {
        $post = Factory::getApplication()->input->post->getArray();
        $detail = new PointsDetails();
        $detail->save($post);
        
        $this->checkNewTotal($post['referreid'], $post['rule']);

        $msg = Text::_('AUP_DETAILSSAVED');
        $redirect = 'index.php?option=com_userpoints&task=' . $post['redirect'];
        $this->redirect($redirect, $msg);
    }

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

        // initialize variables
        $cid = array_map('\\intval', Factory::getApplication()->input->get('cid', array(), 'array'));
        $c2id = Factory::getApplication()->input->get('c2id', '', 'username');

        $post = $app->input->post->getArray();
        // load external plugins
        PluginHelper::importPlugin('userpoints');
        $results = $this->triggerEvent('onBeforeDeleteUserActivityUserPoints', array($cid, $c2id));  // c2id = referreid
        //$msgType	= '';

        if (count($cid)) {

            $msg = Text::_('AUP_SUCCESSFULLYDELETED');
            /*
              $query = "DELETE FROM #__alpha_userpoints_details"
              . "\n WHERE (`id` = " . implode(' OR `id` = ', $cid) . ")"
              ;
             */
            PointsDetails::disableMany($cid);

            $results = $this->triggerEvent('onAfterDeleteUserActivityUserPoints', array($c2id));  // c2id = referreid
        }

        // recalculate for this user 
        $this->checkNewTotal($c2id);

        $app->enqueueMessage($msg);

        $redirect = 'index.php?option=com_userpoints&task=' . $post['redirect'];
        $this->redirect($redirect);
    }

    function _delete_user_all_activities() {

        $app = Factory::getApplication();

        // initialize variables
        $c2id = $app->input->get('c2id', '', 'username');

        $post = $app->input->post->getArray();
        //$msgType	= '';
        // load external plugins
        PluginHelper::importPlugin('userpoints');
        $results = $this->triggerEvent('onBeforeDeleteAllUserActivitiesUserPoints', array($c2id));  // c2id = referreid


        if ($c2id) {
            $msg = Text::_('AUP_SUCCESSFULLYDELETED');
            //$query = "DELETE FROM #__alpha_userpoints_details"
            $points = new PointsDetails($c2id);
            $points->disable();
            $results = $this->triggerEvent('onAfterDeleteAllUserActivitiesUserPoints', array($c2id));  // c2id = referreid
        }

        // recalculate for this user 
        $this->checkNewTotal($c2id);

        $app->enqueueMessage($msg);

        $redirect = 'index.php?option=com_userpoints&task=' . $post['redirect'];
        $this->redirect($redirect);
    }

    function checkNewTotal($referrerid, $rule_id = 0) {
        $pointsuser = PointsUser::withReferrerID($referrerid);
        $pointsuser->last_update = SQL::datetimeSQL();
        $pointsuser->save();
        // update Ranks / Medals if necessary		
        UserPoints::checkRankMedal($referrerid, $rule_id);
    }

}
