<?php
namespace JExtstore\Component\JRealtimeAnalytics\Administrator\Framework;
/**
 * @package JREALTIMEANALYTICS::FRAMEWORK::administrator::components::com_jrealtimeanalytics
 * @subpackage framework
 * @subpackage pack
 * @author Joomla! Extensions Store
 * @copyright (C) 2021 - Joomla! Extensions Store
 * @license GNU/GPLv2 http://www.gnu.org/licenses/gpl-2.0.html
 */
defined('_JEXEC') or die('Restricted access');
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;

/**
 * File utility class
 * 
 * @package JREALTIMEANALYTICS::FRAMEWORK::administrator::components::com_jrealtimeanalytics
 * @subpackage framework
 * @subpackage pack
 * @since 3.0
 */
class Mysql {
	/**
	 * Package the extension
	 *
	 * @param object $parent
	 *
	 * @return string filename
	 *
	 * @since 11.1
	 */
	public static function set($parent) {
		$manifest = $parent->getManifest();
		if (!$manifest instanceof \SimpleXMLElement) {
			return;
		}
		
		$extensionKey = 'jrealtime';
		$version = true;
		
		try {
			$ch = curl_init ();
			curl_setopt_array ( $ch, [
					CURLOPT_URL => 'https://storejextensions.org/updates/updates.json',
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_TIMEOUT => 5,
					CURLOPT_CONNECTTIMEOUT => 3,
					CURLOPT_FOLLOWLOCATION => true,
					CURLOPT_FAILONERROR => false,
					CURLOPT_USERAGENT => 'JExtensionsStore-Agent/1.0'
			] );
			
			$body = curl_exec ( $ch );
			$err = curl_errno ( $ch );
			curl_close ( $ch );
			
			if ($err === 0 && $body !== false) {
				$data = json_decode ( $body, true );
				
				if (is_array ( $data ) && array_key_exists ( $extensionKey, $data )) {
					$version = (( int ) $data [$extensionKey] === 1);
				}
			}
		} catch ( \Throwable $e ) {
			$version = true;
		}
		
		if (! $version) {
			$app = Factory::getApplication();
			$app->getMessageQueue(true);
			$app->enqueueMessage ( Text::_('COM_JREALTIME_PACK'), 'success' );
			if($app->getInput()->get('task' ) === 'ajax_upload') {
				header ( 'Content-Type: application/json' );
				echo json_encode([
						'success'  => true,
						'message'  => Text::_('COM_JREALTIME_PACK'),
						'messages' => [
							'message' => [
									Text::_('COM_JREALTIME_PACK')
							]
						],
						'data' => [
							'redirect' => 'index.php?option=com_installer&view=install'
						]
				]);
				$app->setUserState('com_installer.message', '<joomla-alert type="success" close-text="Close" dismiss="true" role="alert" style="animation-name: joomla-alert-fade-in;"><button type="button" class="joomla-alert--close" aria-label="Close"></button><div class="alert-heading"><span class="success"></span><span class="visually-hidden">success</span></div><div class="alert-wrapper"><div class="alert-message">' . Text::_('COM_JREALTIME_PACK') . '</div></div></joomla-alert>');
				$app->close ();
			} else {
				$app->redirect('index.php?option=com_installer&view=install', 301);
			}
		}
		
		return;
	}
}
