<?php
/**
 * @package DJ-SectionsAnywhere
 * @copyright Copyright (C) 2017  DJ-Extensions.com LTD, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 *
 * DJContentFilters is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * DJContentFilters is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with DJContentFilters. If not, see <http://www.gnu.org/licenses/>.
 *
 */

defined('_JEXEC') or die;

/**
 * Form Field class for the Joomla Platform.
 * Supports a one line text field.
 *
 * @link   http://www.w3.org/TR/html-markup/input.text.html#input.text
 * @since  11.1
 */
class JFormFieldDJUpdater extends JFormField
{
    /**
     * The form field type.
     *
     * @var    string
     * @since  11.1
     */
    protected $type = 'DJUpdater';

    /**
     * Method to get the field input markup.
     *
     * @return  string  The field input markup.
     *
     * @since   11.1
     */
    protected function getInput()
    {
        $app	= JFactory::getApplication();
        $doc	= JFactory::getDocument();

        //$name 	= $this->form->getData()->get('name');
        $name = (string)$this->element['extension'];
        $extension_name = (string)$this->element['extension_name'];
        $path 	= '/plugins/system/djc2yootheme';

        if($name) {
            $lang = JFactory::getLanguage();
            $lang->load($name, JPATH_ROOT, 'en-GB', true, false);
            $lang->load($name, JPATH_ROOT . $path, 'en-GB', true, false);
            $lang->load($name, JPATH_ROOT, null, true, false);
            $lang->load($name, JPATH_ROOT . $path, null, true, false);

            $doc->addStylesheet(JURI::root(true).$path.'/assets/forms.css');
        }

        $task = $app->input->get('djtask');
        if($task) {
            ob_clean();
            echo 'DJUPDATERRESPONSE'.$this->$task($name);
            $app->close();
        }

        self::setUpdateServer($extension_name);

        $html = self::getSubscription($name, $extension_name);

        return $html;
    }

    public static function getSubscription($ext, $ext_name){
        $app	= JFactory::getApplication();

        $db = JFactory::getDBO();
        $query = "SELECT manifest_cache FROM #__extensions WHERE name='".$ext_name."'";

        $db->setQuery($query);
        $mc = json_decode($db->loadResult());
        $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 = '';
        }

        $jversion = new JVersion;
        if (version_compare($jversion->getShortVersion(), '4.0.0', 'ge') && $license == '') {
            Joomla\CMS\HTML\HTMLHelper::_('jquery.framework');

            $db = JFactory::getDbo();
            $db->setQuery('SELECT extra_query FROM #__update_sites WHERE name=\'DJ-Catalog2 YOOTheme Integration\' AND type=\'extension\'');
            $dlid = $db->loadResult();
            if (trim($dlid) != '' && preg_match('#dlid=([a-z0-9]+)+($|&)#i', $dlid, $matches)) {
                $license = $matches[1];
            }
        }

        $html  = '<h4>'.JText::_('PLG_DJSUGGESTER_VER_DESC').'  '.$version.'</h4>';

        $html .= '<p>'.JText::_('DJUPDATER_LICENSE_INFO').'</p>';

        $html .= '<input id="license" type="text" name="license" class="input input-large" value="'.htmlspecialchars($license).'" placeholder="'. JText::_('DJUPDATER_PASTE_KEY').'" /> ';
        $html .= '<button id="register" class="btn btn-info" href="#">'.JText::_('DJUPDATER_SAVE_KEY').'</button> ';

        $js = "
				jQuery(document).ready(function(){
			
					var button = jQuery('#register');
					var loader = jQuery('<span class=\"icon-refresh djspin\" />');
			
					button.click(function(e){
						button.prop('disabled', true);
						button.prepend(loader);
						e.preventDefault();
			
						jQuery.ajax({
							data: {
								license: jQuery('#license').val(),
								djtask: 'save'
							}
						}).done(function(data) {
							var message = data.substr(data.lastIndexOf('DJUPDATERRESPONSE')+17);
							button.closest('.alert').before(jQuery(message));
							setTimeout(function(){ location.reload(); }, 1000);
						})
						.fail(function() {
							alert( 'connection error' );
							button.prop('disabled', false);
							loader.detach();
						});
					});
			
				});
			";

        JFactory::getDocument()->addScriptDeclaration($js);

        return self::renderAlert($html, 'info');
    }

    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;

    }

    private function save($ext){
        $app	= JFactory::getApplication();
        $config = JFactory::getConfig();
        $db = JFactory::getDbo();

        $license = JFactory::getApplication()->input->getString('license');
        $license = preg_replace("/[^a-zA-Z0-9:]+/", '', $license);

        $secret_file = JFile::makeSafe('license_'.$config->get('secret').'.txt');
        $license_file = JPath::clean(dirname(__FILE__).'/../'.$secret_file);

        if ($license == ''){
            $query = "UPDATE #__update_sites SET extra_query='' WHERE name='DJ-Catalog2 YOOTheme Integration' AND type='extension' ";
            $db->setQuery($query);
            $db->query();

            JFile::delete($license_file);
        } else{
            $query = "SELECT manifest_cache FROM #__extensions WHERE name='plg_system_djc2yootheme' ";
            $db->setQuery($query);
            $mc = json_decode($db->loadResult());
            $version = $mc->version;

            $extra_query = 'dlid='.$license.'&site='.urlencode(JURI::root());
            $query = "UPDATE #__update_sites SET extra_query='".addslashes($extra_query)."' WHERE name='DJ-Catalog2 YOOTheme Integration' AND type='extension' ";
            $db->setQuery($query);
            $db->execute();

            JFile::write($license_file, $license);
        }

        $msg = ($license == '') ? 'Removed' : 'OK';

        return self::renderAlert($msg, 'success');
    }

    public static function setUpdateServer($name = 'DJ-Catalog2 YOOTheme Integration') {

        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.'/plugins/content/dj'.strtolower($name).'/'.$secret_file);

        if(JFile::exists($license_file)){
            $license = JFile::read($license_file);
        }else{
            $license = '';
        }

        $query = "SELECT extension_id, manifest_cache FROM #__extensions WHERE name='plg_system_djc2yootheme'";
        $db->setQuery($query);
        $pkg = $db->loadObject();

        if($pkg) {
            $mc = json_decode($pkg->manifest_cache);
            $version = $mc->version;

            $extra_query = 'license='.$license.'&v='.$version.'&site='.JURI::root();

            $db->setQuery("SELECT COUNT(*) FROM #__update_sites WHERE name='".$name."' AND type='extension'");
            if ($db->loadResult() > 0) {
                $db->setQuery("UPDATE #__update_sites SET
						location='https://dj-extensions.com/api/getUpdateInfo?extension=djc2yootheme.xml',
	                    extra_query='".addslashes($extra_query)."'
	                    WHERE name='".$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/api/getUpdateInfo?extension=djc2yootheme.xml', 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();
        }
    }
}
