<?php
/**
 * @package		YouBricks Engine
 * @author		Youjoomla LLC
 * @website     Youjoomla.com 
 * @copyright	Copyright (c) since 2007 Youjoomla LLC.
 * @license   PHP files are GNU/GPL V2. CSS / JS / IMAGES are Copyrighted Commercial
 */
	// Set flag that this is a parent file
	if(!defined('_JEXEC')) define( '_JEXEC', 1 );
	header("Content-type: text/plain; charset=UTF-8");
	$yj_mod_name 				= basename(dirname(dirname(dirname(__FILE__))));
	define( 'DS', DIRECTORY_SEPARATOR );
	define('JPATH_BASE',str_replace("modules".DIRECTORY_SEPARATOR.$yj_mod_name.DIRECTORY_SEPARATOR."src".DIRECTORY_SEPARATOR."ajax","",dirname(__FILE__)));
	require_once ( JPATH_BASE .DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR.'defines.php' );
	require_once ( JPATH_BASE .DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR.'framework.php' );	
		
	$yj_mod_name 				= basename(dirname(dirname(dirname(__FILE__))));
	$_SERVER['PHP_SELF']	= str_replace("modules/".$yj_mod_name."/src/ajax/","",$_SERVER['PHP_SELF']);
	$_SERVER['SCRIPT_NAME'] = str_replace("modules/".$yj_mod_name."/src/ajax/","",$_SERVER['SCRIPT_NAME']);

	$app 	= &JFactory::getApplication('site');
	jimport('joomla.application.module.helper');
	jimport('joomla.registry.registry');
	jimport('joomla.plugin.helper');
	jimport( 'joomla.session.session' );
	$app->initialise();
	$session		 	=& JFactory::getSession();	
	
	$cid 	= JRequest::getInt('cid'); 
	$source	= JRequest::getInt('source');
	$moduleid	= JRequest::getInt('modid');
	if(!(JRequest::getVar('cid') && JRequest::getVar('source') && JRequest::getVar('modid'))){
    	$app->close();	
		exit;
		
	}	 
	//load the language files also
	$language 	= JFactory::getLanguage();
	$language->load($yj_mod_name, JPATH_BASE, null, false, false);		

	//get the module params
	$db = JFactory::getDbo();

	$user = JFactory::getUser();
	$groups = implode(',', $user->getAuthorisedViewLevels());

	$lang = JFactory::getLanguage()->getTag();
	$clientId = (int) $app->getClientId();
		
	$query = $db->getQuery(true);
	$query->select('m.id, m.title, m.module, m.position, m.content, m.showtitle, m.params, mm.menuid');
	$query->from('#__modules AS m');
	$query->join('LEFT', '#__modules_menu AS mm ON mm.moduleid = m.id');
	$query->where('m.published = 1 AND m.id='.$moduleid.'');

	$query->join('LEFT', '#__extensions AS e ON e.element = m.module AND e.client_id = m.client_id');
	$query->where('e.enabled = 1');

	$date = JFactory::getDate();
	$now = $date->toSql();
	$nullDate = $db->getNullDate();
	$query->where('(m.publish_up = ' . $db->Quote($nullDate) . ' OR m.publish_up <= ' . $db->Quote($now) . ')');
	$query->where('(m.publish_down = ' . $db->Quote($nullDate) . ' OR m.publish_down >= ' . $db->Quote($now) . ')');

	//$query->where('m.access IN (' . $groups . ')');
	$query->where('m.client_id = ' . $clientId);
	//$query->where('(mm.menuid = ' . (int) $Itemid . ' OR mm.menuid <= 0)');
	$query->where('m.module = "'.$yj_mod_name.'"');
	
	// Filter by language
	if ($app->isSite() && $app->getLanguageFilter())
	{
		$query->where('m.language IN (' . $db->Quote($lang) . ',' . $db->Quote('*') . ')');
	}

	$query->order('m.position, m.ordering');
	//echo $query->__toString(); exit;
	
	// Set the query
	$db->setQuery($query);
	$module = $db->loadObjectList();

	// Make sure there aren't any errors
	if ($db->getErrorNum()) {
		echo $db->getErrorMsg();
		exit;
	}	

	$params 			= new JRegistry();
	$params->loadString($module[0]->params, 'JSON');

	//add the k2 CB plugin in case module loads k2 items
	if($params->get('item_source') == 2){
		jimport('joomla.filesystem.folder');
		jimport('joomla.filesystem.file');		
		// Community Builder integration
		$componentParams = JComponentHelper::getParams('com_k2');
		if ($componentParams->get('cbIntegration') && JFile::exists(JPATH_ADMINISTRATOR.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_comprofiler'.DIRECTORY_SEPARATOR.'plugin.foundation.php'))
		{
			
			if(!defined('_JEXEC')){
				define('K2_CB', true);
			}
			global $_CB_framework;
			require_once (JPATH_ADMINISTRATOR.DIRECTORY_SEPARATOR.'components'.DIRECTORY_SEPARATOR.'com_comprofiler'.DIRECTORY_SEPARATOR.'plugin.foundation.php');
			cbimport('cb.html');
			cbimport('language.front');
		}
		else
		{
			if(!defined('_JEXEC')){
				define('K2_CB', false);
			}
		}	
	}

	require_once(JPATH_ROOT.'/modules/'.$yj_mod_name.'/helper_ajax.php');
	require(JPATH_ROOT.'/modules/'.$yj_mod_name.'/yjme/params/params.php');
	
	$response	= new JObject;

	if($cid > 0){
		/*
		 * Only one like per hour verification
		 */
		$sql_string_last = "SELECT * FROM #__yj_news_pop_details WHERE Itemid = ".$cid." AND source = '".$source."' AND ip = '".$_SERVER['REMOTE_ADDR']."' AND last_like > ".(time()-$params->get('delay'));
		$db->setQuery( $sql_string_last );
		$sql_query = $db->query();	
		$num_rows = $db->getNumRows();
		// Make sure there aren't any errors
		if ($db->getErrorNum()) {
			$response->error = $db->getErrorMsg();
			// Send the JSON response.
			echo json_encode($response);
			$app->close();
			exit;
		}	
		if( $num_rows > 0 ){
			/* get the number of votes and send an error message */
			$query = "SELECT COUNT(likes) FROM #__yj_news_pop_details WHERE Itemid = '".((int)$cid)."' AND source = '".$source."'";
			$db->setQuery( $query );
			$likes = $db->loadResult();
			// Make sure there aren't any errors
			if ($db->getErrorNum()) {
				$response->error = $db->getErrorMsg();
				// Send the JSON response.
				echo json_encode($response);
				$app->close();
				exit;
			}				

			$response->likes = $likes;
			$response->error = $language->_('MOD_YOUBRICKS_LIKE_DELAY_ERROR');
			
			// Send the JSON response.
			echo json_encode($response);
			$app->close();
			exit();
		}
		
		/*
		 * Update likes number for content, or insert like if first time
		 */
		$sql_string_article = "SELECT * FROM #__yj_news_pop_details WHERE Itemid = '".$cid."' AND source = '".$source."' AND ip = '".$_SERVER['REMOTE_ADDR']."'";
		$db->setQuery( $sql_string_article );
		$db->Query();
		$num_rows_articles = $db->getNumRows();
		// Make sure there aren't any errors
		if ($db->getErrorNum()) {
			$response->error = $db->getErrorMsg();
			// Send the JSON response.
			echo json_encode($response);
			$app->close();
			exit;
		}		
		if( $num_rows_articles > 0 ){	
			$sql_voter = "UPDATE #__yj_news_pop_details SET likes = likes + 1 WHERE Itemid = '".$cid."' AND source = '".$source."' AND ip = '".$_SERVER['REMOTE_ADDR']."'";
		}else{
			$sql_voter = "INSERT INTO #__yj_news_pop_details VALUES ('',".$cid.",1,".$source.",'".$_SERVER['REMOTE_ADDR']."',".time().")";
		}		
		$db->setQuery( $sql_voter );
		$db->Query( $sql_voter );	
		// Make sure there aren't any errors
		if ($db->getErrorNum()) {
			$response->error = $db->getErrorMsg();
			// Send the JSON response.
			echo json_encode($response);
			$app->close();
			exit;
		}	
		/*
		 * Update like time for content, or insert like time
		 */
		$sql_string_ip = "SELECT * FROM #__yj_news_pop_details WHERE Itemid = ".$cid." AND ip = '".$_SERVER['REMOTE_ADDR']."' AND source = '".$source."'";
		$db->setQuery( $sql_string_ip );
		$db->Query();	
		$num_rows_ip = $db->getNumRows();	
		// Make sure there aren't any errors
		if ($db->getErrorNum()) {
			$response->error = $db->getErrorMsg();
			// Send the JSON response.
			echo json_encode($response);
			$app->close();
			exit;
		}	
		if( $num_rows_ip > 0 ){	
			$sql_voter = "UPDATE #__yj_news_pop_details SET last_like = ".time()." WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND Itemid = '".((int)$cid)."' AND source = '".$source."'";	
		}else{
			$sql_voter = "INSERT INTO #__yj_news_pop_details SET Itemid = '".$cid."', ip = '".$_SERVER['REMOTE_ADDR']."', source = '".$source."', last_like = ".time();		
		}
		$db->setQuery( $sql_voter );
		$db->Query( $sql_voter );		
		// Make sure there aren't any errors
		if ($db->getErrorNum()) {
			$response->error = $db->getErrorMsg();
			// Send the JSON response.
			echo json_encode($response);
			$app->close();
			exit;
		}			
		/* 
		 * display the number of votes
		 */
		$query = "SELECT COUNT(likes) FROM #__yj_news_pop_details WHERE Itemid = '".((int)$cid)."' AND source = '".$source."'";
		$db->setQuery( $query );
		$likes = $db->loadResult();
		// Make sure there aren't any errors
		if ($db->getErrorNum()) {
			$response->error = $db->getErrorMsg();
			// Send the JSON response.
			echo json_encode($response);
			$app->close();
			exit;
		}	
		$response->likes = $likes;
		$response->message = $language->_('MOD_YOUBRICKS_ADD_LIKE_MSG');

		// Send the JSON response.
		echo json_encode($response);
		$app->close();
		exit;

	}else{
		$response->error = $language->_('MOD_YOUBRICKS_INVALID_CONTENT');
		// Send the JSON response.
		echo json_encode($response);
    	$app->close();	
		exit;
	}