<?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\Plugin\CMSPlugin;
use Joomla\CMS\Component\ComponentHelper;
use BlackSheepResearch\Component\UserPoints\Site\Problems\SQL;

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

    protected $plugin_type = 'extension';
    static protected $Update_Key = '';

    public function onExtensionBeforeSave($context, $table, $isNew) {
        // Check that we're modifying the correct component.
        if ($context !== 'com_config.component' OR $table->element !== 'com_userpoints') {
            return;
        }

        $params = ComponentHelper::getParams('com_userpoints');
        self::$Update_Key = $params['Update_Key'];
    }

    public function onExtensionAfterSave($context, $table, $isNew) {
        // Check that we're modifying the correct component.
        if ($context !== 'com_config.component' OR $table->element !== 'com_userpoints') {
            return;
        }

        $db = SQL::getInstance();
        $db->setQuery("SELECT params FROM `#__extensions` WHERE type = 'component' AND element = 'com_userpoints'");
        $new_key = \json_decode($db->loadResult())->Update_Key;

        if (self::$Update_Key != $new_key) {
            $db->setQuery("UPDATE #__update_sites SET extra_query = 'hash=$new_key' WHERE name LIKE '%UserPoints%'");
            $db->execute();
        }
    }

}
