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

class Rules extends Model {

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

    function _load_rules() {
        $app = Factory::getApplication();
        $db = SQL::getInstance();

        $filter_category = $app->getUserStateFromRequest('com_userpoints' . '.filter_category', 'filter_category', 'all', 'word');

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

        if ($filter_category != 'all') {
            $filter = "WHERE r.category = {$db->quote($filter_category)}";
        } else {
            $filter = "";
        }

        // check if Kunena forum is installed to show pre-installed rules for Kunena
        // Dectects Kunena 2.0+
        if (class_exists('KunenaForum') && KunenaForum::enabled()) {
            ( $filter != '' ) ? $filter .= " AND " : $filter .= "WHERE ";
            $filter .= "(r.plugin_function!='plgaup_newtopic_kunena' AND r.plugin_function!='plgaup_reply_kunena' )";
            // Detects Kunena 1.6 and 1.7
        } elseif (class_exists('Kunena') && Kunena::enabled()) {
            if (substr(Kunena::version(), 0, 3) == '1.7') {
                ( $filter != '' ) ? $filter .= " AND " : $filter .= "WHERE ";
                $filter .= "(r.plugin_function!='plgaup_newtopic_kunena' AND r.plugin_function!='plgaup_reply_kunena' )";
            } else {
                ( $filter != '' ) ? $filter .= " AND " : $filter .= "WHERE ";
                $filter .= "(r.plugin_function!='plgaup_kunena_topic_create' AND r.plugin_function!='plgaup_kunena_topic_reply' AND r.plugin_function!='plgaup_kunena_message_delete' AND r.plugin_function!='plgaup_kunena_message_thankyou')";
            }
        }
        // end check Kunena pre_installed rules

        $result = Rule::getRulesWithViewlevels($filter, $limitstart, $limit, $total);

        $lists = array();
        $options = array();
        $options[] = HTMLHelper::_('select.option', '', Text::_('JNONE'));
        $options[] = HTMLHelper::_('select.option', 'us', Text::_('AUP_CAT_USER'));
        $options[] = HTMLHelper::_('select.option', 'co', Text::_('AUP_CAT_COMMUNITY'));
        $options[] = HTMLHelper::_('select.option', 'ar', Text::_('AUP_CAT_ARTICLE'));
        $options[] = HTMLHelper::_('select.option', 'li', Text::_('AUP_CAT_LINK'));
        $options[] = HTMLHelper::_('select.option', 'po', Text::_('AUP_CAT_POLL_QUIZZ'));
        $options[] = HTMLHelper::_('select.option', 're', Text::_('AUP_CAT_RECOMMEND_INVITE'));
        $options[] = HTMLHelper::_('select.option', 'fo', Text::_('AUP_CAT_COMMENT_FORUM'));
        $options[] = HTMLHelper::_('select.option', 'vi', Text::_('AUP_CAT_VIDEO'));
        $options[] = HTMLHelper::_('select.option', 'ph', Text::_('CAT_CAT_PHOTO'));
        $options[] = HTMLHelper::_('select.option', 'mu', Text::_('AUP_CAT_MUSIC'));
        $options[] = HTMLHelper::_('select.option', 'sh', Text::_('AUP_CAT_SHOPPING'));
        $options[] = HTMLHelper::_('select.option', 'pu', Text::_('AUP_CAT_PURCHASING'));
        $options[] = HTMLHelper::_('select.option', 'cd', Text::_('AUP_CAT_COUPON_CODE'));
        $options[] = HTMLHelper::_('select.option', 'su', Text::_('AUP_CAT_SUBSCRIPTION'));
        $options[] = HTMLHelper::_('select.option', 'ga', Text::_('AUP_CAT_GAMING'));
        $options[] = HTMLHelper::_('select.option', 'sy', Text::_('AUP_CAT_SYSTEM'));
        $options[] = HTMLHelper::_('select.option', 'ot', Text::_('AUP_CAT_OTHER'));
        $options[] = HTMLHelper::_('select.option', 'all', Text::_('AUP_ALL'));
        $lists['filter_category'] = HTMLHelper::_('select.genericlist', $options, 'filter_category', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $filter_category);

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

    function _edit_rule() {
        $cid = Factory::getApplication()->input->get('cid', array(0), 'array');
        if (count($cid)) {
            return Rule::withRuleID($cid[0]);
        }
    }

    function _delete_rule() {
        // initialize variables
        $cid = array_map('\\intval', Factory::getApplication()->input->get('cid', array(), 'array'));
        $msgType = '';

        if (count($cid)) {
            // are there one or more rows to delete?
            $msg = Text::sprintf('AUP_MSGSUCCESSFULLYDELETED', Text::_('AUP_RULES'), '');
            if (count($cid) == 1) {
                $rule = Rule::withRuleID($cid[0]);
                if ($rule->system) {
                    $msg = Text::_('AUP_SYSTEM_RULES_NO_DELETE');
                    $msgType = 'error';
                }
                else {
                    $rule->delete();
                }
            }
            else {
                Rule::deleteMany($cid);
            }
        }
        $this->redirect('index.php?option=com_userpoints&task=rules', $msg, $msgType);
    }

    function _save_rule($apply = 0) {
        // initialize variables
        $post = Factory::getApplication()->input->getArray(array());
        $id = Factory::getApplication()->input->get('id', 0, 'int');
        $emailbody = Factory::getApplication()->input->get('emailbody', '', 'raw');
        $post['emailbody'] = $emailbody;

        if ($post['plugin_function'] == 'sysplgup_unlockmenus' || substr($post['plugin_function'], 0, 22) == 'sysplgup_unlockmenus_') {
            $post['content_items'] = implode(',', $post['content_items']);

            // $cache = Factory::getCache();
            // $cache->cleanCache();
        }

        if ($post['plugin_function'] == 'plgaup_clickonmenus' || substr($post['plugin_function'], 0, 20) == 'plgaup_clickonmenus_') {
            $post['content_items'] = implode(',', $post['content_items']);

            // $cache = Factory::getCache();
            // $cache->cleanCache();
        }

        if ($post['plugin_function'] == 'plgaup_readarticle_by_cat' || substr($post['plugin_function'], 0, 26) == 'plgaup_readarticle_by_cat_') {
            $post['categories'] = implode(',', $post['categories']);
        }

        $rule = new Rule();
        $rule->save($post);

        $msg = Text::_('AUP_RULESAVED');
        if (!$apply) {
            $this->redirect('index.php?option=com_userpoints&task=rules', $msg);
        } else {
            $this->redirect('index.php?option=com_userpoints&task=editrule&cid[]=' . $id, $msg);
        }
    }

    function _copy_rule() {
        // Initialize variables
        $cid = array_map('\\intval', Factory::getApplication()->input->get('cid', array(), 'array'));
        $failed = false;
        $j = 0;
        foreach ($cid as $id) {
            $rule = new Rule();

            $item = Rule::withRuleID($id);

            $unique = uniqid('', false);

            if ($item AND $item->blockcopy == '0') {

                // values loaded into array set for store
                $rule->id = NULL;
                $rule->rule_name = Text::_('AUP_COPYOF') . " " . Text::_($item->rule_name);
                $rule->rule_description = "";
                $rule->rule_plugin = $item->rule_plugin;
                $rule->plugin_function = $item->plugin_function . '_' . $unique;
                $rule->access = $item->access;
                $rule->component = $item->component;
                $rule->calltask = $item->calltask;
                $rule->taskid = $item->taskid;
                $rule->points = $item->points;
                $rule->points2 = $item->points2;
                $rule->percentage = $item->percentage;
                $rule->rule_expire = $item->rule_expire;
                $rule->sections = $item->sections;
                $rule->categories = $item->categories;
                $rule->content_items = $item->content_items;
                $rule->exclude_items = $item->exclude_items;
                $rule->published = 0;
                $rule->system = 0;
                $rule->duplicate = 1;
                $rule->blockcopy = 0;
                $rule->autoapproved = $item->autoapproved;
                $rule->fixedpoints = 1;
                $rule->category = $item->category;
                $rule->displaymsg = $item->displaymsg;
                $rule->msg = $item->msg;
                $rule->method = $item->method;
                $rule->notification = $item->notification;
                $rule->emailsubject = $item->emailsubject;
                $rule->emailbody = $item->emailbody;
                $rule->emailformat = $item->emailformat;
                $rule->bcc2admin = $item->bcc2admin;
                $rule->type_expire_date = $item->type_expire_date;
                $rule->chain = 0;
                $rule->linkup = intval($item->linkup);

                if (!$rule->save()) {
                    Factory::getApplication()->enqueueMessage($rule->getError(), 'error');
                    $failed = true;
                }
                $j++;
            }
        }

        Rule::reset();
        if ($failed) {
            return false;
        }
        $msg = Text::sprintf('AUP_XCOPYOFRULE', $j);
        $this->redirect('index.php?option=com_userpoints&task=rules', $msg);
    }

    /**
     * Set the access of selected rule
     */
    function setAccess($items, $access) {

        foreach ($items as $id) {
            $rule = Rule::withRuleID($id);
            $rule->access = $access;
            $rule->save();
        }
        return true;
    }

}
