<?php
/**
 * @package DJ-Catalog2
 * @copyright Copyright (C) 2017 DJ-Extensions.com, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: https://dj-extensions.com
 * @author email contact@dj-extensions.com
 */

defined('_JEXEC') or die('Restricted access');

class DJLicense{
	
	public static function getSubscription($name){
		
		if (!in_array('curl', get_loaded_extensions())) {
			return self::renderAlert(JText::_('COM_DJCATALOG2_DJLIC_CURL_NOT_INSTALLED'), 'error');
		}
		
		$app	= JFactory::getApplication();
		
		$ext = 'pkg_dj-'.strtolower($name);
		
		self::setUpdateServer($name);
		
		$db = JFactory::getDBO();
		$query = "SELECT manifest_cache FROM #__extensions WHERE element ='".$ext."'";
		$db->setQuery($query);
		$result = $db->loadResult();
		
		// we change ext name to component, because package don't have assigned license
		$ext = 'com_dj'.strtolower($name);
		
		if(!$result) { // in case package wasn't installed check the version of the component
			$query = "SELECT manifest_cache FROM #__extensions WHERE element ='".$ext."'";
			$db->setQuery($query);
			$result = $db->loadResult();
		}
		
		$mc = json_decode($result);
		$version = $mc->version;
		$config = JFactory::getConfig();
		
		$secret_file = JFile::makeSafe('license_'.$config->get('secret').'.txt');
		$license_file = JPath::clean(dirname(__FILE__).'/../'.$secret_file);
		
		if(JFile::exists($license_file)){
			$license = file_get_contents($license_file);
		} else {
			$license = '';
		}
		
		
		$icon_class = 'djlic_invalid';
		$u = JUri::getInstance();
		
		
		$update = '<div class="djlic_box">';
		$update .= '<div class="djlic_logo_wrapper">';
		$update .= '<div class="djlic_logo"><img style="width: 70px;" alt="DJ-' . $name . '" src="' . JURI::base() . 'components/com_djcatalog2/assets/images/dj-catalog2.svg" /></div>';
		$update .= '<div class="djlic_title">DJ-' . $name . '</div>';
		$update .= '</div>';
		$update .= '<div class="djlic_version">';
		$update .= '<span class="' . $icon_class . '"></span>';
		$update .= '<div class="djlic_info">';
		$update .= '<a href="https://dj-extensions.com/support/changelogs/dj-catalog2" target="_blank">' . JText::_('COM_DJCATALOG2_DJLIC_CHANGELOG') . '</a>';
		$update .= '</div>';
		$update .= '<div class="djlic_info">';
		
		$update .= '<p>' . JText::_('COM_DJCATALOG2_DJLIC_ENTER_LICENSE') . ' <a href="//' . $u->getHost() . '" target="_blank">' . $u->getHost() . '</a></p>';
		$update .= '<input id="license" type="text" name="license" class="input input-large" placeholder="' . JText::_('DJUPDATER_PASTE_KEY') . '" value="' . trim($license) . '" /> ';
		$update .= '<button id="register" class="btn btn-djex" href="#">' . JText::_('DJUPDATER_REGISTER_KEY') . '</button> ';
		$update .= '<a class="btn btn-warning" target="_blank" href="https://dj-extensions.com/dj-catalog2">' . JText::_('DJUPDATER_BUY_LICENSE') . '</a><br /><br />';
		
		$update .= '<span class="djlic_iline3">' . JText::_('COM_DJCATALOG2_DJLIC_INVALID_INFO') . '</span>';
		$update .= '</div>';
		$update .= '</div>';
		
		
		$js = "
			jQuery(document).ready(function(){
			
				var button = jQuery('#register');
				var loader = jQuery('<i class=\"icon-refresh djspin\" />');
				var input = jQuery('#license');
			
				if (input.val() != '') {
					input.addClass('readonly').attr('readonly', 'readonly');
				}
				input.click(function(){
					input.removeAttr('disabled')
						.removeAttr('readonly')
						.removeClass('readonly');
				});
			
				button.click(function(e){
					button.prop('disabled', true);
					button.prepend(loader);
					e.preventDefault();
			
					jQuery.ajax({
						data: {
							option: '" . $ext . "',
							task: 'license.save',
							extension: '" . $name . "',
							license: jQuery('#license').val()
						}
					}).done(function(data) {
						button.closest('.djlic_invalid, .djlic_expired').before(jQuery(data));
						setTimeout(function(){ location.reload(); }, 1000);
					})
					.fail(function() {
						alert( 'connection error' );
						button.prop('disabled', false);
						loader.detach();
					});
				});
								
			});
		";
		
		JFactory::getDocument()->addScriptDeclaration($js);
		
		return $update;

	}
	
	public static function renderAlert($msg, $type = '', $title = '') {
		if(!in_array($type, array('success', 'error', 'info', ''))) $type = 'info';
		
		$html = 	'<div class="alert alert-'.$type.'">'
			.		(!empty($title) ? '<h3>'.$title.'</h3>' : '')
			.		'<div class="alert-body">'.$msg.'</div>'
				.	'</div>';
				
				return $html;
	}
	
	public static function setUpdateServer($name) {
		
		if(empty($name)) return;
		// update the update server information for package
		$db = JFactory::getDbo();
		$config = JFactory::getConfig();
		$secret_file = JFile::makeSafe('license_'.$config->get('secret').'.txt');
		$license_file = JPath::clean(JPATH_ROOT.'/administrator/components/com_dj'.strtolower($name).'/'.$secret_file);
		
		if(JFile::exists($license_file)){
			$license = file_get_contents($license_file);
		}else{
			$license = '';
		}
		
		$query = "SELECT extension_id, manifest_cache FROM #__extensions WHERE element='pkg_dj-".strtolower($name)."' AND type='package' ";
		$db->setQuery($query);
		$pkg = $db->loadObject();
		
		if($pkg) {
			$mc = json_decode($pkg->manifest_cache);
			$version = $mc->version;
			
			$extra_query = 'dlid='.$license.'&v='.$version.'&site='.JURI::root();
			
			$db->setQuery("SELECT COUNT(*) FROM #__update_sites WHERE name='DJ-".$name."' AND type='extension'");
			if ($db->loadResult() > 0) {
				$db->setQuery("UPDATE #__update_sites SET
	                    extra_query='".addslashes($extra_query)."'
	                    WHERE name='DJ-".$name."' AND type='extension'");
			} else {
				$db->setQuery("INSERT INTO #__update_sites (`name`, `type`, `location`, `enabled`, `extra_query`) VALUES
	                    ('DJ-".$name."', 'extension', 'https://dj-extensions.com/index.php?option=com_ars&view=update&task=stream&format=xml&id=55', 1, '".addslashes($extra_query)."')");
				$db->execute();
				
				$update_site_id = $db->insertid();
				$db->setQuery("INSERT INTO #__update_sites_extensions (`update_site_id`, `extension_id`)
						VALUES (".$update_site_id.", ".$pkg->extension_id.")");
			}
			$db->execute();
		}
	}
}