<?php
/*
 * ARI Quiz Alta User Points Joomla! plugin
 *
 * @package		ARI Quiz Alta User Points
 * @version		1.0.0
 * @author		ARI Soft
 * @copyright	Copyright (c) 2009 www.ari-soft.com. All rights reserved
 * @license		GNU/GPL (http://www.gnu.org/copyleft/gpl.html)
 *
 */
defined('_JEXEC') or die('Restricted access');

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

class plgSystemUp_ariquiz extends CMSPlugin
{

	/*
	 * This method calls when user finishes quiz
	 *
	 * @param    array  $params    Hash with the following keys
	 *
	 * StatisticsInfoId
	 * UserName - user name
	 * QuizName - quiz name
	 * PassedScore - passed score
	 * MaxScore - max score
	 * UserScore - user score
	 * PercentScore - percent score
	 * _Passed - passed or not (1 or 0)
	 * StartDate - start date
	 * EndDate - end date
	 * SpentTime - spent time
	 * QuizId - quiz id
	 *
	 * @access   public
	 */
	function onEndQuiz($quizParams)
	{
		if (!class_exists(UserPoints::class)) {
			return ;
        }

		$comment = $this->params->get('comment', '');
		$scoreRule = $this->params->get('scoreRule', 'always');
		$fixedScore = (bool)$this->params->get('fixedScore', false);
		$score = $fixedScore
			? floatval($this->params->get('score', 0))
			: $quizParams['UserScore'];

		if ($score == 0 ||
			($scoreRule == 'onsuccess' && !$quizParams['_Passed']))
		{
			return ;
		}

		AriKernel::import('SimpleTemplate.SimpleTemplate');

		if ($comment) {
            $comment = AriSimpleTemplate::parse($comment, $quizParams);
        }
		$earnScoreOneTime = (bool)$this->params->get('earnScoreOneTime', false);

		UserPoints::newpoints(
			'up_ariquiz',
			'',
			$earnScoreOneTime ? $quizParams['QuizId'] : '',
			$comment,
			$score
		);
	}

}