<?php
/**
 * @package     Joomla.Plugin
 * @subpackage  Content.joomla
 *
 * @copyright   Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

jimport('joomla.registry.registry');

// Autoload Composer
require JPATH_SITE . '/administrator/components/com_notifly/vendor/autoload.php';

// Register Event Helper
JLoader::register('NotiflyEventsHelper', JPATH_SITE . '/administrator/components/com_notifly/helpers/events.php');
// Register Message Helper
JLoader::register('NotiflyMessageHelper', JPATH_SITE . '/administrator/components/com_notifly/helpers/message.php');

/**
 * Example Content Plugin
 *
 * @since  1.6
 */
class PlgSystemNotifly extends JPlugin
{
	/*
	* construct and load group plugins
	*
	* @var object
	* @since 1.0
	*/
	protected $configs = null;
	// Application objet
	protected $app;
	// Document object
	protected $document;

	function __construct( &$subject, $params ) {

		parent::__construct( $subject, $params );
		JPluginHelper::importPlugin('notifly');

		$this->app 				= JFactory::getApplication();
		$this->document 		= JFactory::getDocument();

		// Load lang
		$lang = JFactory::getLanguage();
		$extension = 'com_notifly';
		$base_dir = JPATH_ADMINISTRATOR;
		$lang = JFactory::getLanguage();
		$language_tag = $lang->getTag();
		$reload = true;
		$lang->load($extension, $base_dir, $language_tag, $reload);
	}


	/**
	 * Add the canonical uri to the head.
	 *
	 * @return  void
	 *
	 * @since   3.5
	 */
	public function onAjaxNotifly()
	{
		// index.php?option=com_ajax&plugin=notifly&format=json&action=click
		if (!$this->app->isClient('site'))
		{
			return;
		}

		$action = $this->app->input->get('action', 'view');

		if($action == 'click'){
			$this->updateClick();
		}else{
			$this->updateView();		
		}
		return true;
	}

	public function updateClick(){
		$db = JFactory::getDbo();
		// get extensionid
		$query = $db->getQuery(true)
					->select('*')
					->from('#__notifly_logs')
					->where($db->quoteName('date') . ' = ' . $db->quote(JFactory::getDate()->format('Y-m-d') . ' 00:00:00'));
		$db->setQuery($query);
		
		$result = $db->loadObject();

		$log = new stdClass();
		$log->click = $result->click+1;
		$log->date = JFactory::getDate()->format('Y-m-d') . ' 00:00:00';
		$db->updateObject('#__notifly_logs', $log, 'date');

		return true;
	}

	public function updateView()
	{

		// check if has record for today
		$db = JFactory::getDbo();
		// get extensionid
		$query = $db->getQuery(true)
					->select('*')
					->from('#__notifly_logs')
					->where($db->quoteName('date') . ' = ' . $db->quote(JFactory::getDate()->format('Y-m-d') . ' 00:00:00'));
		$db->setQuery($query);
		
		$result = $db->loadObject();
		
		if(!isset($result->id) or !$result->id){
			// incert record
			$log = new stdClass();
			$log->date = JFactory::getDate()->format('Y-m-d') . ' 00:00:00';
			$log->view = 1;

			// Insert the object into the user profile table.
			$db->insertObject('#__notifly_logs', $log);
		}
		else
		{
			// update record
			$log = new stdClass();
			$log->view = $result->view+1;
			$log->date = JFactory::getDate()->format('Y-m-d') . ' 00:00:00';
			$db->updateObject('#__notifly_logs', $log, 'date');
		}

		return true;
	}

	/**
	 * Add the canonical uri to the head.
	 *
	 * @return  void
	 *
	 * @since   3.5
	 */
	public function onAfterDispatch()
	{
		
		if (!$this->app->isClient('site') || $this->document->getType() !== 'html')
		{
			return;
		}
		
		if ($this->app->input->get('tmpl') == 'component')
		{
			return;
		}

		$comInfo = JComponentHelper::getComponent('com_notifly');
		// hide for loged in users if enabled
		if($comInfo->params->get('hide_user') && JFactory::getUser()->id){
			return;
		}

		$options = [];
		$options['items'] = NotiflyEventsHelper::getList($comInfo->params->get('notifly_random', 0));
		$options['params'] = [
			'notifly_random' => $comInfo->params->get('notifly_random', 0),
			'notifly_loop' => $comInfo->params->get('notifly_loop', 0),
			'hide_mobile' => $comInfo->params->get('hide_mobile', 0),
			'hide_desktop' => $comInfo->params->get('hide_desktop', 0),
			'hide_user' => $comInfo->params->get('hide_user', 0),
			'allow_close' => $comInfo->params->get('allow_close', 0),
			'notify_delay_random' => $comInfo->params->get('notify_delay_random', 0), // later
			'notify_newtab' => $comInfo->params->get('notify_newtab', 0), // later
			'notify_box_link' => $comInfo->params->get('notify_box_link', 0), // later
			'notify_max' => $comInfo->params->get('notify_max', 0), // later
			'notify_max_item' => $comInfo->params->get('notify_max_item', 0), // later
			'notify_max_time' => $comInfo->params->get('notify_max_time', 0), // later
			'initial_delay' => $comInfo->params->get('initial_delay', 0), // later
			'max_bypage' => $comInfo->params->get('max_bypage', 20),
			'display_time' => $comInfo->params->get('display_time', 0),
			'delay_time' => $comInfo->params->get('delay_time', 0),
			'box_position' => $comInfo->params->get('box_position', 0), // later
			'mobile_position' => $comInfo->params->get('mobile_position', 0), // later
			'expire_cookie' => $comInfo->params->get('expire_cookie', 48),
			'wrapper_width' => $comInfo->params->get('wrapper_width', '300px'),
			'enable_hitcounter' => $comInfo->params->get('enable_hitcounter', 1),
			'show_branding' => $comInfo->params->get('show_branding', 1)
		];

		$options['baseurl'] = Juri::root('true');
		$this->document->addScriptOptions('notifly', $options);

		JHtml::_('jquery.framework');
		JHtml::_('script', 'com_notifly/showdown.min.js', array('version' => 'auto', 'relative' => true));
		JHtml::_('script', 'com_notifly/mustache.min.js', array('version' => 'auto', 'relative' => true));
		JHtml::_('script', 'com_notifly/cookies.min.js', array('version' => 'auto', 'relative' => true));
		JHtml::_('script', 'com_notifly/notifly-core.js', array('version' => 'auto', 'relative' => true));
		JHtml::_('stylesheet', 'com_notifly/notifly-core.min.css', array('version' => 'auto', 'relative' => true));

		return true;
	}

	/**
	 * Adds additional fields to the user editing form
	 *
	 * @param   JForm  $form  The form to be altered.
	 * @param   mixed  $data  The associated data for the form.
	 *
	 * @return  boolean
	 *
	 * @since   1.6
	 */
	public function onContentPrepareForm($form, $data)
	{
		if (!($form instanceof JForm))
		{
			return false;
		}		

		$this->handlePluginModal($form, $data);
		$this->handleConfigView($form, $data);

		return;

	}

	public function handlePluginModal($form, $data){
        // Check we are manipulating a valid form.
        $name = $form->getName();
        
        if (!in_array($name, array('com_plugins.plugin')))
        {
            return;
        }

        $input = JFactory::getApplication()->input;
        $layout = $input->get('layout');
        $source = $input->get('source');
        if(is_object($data)){
            $folder = $data->get('folder');
        }else{
            $folder = isset($data['folder']) ? $data['folder'] : '';
        }
        
        if($layout == 'modal' && isset($folder) && $folder == 'notifly')
        {
            JHtml::_('script', 'com_notifly/admin-notifly.js', array('version' => 'auto', 'relative' => true));
            JHtml::_('stylesheet', 'com_notifly/notifly-admin.css', array('version' => 'auto', 'relative' => true));
        }
    }

	public function handleConfigView($form, $data)
	{
		// Check we are manipulating a valid form.
		$name = $form->getName();
		if (!in_array($name, array('com_config.component')))
		{
			return;
		}

		$input = JFactory::getApplication()->input;
		$component = $input->get('component');
		$view = $input->get('view');

		if($component == 'com_notifly' && $view == 'component')
		{
			JFactory::getDocument()->addStyleDeclaration('#configTabs a[href*="#design"], #configTabs a[href*="#behavior"]{display: none;}');
		}
	}

	public function onAfterRender(){

    	if (!$this->app->isClient('site') || $this->document->getType() !== 'html')
		{
			return;
		}

		if ($this->app->input->get('tmpl') == 'component')
		{
			return;
		}
		
		// Init Mustache 
		$m = new Mustache_Engine;
		$events = NotiflyEventsHelper::getEvents();

	    $eventsHtmlStart = '<div id="notifly" class="notifly-position-bottom-left">';
	    $eventsHtmlEnd = '</div>';
	    $html = '';
	    $template = '
				<div class="notifly-inner">
					<img src="{{image_url}}" alt={{name}} />
					<div class="notifly-content">
						<div class="notifly-title">{{name}} from {{country}}</div>
					</div>
				</div>
	    ';

	    foreach ($events as $key => $event) {
	    	$message = NotiflyMessageHelper::parseMessage($event->message, $event);
	    	$html .= $message;
	    	//$tmptemplate = $this->parseTemplate($template, $message, $event);
	    }
	    
    	JResponse::appendBody($eventsHtmlStart. $html . $eventsHtmlEnd);
  	}

  	public function onExtensionAfterSave($option, $data) {

        if ( ($option == 'com_config.component') && ( $data->element == 'com_notifly' ) ) {

            $params = new JRegistry;
            $params->loadString($data->params);
            
            $username   = $params->get('username');
            $key 		= $params->get('key');

            if(!empty($username) and !empty($key) )
            {

                $extra_query = 'username=' . urlencode($username);
                $extra_query .='&amp;key=' . urlencode($key);

                $db = JFactory::getDbo();
                
                $fields = array(
                    $db->quoteName('extra_query') . '=' . $db->quote($extra_query),
                    $db->quoteName('last_check_timestamp') . '=0'
                );

                // Update site
                $query = $db->getQuery(true)
                    ->update($db->quoteName('#__update_sites'))
                    ->set($fields)
                    ->where($db->quoteName('name').'='.$db->quote('Notifly Update Site'));
                $db->setQuery($query);
                $db->execute();
            }
        }
    }
	
}
