<?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;

// no direct access
defined('_JEXEC') or die('Restricted access');

use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Filesystem\Folder;
use BlackSheepResearch\Component\UserPoints\Site\UserPoints;
use BlackSheepResearch\Component\UserPoints\Site\Problems\PointsUser;
use BlackSheepResearch\Component\UserPoints\Site\Problems\PointsDetails;
use BlackSheepResearch\Component\UserPoints\Site\Problems\ProblemBase;
use BlackSheepResearch\Component\UserPoints\Site\Controller;

/**
 * @package UserPoints
 */
class AdminController extends Controller {

    static protected $myspace = __NAMESPACE__;
    static protected $suffix = '';

    public function execute($task) {
        if (method_exists($this, $task)) {
            $this->$task();
        } else {
            $controllers = Folder::files(__DIR__ . '/Controllers');
            foreach ($controllers as $controller) {
                $classname = __NAMESPACE__ . '\\Controllers\\' . substr($controller, 0, -4);
                $methods = get_class_methods($classname);
                if (in_array($task, $methods)) {
                    $object = new $classname;
                    break;
                }
            }
            if (empty($object)) {
                $classname = __NAMESPACE__ . '\\Controllers\\CpanelControl';
                $object = new $classname;
                $task = 'cpanel';
            }
            $object->$task();
        }
    }

    public function about() {
        $view = $this->getView('AboutHTML', 'html');
        $view->show();
    }

    public function setmaxpoints() {
        $view = $this->getView('MaxpointsHTML', 'html');
        $setpoints = Factory::getApplication()->input->get('newmaxpoints', 0, 'int');
        $this->viewdata['setpoints'] = $setpoints;
        $view->show();
    }

    public function deletependingapproval() {
        $cid = Factory::getApplication()->input->get('cid', 0, 'int');
        $detail = new PointsDetails($cid);
        $detail->delete();
        $this->redirect('index.php?option=com_userpoints&task=cpanel');
    }

    public function extractEmailsFromString($sChaine) {
        preg_match_all('/\s[^@\s]+@[^@\s]+/', $sChaine, $aEmails);
        return $aEmails[0];
    }

    public function changeuserlevel() {
        $app = Factory::getApplication();
        $model = $this->getModel('requests');
        $model->_acceptlevel();
        $this->redirect('index.php?option=com_userpoints&task=cpanel');
    }

    // show print coupon
    public function printcoupon() {
        $app = Factory::getApplication();
        $model = $this->getModel('couponcodes');
        $view = $this->getView('CouponcodesHTML', 'html');
        $SiteName = $app->getCfg('sitename');
        // load info coupon
        $row = $model->_print_coupon();
        $this->viewdata['coupon'] = $row;
        $this->viewdata['sitename'] = $SiteName;
        // Display
        $view->print_coupon();
    }

    public function applycustom() { // specific user
        $cid = Factory::getApplication()->input->get('cid', '', 'string');
        $name = Factory::getApplication()->input->get('name', '', 'string');

        if (!$cid) {
            return false;
        }

        $view = $this->getView('RulesHTML', 'html');

        $this->viewdata['cid'] = $cid;
        $this->viewdata['name'] = $name;

        $view->_displaycustompoints();
    }

    public function savecustompoints() { // specific user
        $app = Factory::getApplication();

        $referrerid = Factory::getApplication()->input->get('cid', '', 'username');
        $name = Factory::getApplication()->input->get('name', '', 'string');

        $points = Factory::getApplication()->input->get('points', 0, 'float');
        $reason = Factory::getApplication()->input->get('reason', '', 'SAFE_HTML ');

        if ($referrerid) {
            UserPoints::userpoints('sysplgup_custom', $referrerid, 0.0, '', $reason, $points);
            UserPoints::checkRankMedal($referrerid);
        }

        $this->redirect('index.php?option=com_userpoints&task=showdetails&cid=' . $referrerid . '&name=' . $name);
    }

    public function archiveActivities() {
        // show form for archive
        $view = $this->getView('ArchiveHTML', 'html');
        $view->show();
    }

    public function processarchive() {
        $app = Factory::getApplication();
        Session::checkToken() or jexit(Text::_('JINVALID_TOKEN'));
        // Purge old points expired before combine all activities
        $model = $this->getModel('users');
        $_purgeexpirepoints = $model->_purge_expires();
        // process to combine the set of all actions in one activity from a specified date
        $modelArchive = $this->getModel('archive');
        // delete and combine activities(s)
        $combined = $modelArchive->_archive();
        // Display
        $this->redirect('index.php?option=com_userpoints&task=cpanel&recalculate=start');
    }

    public function reportsystem() {
        $model = $this->getModel('reportsystem');
        // show form for report
        $view = $this->getView('ReportsystemHTML', 'html');
        // load report
        $_reportsystem = $model->_generate_report();
        $this->viewdata['reportsystem'] = $_reportsystem;
        $view->show();
    }

    // import export table activity

    public function importexportTableActivities() {

        $view = $this->getView('ExportHTML', 'html');
        $view->show();
    }

    private function getInputs($operation): array {
        $cid = Factory::getApplication()->input->get('cid', array(0), 'array');
        if (count($cid) < 1) {
            \JViewContent::displayError(sprintf(Text::_('AUP_SELECT_AN_ITEM'), Text::_($operation)));
            $nonzero = false;
        } else {
            $nonzero = true;
        }
        return [
            $nonzero,
            Factory::getApplication()->input->get('option', 'com_userpoints', 'cmd'),
            Factory::getApplication()->input->get('table', '', 'cmd'),
            $cid,
            Factory::getApplication()->input->get('redirect', 'cpanel', 'cmd')
        ];
    }

    private function toggle(string $operation, bool $turn_on, string $property) {
        list($nonzero, $option, $table, $cid, $redirect) = $this->getInputs($operation);
        if ($nonzero AND UserPoints::getUser()->authorise('core.edit.state', 'com_userpoints')) {
            ProblemBase::toggleProperties($cid, $turn_on, ('#__' . $table), $property);
        }
        $this->redirect("index.php?option=$option&task=$redirect");
    }

    private function toggleApprove (string $operation, bool $turn_on) {
        list($nonzero, $option, $table, $cid, $redirect) = $this->getInputs($operation);
        if ($nonzero AND UserPoints::getUser()->authorise('core.edit.state', 'com_userpoints')) {
            $detailset = PointsDetails::getMany($cid);
            foreach ($detailset as $details) {
                if ($details->enabled AND !$details->status) {
                    $details->status = $turn_on;
                    $details->approved = $turn_on;
                    $details->save();
                    PointsUser::withReferrerID($details->referreid)->updateUserAccount($details);
                }
            }
        }
        $this->redirect("index.php?option=$option&task=$redirect");
    }

    public function publish() {
        $this->toggle(Text::_('AUP_PUBLISH'), true, 'published');
    }

    public function unpublish() {
        $this->toggle(Text::_('AUP_UNPUBLISH'), false, 'published');
    }

    public function autoapprove() {
        $this->toggle(Text::_('AUP_AUTOAPPROVE'), true, 'autoapproved');
    }

    public function unautoapprove() {
        $this->toggle(Text::_('AUP_UNAUTOAPPROVE'), false, 'autoapproved');
    }

    public function registration() {
        $this->toggle(Text::_('AUP_REGISTRATION'), true, 'inscription');
    }

    public function unregistration() {
        $this->toggle(Text::_('AUP_UNREGISTRATION'), false, 'inscription');
    }

    public function approve() {
        $this->toggleApprove(Text::_('AUP_APPROVE'), true);
    }

    public function unapprove() {
        $this->toggleApprove(Text::_('AUP_UNAPPROVE'), false);
    }

    public function applybonus() {
        $cid = Factory::getApplication()->input->get('cid', array(0), 'array');
        if (count($cid) < 1) {
            \JViewContent::displayError(Text::_('Select an item to') . ' ' . Text::_('AUP_BONUS_APPLY'));
        } else {
            if (UserPoints::getUser()->authorise('core.edit.state', 'com_userpoints')) {
                foreach (PointsUser::getMany($cid) as $pointsuser) {
                    if ($pointsuser->referreid) {
                        UserPoints::userpoints('sysplgup_bonuspoints', $pointsuser->referreid, 0, '', Text::_('AUP_BONUSPOINTS'));
                        $pointsuser->checkTotalAfterRecalculate('sysplgup_bonuspoints');
                    }
                }
            }
            Factory::getApplication()->enqueueMessage(Text::_('AUP_RECALCULATION_MADE'));
            $this->redirect("index.php?option=com_userpoints&task=statistics");
        }
    }
}
