<?php
/**
 * Adodis Blog package
 * @author J-Extension <contact@jextn.com>
 * @link http://www.jextn.com
 * @copyright (C) 2012 - 2013 J-Extension
 * @license GNU/GPL, see LICENSE.php for full license.
**/

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

// Import Joomla predefined functions
jimport('joomla.application.component.modelitem');

class AdodisBlogModelBlogs extends JModelItem
{
	/**
	 * total Blogs
	 */
	var $_total								= null;

	/**
	 * Pagination object
	 */
	var $_pagination						= null;

	/**
	 * Constructor
	 */
	function __construct()
	{
		parent::__construct();

		//Get configuration
		$app								= JFactory::getApplication();
		$config								= JFactory::getConfig();

		// Get the pagination request variables
		$this->setState('limit', $app->getUserStateFromRequest('com_adodisblog.limit', 'limit', $config->get('list_limit'), 'int'));
		$this->setState('limitstart', JRequest::getVar('limitstart', 0, '', 'int'));
	}

	protected function populateState($ordering = null, $direction = null)
	{
		$settings							= $this->getSettings();
		$order_by							= $settings->orderby;
		$sort_by							= $settings->sortby;

		$order								= 'bg.'.$order_by;

		$this->setState('list.ordering', $order);

		$this->setState('list.direction', $sort_by);
	}

	/**
	 * Method to get Blogs data.
	 */
	public function getItems()
	{
		// Connect db
		$db									= $this->getDbo();
		$query								= $db->getQuery(true);

		$query->select('bg.id AS blogid, bg.name AS post_by_name, bg.isgood AS bg_isgood, bg.isbad AS bg_isbad, bg.*');
		$query->from('#__adodisblog_blogs AS bg');
		$query->where('bg.published=1');

		$query->select( 'u.*' );
		$query->join( 'LEFT', '#__adodisblog_users AS u ON u.user_id = bg.created_by ' );

		$query->select( 'cat.title AS category_title' );
		$query->join( 'LEFT', '#__categories AS cat ON cat.id = bg.catid' );

		$query->select( 'ct.count_comment' );
		$query->join( 'LEFT', '(SELECT ct.blog_id , count(ct.blog_id) AS count_comment FROM #__adodisblog_comments AS ct WHERE ct.published=1 GROUP By ct.blog_id) as ct ON ct.blog_id = bg.id' );

		$db->setQuery($query);
		$blog								= $db->loadObjectList();

		if ($error = $db->getErrorMsg()) {
			throw new Exception($error);
		}

		if( empty($blog) ) {
			JError::raiseNotice(404, JText::_('COM_ADODISBLOG_ERROR_BLOGS_NOT_FOUND'));
		} else {
			$query->where('bg.published = 1');
			$query->order($db->getEscaped($this->getState('list.ordering', 'bg.ordering')).' '.$db->getEscaped($this->getState('list.direction', 'desc')));

			$blogs							= $db->loadObjectList();

			if( empty( $blogs )) {
				JError::raiseNotice(404, JText::_('COM_ADODISBLOG_ERROR_BLOGS_NOT_PUBLISHED'));
			}

			$this->_total					= count($blogs);

			if ($this->getState('limit') > 0) {
				$this->_data				= array_splice($blogs, $this->getState('limitstart'), $this->getState('limit'));
			} else {
				$this->_data				= $blogs;
			}

			return $this->_data;

		}
	}

	/**
	 * Method to get the total number of weblink items for the category
	 */
	function getTotal()
	{
		return $this->_total;
	}

	/**
	 * Method to get a pagination object of the weblink items for the category
	 */
	function getPagination()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination				= new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit'));
		}

		return $this->_pagination;
	}

	public function getSettings()
	{
		$id					= 1;
		$settings  			= JTable::getInstance('Settings', 'AdodisBlogTable');
		$settings->load($id);

		return $settings;
	}

	public function activateBlog(){

		$id					= JRequest::getInt('tid');
		$table  			= JTable::getInstance('Blog', 'AdodisBlogTable');
		$table->load($id);
		$table->published 	= '1';

		if (!$table->store()) {
			return false;
		} else {
			return true;
		}
	}

	public function checkUserBlock()
	{
		$user			= & JFactory::getUser();
		$uid			= $user->get('id');

		if($uid){
			$db			= $this->getDbo();
			$query		= $db->getQuery(true);
			$query->select('ur.block');
			$query->from('#__adodisblog_users AS ur');
			$query->where('ur.user_id ='.$uid);
			$db->setQuery($query);
			$block		= $db->loadResult();
			return $block;
		}
	}

	public function updateLikesBlog($id,$likes,$ival,$liketxt,$disliketxt){
		$db								= $this->getDbo();
		$query							= $db->getQuery(true);
		$user							= & JFactory::getUser();

		// to find the rated user
		$query->select('b.*');
		$query->from('#__adodisblog_blogs as b');
		$query->where('b.id='.$id);
		$db->setQuery($query);
		$result 						= $db->loadObjectList();
		$isgood 						= $result[0]->isgood;
		$isbad							= $result[0]->isbad;

		$userid_check 					= $result[0]->rated_ids;
		$userid_check 					= explode(",",$userid_check);
		//condition to check the user existance
		$app							= JFactory::getApplication();
		$params 						= $app->getParams();
		if($params->get('show_like_dislike_b_or',1))
		{
			if(!$user->id){
				echo sprintf(JText::_('COM_ADODISBLOG_BLOG_LOGIN_ACCESS_LIKES_DISLIKES'),$liketxt,$disliketxt).',none';
			}
			else if(in_array($user->id,$userid_check)){
				echo JText::_('COM_ADODISBLOG_COMMENTS_ALREADY_VOTED').',none';
			}else{
				$query					= $db->getQuery(true);
				$query->update('`#__adodisblog_blogs`');
				if($likes == '1' ){
					$addisgood 			= $isgood+1;
					$query->set("isgood = ".$addisgood);
				}else{
					$addisbad 			= $isbad+1;
					$query->set("isbad = ".$addisbad);
				}
				$query->where('id ='.$id);
				$db->setQuery($query);
				if($db->query()){

					//to display the number of likes

					$query->select('b.*');
					$query->from('#__adodisblog_blogs as b');
					$query->where('b.id='.$id);
					$db->setQuery($query);
					$new_result 		= $db->loadObjectList();

					// update user id in Blogs

					$rated_ids 			= $new_result[0]->rated_ids;
					if($rated_ids){
						$updated_ids 	= $rated_ids.",".$user->id;
					}else{
						$updated_ids 	= $user->id;
					}
					$query				= $db->getQuery(true);
					$query->update('`#__adodisblog_blogs`');
					$query->set("rated_ids = '$updated_ids'");
					$query->where('id ='.$id);
					$db->setQuery($query);
					$db->query();

					// display likes and dislikes
					$output 			= $new_result[0]->isgood - $new_result[0]->isbad;

					echo JText::_('COM_ADODISBLOG_COMMENTS_LIKES').$new_result[0]->isgood." ".JText::_('COM_ADODISBLOG_COMMENTS_DISLIKES').$new_result[0]->isbad.','.$output.','.$new_result[0]->isgood.','.$new_result[0]->isbad;
				}
				return $new_result;
			}
		} else {
			$session 					= JFactory::getSession();
			if($session->get('blog_like_sess'.$id)!='liked'){
				$query					= $db->getQuery(true);
				$query->update('`#__adodisblog_blogs`');
				if($likes == '1' ){
					$addisgood 			= $isgood+1;
					$query->set("isgood = ".$addisgood);
				}else{
					$addisbad 			= $isbad+1;
					$query->set("isbad = ".$addisbad);
				}
				$query->where('id ='.$id);
				$db->setQuery($query);
				if($db->query()){

					//to display the number of likes

					$query->select('b.*');
					$query->from('#__adodisblog_blogs as b');
					$query->where('b.id='.$id);
					$db->setQuery($query);
					$new_result 		= $db->loadObjectList();

					// display likes and dislikes
					$output 			= $new_result[0]->isgood - $new_result[0]->isbad;
					echo JText::_('COM_ADODISBLOG_COMMENTS_LIKES').$new_result[0]->isgood." ".JText::_('COM_ADODISBLOG_COMMENTS_DISLIKES').$new_result[0]->isbad.','.$output.','.$new_result[0]->isgood.','.$new_result[0]->isbad;
					$session->set('blog_like_sess'.$id, 'liked');
				}
				return $new_result;
			} else {
				echo JText::_('COM_ADODISBLOG_COMMENTS_ALREADY_VOTED').',none';
			}
		}
	}
}
?>
