<?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('K2_CB')){
				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('K2_CB')){
				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){
//#__content_rating WHERE content_id
            $db = &JFactory::getDBO();
            $userIP = $_SERVER['REMOTE_ADDR'];
            $query = "SELECT * FROM #__content_rating WHERE content_id =".$cid;
            $db->setQuery($query);
            $rating = $db->loadObject();

            if (!$rating)
            {
                $query = "INSERT INTO #__content_rating ( content_id, lastip, rating_sum, rating_count ) VALUES ( ".$cid.", ".$db->Quote($userIP).", 5, 1 )";
                $db->setQuery($query);
                $db->query();
				$response->likes = 1;
				$response->message = $language->_('MOD_YOUBRICKS_ADD_LIKE_MSG');
						echo json_encode($response);
						$app->close();
						exit;
            }

            else
            {
                if ($userIP != ($rating->lastip))
                {
                    $query = "UPDATE #__content_rating"." SET rating_count = rating_count + 1, rating_sum = rating_sum + 5, lastip = ".$db->Quote($userIP)." WHERE content_id = {$cid}";
                    $db->setQuery($query);
                    $db->query();
				$response->likes = 1;
				$response->message = $language->_('MOD_YOUBRICKS_ADD_LIKE_MSG');
						echo json_encode($response);
						$app->close();
						exit;

                }
                else
                {
				$response->likes = 0;
				$response->error = $language->_('MOD_YOUBRICKS_LIKE_DELAY_ERROR');
						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;
	}