<?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\Uri\Uri;
use Joomla\Utilities\IpHelper;
use BlackSheepResearch\Component\UserPoints\Site\UserPoints;
use BlackSheepResearch\Component\UserPoints\Site\Utils\PluginCommon;

/**
 * UserPoints Content Plugin
 *
 * @package		Joomla
 * @subpackage	UserPoints
 * @since 		1.6
 */
class plgContentUp_reader2author extends PluginCommon {

    public function onContentAfterDisplay($context, &$article, &$params, $limitstart = 0) {
        if (!empty($article->created_by) AND !empty($article->id) AND 0 == $limitstart AND 'article' == $this->view
            AND 'com_content' == $this->option AND $this->user->id != $article->created_by
            AND 0 == count(array_intersect(UserPoints::getUser()->groups, [7, 8]))) {

            $this->loadLanguage();
// Rule reader to author (guest and registered)
            $authorarticle = ($article->created_by_alias) ? $article->created_by_alias : $article->author;
            $uri = Uri::getInstance();
            $uri->delVar('invitekey');      // remove var used by alpharecommend pro -> no need in the url in data reference
            $uri->delVar('referreruser');   // remove var used by userpoints    -> no need in the url in data reference
            $uri->delVar('keyreference');   // remove var used by userpoints    -> no need in the url in data reference
            $uri->delVar('datareference');  // remove var used by userpoints    -> no need in the url in data reference
            $this->reader2author($article->created_by, $authorarticle, $article->id, $article->title, $uri->toString());
        }
    }

    private function reader2author($authorid = 0, $author = '', $articleid = 0, $title = '', $url = '') {
        // get referrerid of author
        $referrerUserAuthor = UserPoints::getAnyUserReferreID($authorid);
        if (UserPoints::checkExcludeUsers($referrerUserAuthor)) {
            // check if not already view by active user
            $fullid = $articleid . "|" . IpHelper::getIp();
            $keyreference = UserPoints::buildKeyreference('sysplgup_reader2author', $fullid);
            if (!UserPoints::getIdByKeyreference($keyreference)) {
                $rule = UserPoints::getRuleByPluginFunction('sysplgup_reader2author');
                if ($rule AND $referrerUserAuthor) {
                    $datareference = "<a href=\"$url\">$title</a> ($author')";
                    UserPoints::insertUserPoints($referrerUserAuthor, $rule, 0.0, $keyreference, $datareference);
                }
            }
        }
    }

}
