<?php

/*
 * @component UserPoints
 * @copyright Copyright (C) 2015-2022 Bernard Gilly - Adrien Roussel - Martin Brampton
 * @license : GNU/GPL
 * @Website : https://remository.com
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

use Joomla\CMS\Factory;
use Joomla\CMS\Plugin\CMSPlugin;
use BlackSheepResearch\Component\UserPoints\Site\UserPoints;

/**
 * UserPoints Content Plugin
 *
 * @package		Joomla
 * @subpackage	UserPoints
 * @since 		1.6
 */
class plgContentUp_content extends CMSPlugin {

    public function onContentPrepare($context, &$article, &$params, $limitstart) {
        $app = Factory::getApplication();

        $user = UserPoints::getUser();

        if (isset($article->id)) {
            $articleid = $article->id;
        } else {
            $articleid = null;
        }

        $option = $app->input->get('option', '');
        $view = $app->input->get('view', '');
        $print = $app->input->get('print', '');

        if (0 == count(array_intersect(UserPoints::getUser()->groups, [7, 8]))) {
            return;
        }
        if (!$user->id || !$articleid) {
            $article->text = preg_replace(" |{AUP::SHOWPOINTS}| ", "", $article->text);
            return;
        }

        $lang = Factory::getLanguage();
        $lang->load('com_userpoints', JPATH_SITE);

        // *******************************************
        // * show current points of the current user *
        // *******************************************
        if (preg_match('#{AUP::SHOWPOINTS}#Uis', $article->text, $m)) {
            $show = $m[0];
            $referrerid = UserPoints::getReferreid();
            if ($show AND $referrerid) {
                $currentpoints = UserPoints::getFPoints(UserPoints::getCurrentTotalPoints($referrerid));
                if (!$article->title || $article->title == NULL) {
                    $article->title = $option;
                }
                $article->text = preg_replace(" |{AUP::SHOWPOINTS}| ", $currentpoints, $article->text);
            } else {
                $article->text = preg_replace(" |{AUP::SHOWPOINTS}| ", "", $article->text);
            }
        }
    }

}
