<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_notifly
 *
 * @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;

/**
 * Notifly component helper.
 *
 * @since  1.6
 */
class NotiflyMessageHelper
{
	/**
	 * Returns valid contexts
 	 * @param   time of action
	 *
	 * @return  array

	 *
	 * @since   1.0.0
	 */
	public static function parseMessage($msg, $event)
	{
		$title = isset($event->title) && !empty($event->title) ? $event->title : JText::_('COM_NOTIFLY_MESSAGE_TITLE');
		$url = isset($event->url) && !empty($event->url) ? JRoute::_($event->url) : Juri::root();

		$m = new Mustache_Engine;
		$data = array(
			'name' => isset($event->name) && !empty($event->name) ? $event->name : JText::_('COM_NOTIFLY_MESSAGE_SOMEONE'),
			'city' => isset($event->city) && !empty($event->city) ? $event->city : JText::_('COM_NOTIFLY_MESSAGE_CITY_UNKNOWN'),
			'province' => isset($event->province) && !empty($event->province) ? $event->province : JText::_('COM_NOTIFLY_MESSAGE_PROVINCE_UNKNOWN'),
			'country' => isset($event->country) && !empty($event->country) ? $event->country : JText::_('COM_NOTIFLY_MESSAGE_COUNTRY_UNKNOWN'),
			'title' => $title,
			'url' => $url,
			'title_with_link' => '['.$title.']('.$url.')', //'<a href="'.$url.'">'.$title.'</a>',
			'time_ago' => isset($event->created) && !empty($event->created) ? NotiflyMessageHelper::getFormatedTime($event->created) : JText::_('COM_NOTIFLY_MESSAGE_CREATED')
		);	

		return $m->render($msg, $data);
	}

	/**
	 * Returns valid contexts
 	 * @param   ip
	 *
	 * @return  array

	 *
	 * @since   1.0.0
	 */
	public static function getLocation($ip)
	{
		// http://api.db-ip.com/v2/e9a901d2b1df53e77ab70dc79a74d11558d3bdb9/61.6.1.39
		// http://freegeoip.net/json/?q=119.148.0.0
		
		try {
			// Set up custom headers for a single request.
			$headers = array('Accept' => 'application/json');
			$http = JHttpFactory::getHttp();
			
			// In this case, the Accept header in $headers will override the options header.
			$response = $http->get('http://freegeoip.net/json/' . $ip, $headers);
			if($response->code == '200'){
				$data = json_decode($response->body, true);
				return $data;
			}
		} catch (Exception $e) {
			// Add a message to the message queue
			JFactory::getApplication()->enqueueMessage(JText::_('COM_NOTIFLY_ERROR_LOCATION'), 'error');
		}
	}


	/**
	 * Get either a Gravatar URL or complete image tag for a specified email address.
	 *
	 * @param string $email The email address
	 * @param string $s Size in pixels, defaults to 80px [ 1 - 2048 ]
	 * @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
	 * @param string $r Maximum rating (inclusive) [ g | pg | r | x ]
	 * @param boole $img True to return a complete IMG tag False for just the URL
	 * @param array $atts Optional, additional key/value attributes to include in the IMG tag
	 * @return String containing either just a URL or a complete image tag
	 * @source https://gravatar.com/site/implement/images/php/
	 */
	public static function getGravater( $email, $s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array() ) {
	    $url = 'https://www.gravatar.com/avatar/';
	    $url .= md5( strtolower( trim( $email ) ) );
	    $url .= "?s=$s&d=$d&r=$r";
	    if ( $img ) {
	        $url = '<img src="' . $url . '"';
	        foreach ( $atts as $key => $val )
	            $url .= ' ' . $key . '="' . $val . '"';
	        $url .= ' />';
	    }
	    return $url;
	}

	public static function getRealIpAddr()
	{
	    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
	    {
	      $ip=$_SERVER['HTTP_CLIENT_IP'];
	    }
	    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
	    {
	      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
	    }
	    else
	    {
	      $ip=$_SERVER['REMOTE_ADDR'];
	    }
	    return $ip;
	}
	
	//https://stackoverflow.com/questions/1416697/converting-timestamp-to-time-ago-in-php-e-g-1-day-ago-2-days-ago
	public static function getFormatedTime($datetime, $full = false) 
	{
		$zone = JFactory::getConfig()->get('offset');
		$now = JFactory::getDate( 'now' , $zone );
	    $ago = JFactory::getDate( $datetime , $zone );
	    $diff = $now->diff($ago);

	    $diff->w = floor($diff->d / 7);
	    $diff->d -= $diff->w * 7;

	    $string = array(
	        'y' => 'year',
	        'm' => 'month',
	        'w' => 'week',
	        'd' => 'day',
	        'h' => 'hour',
	        'i' => 'minute',
	        's' => 'second',
	    );
	    foreach ($string as $k => &$v) {
	        if ($diff->$k) {
	            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
	        } else {
	            unset($string[$k]);
	        }
	    }

	    if (!$full) $string = array_slice($string, 0, 1);
	    return $string ? implode(', ', $string) . ' '. JText::_('COM_NOTIFLY_MESSAGE_AGO') : JText::_('COM_NOTIFLY_MESSAGE_NOW');
	}



}
