<?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\Uri\Uri;
use Joomla\CMS\Language\Text;
use Joomla\CMS\HTML\HTMLHelper;
use BlackSheepResearch\Component\UserPoints\Administrator\Model;
use BlackSheepResearch\Component\UserPoints\Site\Problems\LevelRankData;
use BlackSheepResearch\Component\UserPoints\Site\Problems\Medal;
use BlackSheepResearch\Component\UserPoints\Site\Problems\PointsUser;
use BlackSheepResearch\Component\UserPoints\Site\Problems\SQL;

class Levelrank extends Model {

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

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

        $filter_order = $app->getUserStateFromRequest('com_userpoints.filter_order_rank', 'filter_order_rank', 'ordering', 'cmd');
        $filter_order_Dir = $app->getUserStateFromRequest('com_userpoints.filter_order_Dir_rank', 'filter_order_Dir_rank', 'ASC', 'word');
        $filter_category_id = Factory::getApplication()->input->get('filter_category_id', 0, 'int');

        // Get the pagination request variables
        list($limitstart, $limit) = LevelRankData::getLimitsFromRequest();
        $total = $filter_category_id ? LevelRankData::countByFieldvalue('category', $filter_category_id) : LevelRankData::countAll();
        $results = LevelRankData::getLimitedRange($limitstart, $limit, 'category', $filter_category_id);
        
        /*
        $filter = '';
        if ($filter_category_id) {
            $filter .= " WHERE category='" . $filter_category_id . "'";
        }

        if ($filter_order) {
            $orderby = ' ORDER BY typerank ASC,' . $filter_order . ' ' . $filter_order_Dir . ', levelpoints DESC';
        } else {
            $orderby = ' ORDER BY typerank ASC, ordering ASC, levelpoints DESC';
        }

        //$query = "SELECT *, '' AS numrank, '' AS nummedals FROM #__alpha_userpoints_levelrank "
        $query = "SELECT *, '' AS numrank, '' AS nummedals, '' AS category_title FROM #__alpha_userpoints_levelrank "
                . $filter
                . $orderby;
        $total = @$this->_getListCount($query);
        $results = $this->_getList($query, $limitstart, $limit);

        for ($i = 0, $n = count($results); $i < $n; $i++) {
            $row = $results[$i];
            $row->numrank = PointsUser::levelrankCount($row->id);
            $row->nummedals = Medal::countAll();

            $row->category = ($row->category > 0) ? $row->category : 1;
            $query = "SELECT title FROM #__categories "
                    . "\nWHERE id='" . $row->category . "'";
            $db->setQuery($query);
            $row->category_title = $db->loadResult();

            if ($row->ruleid) {
                $query = "SELECT rule_name FROM #__alpha_userpoints_rules "
                        . "\nWHERE id='" . $row->ruleid . "'";
                $db->setQuery($query);
                $row->rulename = Text::_($db->loadResult());
            } else
                $row->rulename = "- " . Text::_('AUP_ALL') . " -";
        }
         * 
         */

        // table ordering
        $lists['order_Dir_rank'] = $filter_order_Dir;
        $lists['order_rank'] = $filter_order;

        $lists['filter_category_id'] = $filter_category_id;

        // choice folder for upload icons or large image medals/ranks
        $options[] = HTMLHelper::_('select.option', 'icons', Text::_('AUP_ICON'));
        $options[] = HTMLHelper::_('select.option', 'large', Text::_('AUP_IMAGE'));
        $lists['folder'] = HTMLHelper::_('select.radiolist', $options, 'folder', 'class="inputbox" size="1"', 'value', 'text', 'icons');

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

    function _edit_levelrank() {
        $db = SQL::getInstance();
        $cid = Factory::getApplication()->input->get('cid', array(0), 'array');
        $option = Factory::getApplication()->input->get('option', '', 'cmd');

        if (!is_array($cid)) {
            $cid = array(0);
        }

        $row = new LevelRankData($cid[0]);
        $lists = array();

        $oplistType[] = HTMLHelper::_('select.option', '0', Text::_('AUP_RANK'));
        $oplistType[] = HTMLHelper::_('select.option', '1', Text::_('AUP_MEDAL'));
        $lists['typerank'] = HTMLHelper::_('select.genericlist', $oplistType, 'typerank', 'class="inputbox" size="1"', 'value', 'text', $row->typerank);

        $query = "SELECT plugin_function, rule_name FROM #__alpha_userpoints_rules WHERE published='1'";
        $db->setQuery($query);
        $results = $db->loadObjectList();

        $oplistRules[] = HTMLHelper::_('select.option', '0', '- ' . Text::_('AUP_ALL') . ' -');
        foreach ($results as $result) {
            $oplistRules[] = HTMLHelper::_(
                            'select.option',
                            $result->plugin_function,
                            Text::_($result->rule_name)
            );
        }
        $lists['rules'] = HTMLHelper::_('select.genericlist', $oplistRules, 'rule_id', 'class="inputbox" size="1"', 'value', 'text', $row->rule_id);

        // choice folder for upload icons or large image medals/ranks
        $options[] = HTMLHelper::_('select.option', 'icons', Text::_('AUP_ICON'));
        $options[] = HTMLHelper::_('select.option', 'large', Text::_('AUP_IMAGE'));
        $lists['folder'] = HTMLHelper::_(
                        'select.radiolist',
                        $options,
                        'folder',
                        'class="inputbox" size="1"',
                        'value',
                        'text',
                        'icons'
        );
        $lists['filter_category_id'] = $row->category;

        return array($row, $lists);
    }

    function _delete_levelrank() {
        // initialize variables
        $cid = array_map('\\intval', Factory::getApplication()->input->get('cid', array(), 'array'));
        if (count($cid)) {
            LevelRankData::deleteMany($cid);
            // remove user medals
            Medal::deleteMany($cid, 'medal');
            // change level/rank user if necessary
            PointsUser::resetByLevelranks($cid);
        }
        $this->redirect('index.php?option=com_userpoints&task=levelrank');
    }

    function _save_levelrank($apply = 0) {

        $app = Factory::getApplication();

        // initialize variables
        $object = new \stdClass();
        $input = $app->input->post;

        $object->id = $input->getInt('id', 0);
        $object->rank = $input->getString('rank');
        $object->description = $input->getRaw('description');
        $object->category = $input->getInt('category', 0);
        $object->typerank = $input->getInt('typerank', 0);
        $object->levelpoints = $input->get('levelpoints', 0);
        $object->rule_id = $input->getString('rule_id', 0);
        $object->icon = $input->get('icon');
        $object->image = $input->get('image');
        $object->notification = $input->getInt('notification', 0);
        $object->emailsubject = $input->getString('emailsubject');
        $object->emailbody = $input->getRaw('emailbody');
        $object->emailformat = $input->getInt('emailformat', 0);
        $object->bcc2admin = $input->getInt('bcc2admin', 0);

        $row = new LevelRankData();
        $row->save($object);

        $msg = Text::_('AUP_DETAILSSAVED');

        // launch recalculation for all users
        $this->redirect('index.php?option=com_userpoints&task=recalculate', $msg);
    }

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

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

        $cid = Factory::getApplication()->input->get('cid', 0, 'int');
        $typerank = Factory::getApplication()->input->get('typerank', 0, 'int');

        switch ($typerank) {
            case '1' :
                $total = Medal::countByFieldvalue('medal', $cid);
                $results = Medal::selectionWithMedal($cid, $limitstart, $limit);
                break;

            default :
                $query = "SELECT aup.leveldate AS dateawarded, '' AS reason, u.name, u.username, lv.id AS cid, lv.typerank, lv.icon, lv.rank FROM #__alpha_userpoints AS aup"
                        . "\n LEFT JOIN #__alpha_userpoints_levelrank AS lv ON aup.levelrank=lv.id"
                        . "\n LEFT JOIN #__users AS u ON aup.userid=u.id"
                        . "\n WHERE aup.levelrank=$cid"
                        . "\nORDER BY aup.leveldate DESC";
                $total = $this->_getListCount($query);
                $results = $this->_getList($query, $limitstart, $limit);
        }

        return array($results, $total, $limit, $limitstart);
    }

    function orderItem($item, $movement) {
        $levelrank = new LevelRankData($item);
        $levelrank->changeOrder($movement > 0 ? 'up' : 'down');
        return true;
    }

    function setOrder($items) {
        $order = array_map('\\intval', Factory::getApplication()->input->get('order', array(), 'array'));
        LevelRankData::reorder($items, $order);
        return true;
    }
}
