<?php

/**
 * @name          : Joomla Social Pinboard
 ** @version	  : 2.0
 * @package       : apptha
 * @since         : Joomla 1.5
 * @author        : Apptha - http://www.apptha.com
 * @copyright     : Copyright (C) 2011 Powered by Apptha
 * @license       : http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL
 * @abstract      : Social Pinboard Component follow model
 * @Creation Date : March 2013
 * @Modified Date : March 2013
 * */
// No direct Access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');
jimport('joomla.user.helper');

class wishlogueModelfamily extends WishlogueModel {

	///rgs.

    function getMemberProfile($user_id) {

        $db = $this->getDBO();
        $query = "select website, email, about, user_id,user_image,username,first_name,last_name from #__pin_user_settings where user_id = $user_id ";
        $db->setQuery($query);
        $user_result = $db->loadObject();

        return $user_result;
    }

	function MAIL_Request( $toID, $fromID, $subject, $Field )
	{
		if($Field == 'Friends') {
			$Field = 'Friend';
		}
		$db = $this->getDBO();

		$Result = $this->getMemberProfile($toID);
		$to_user_about = $Result->about;
		$to_user_website = $Result->website;
		$to_user_image = $Result->user_image;
		$to_user_name = ucwords($Result->first_name) . ' ' . ucwords($Result->last_name);
		$to_user_url = JURI::root() . 'index.php?option=com_wishlogue&view=cataloguedisplay&uid=' . $toID;
		if ($to_user_image != '') {
			$to_user_image_o = substr($to_user_image, 0, strlen($to_user_image)-4) . '_o.jpg';
			if( file_exists( JPATH_ROOT . '/images/wishlogue/avatars/' . $to_user_image_o ) ) {
				$to_user_image = JURI::base() . 'images/wishlogue/avatars/' . $to_user_image_o;
			}
			else if( file_exists( JPATH_ROOT . '/images/wishlogue/avatars/' . $to_user_image ) ) {
				$to_user_image = JURI::base() . 'images/wishlogue/avatars/' . $to_user_image;
			} else {
				$to_user_image = JURI::Base() . 'components/com_wishlogue/images/no_user.png';
			}
		} else {
			$to_user_image = JURI::Base() . 'components/com_wishlogue/images/no_user.png';
		}

		$Result = $this->getMemberProfile($fromID);
		$toEmail = $Result->email;
		$from_user_name = ucwords($Result->first_name) . ' ' . ucwords($Result->last_name);

		$subject = str_replace('{Friend_Family}', $Field, $subject);
		$Subject = str_replace('{user_name}', $to_user_name, $subject);
		$subject = str_replace('{user_name}', "<a href='$to_user_url'>" . $to_user_name . '</a>', $subject);

		$mailer = JFactory::getMailer();
		$app = JFactory::getApplication();
		$config = JFactory::getConfig();
		$sender = $config->get('mailfrom');
		$site_name = $config->get('sitename');
		$mailer->setSender($sender);
		$templateparams = $app->getTemplate(true)->params;
		$logo = $templateparams->get('logo');
		if ($logo != null) {
			$image_source = JURI::base() . '/' . htmlspecialchars($logo);
		} else {
			$image_source = JURI::base() . '/templates/wishlogue/images/logo-large.png';
		}
		$mailer->addRecipient($toEmail);
		$baseurl = JURI::base();
		$message = file_get_contents(JURI::base() . '/templates/wishlogue/emailtemplate/mail_request.html');
		$message = str_replace("{baseurl}", $baseurl, $message);
		$message = str_replace("{site_name}", $site_name, $message);
		$message = str_replace("{site_logo}", $image_source, $message);
		$message = str_replace("{subject}", $subject, $message);
		$message = str_replace("{from_user_name}", $from_user_name, $message);
		$message = str_replace("{to_user_url}", $to_user_url, $message);
		$message = str_replace("{to_user_image}", $to_user_image, $message);
		$message = str_replace("{to_user_name}", $to_user_name, $message);
		$message = str_replace("{to_user_about}", $to_user_about, $message);
		$message = str_replace("{to_user_website}", $to_user_website, $message);

		$mailer->isHTML(true);
		$mailer->setSubject($Subject);
		$mailer->Encoding = 'base64';
		$mailer->setBody($message);

		$send = $mailer->Send();
	}

	function getMembersCount( $field )
	{
		$user = JFactory::getUser();
		$userId = $user->id;
		$db = $this->getDBO();

		$query = "SELECT $field FROM #__pin_user_settings 
					WHERE status = 1 AND user_id = $userId";
		$db->setQuery($query);
		$modeResult = $db->loadResult();
		if( $modeResult == '' || $modeResult == null ) {
			return '0';
		}
		else {
			$modeRes = explode(',', $modeResult);
			return count($modeRes);
		}
	}

	function FamilySearchBox($SearchTerm, $field)
	{
		$SearchTerm = preg_replace( '/\s+/', ' ', $SearchTerm );
		$SearchTerm = trim($SearchTerm);
		if ( $SearchTerm != '' && $SearchTerm != null )
		{
			$user = JFactory::getUser();
			$userId = $user->id;
			$db = $this->getDBO();

			$query = "SELECT user_image, username, first_name, last_name, user_id 
						FROM #__pin_user_settings
						WHERE CONCAT(first_name, ' ', last_name, ' ', username) LIKE '%$SearchTerm%' 
						AND user_id NOT IN ($userId) AND status = 1 AND published != -2";
			$db->setQuery($query);
			$SearchResult = $db->loadObjectList();
			foreach( $SearchResult as $Result ) {
				if (!$Result->user_image) {
					$srcPath = JUri::root() . "/components/com_wishlogue/images/no_user.png";
				} else {
					$userImageDetails = pathinfo($Result->user_image);
					$userProfileImage = $userImageDetails['filename'] . '_o.' . $userImageDetails['extension'];
					$srcPath = JUri::root() . "/images/wishlogue/avatars/" . $userProfileImage;
				}
				$data[] = array(
				'value' => $Result->first_name . ' ' . $Result->last_name . ' (' . $Result->username . ')',
				'label' => "<img align='left' src='$srcPath' width='20' height='20'>" . 
							$Result->first_name . ' ' . $Result->last_name . ' (' . $Result->username . ')', );
			}
			if(!isset($data)) {
				$data[] = array(
					'value' => '',
					'label' => JText::_('COM_WISHLOGUE_SEARCH_FAMILY_NO_RESULTS'), );
			}
		}
		else {
			$data[] = array(
				'value' => '',
				'label' => JText::_('COM_WISHLOGUE_SEARCH_FAMILY_NO_RESULTS'), );
		}
		return $data;
    }

	// function to decline Request from notifications
	function declineRequest($member, $field)
	{
        $db = $this->getDBO();
        $user = JFactory::getUser();
        $userId = $user->id;

		/// get Relationship
		$getRelationship = $this->getRelationship($member, $field);
		if( $getRelationship == 'already_received' )
		{
			$query = "DELETE FROM #__pin_notifications WHERE from_id = $member
						AND to_id = $userId AND notify_for = 'invite_" . "$field'";
			$db->setQuery($query);
			$db->query();
			return 'request_deleted';
		}
		return 'failed';
    }

	// function to accept Request from notifications
	function acceptRequest($member, $field)
	{
        $db = $this->getDBO();
        $user = JFactory::getUser();
        $userId = $user->id;

		/// get Relationship
		$getRelationship = $this->getRelationship($member, $field);
		if( $getRelationship == 'already_received' ) {
			return $this->confirmRequest($member, $field);
		}
		return 'failed';
    }

	function removefromFamily($member, $field)
	{
        $db = $this->getDBO();
        $user = JFactory::getUser();
        $userId = $user->id;

		/// get Relationship
		$getRelationship = $this->getRelationship($member, $field);

		if( $getRelationship == 'already_sent' )
		{
			$query = "DELETE FROM #__pin_notifications WHERE from_id = $userId
						AND to_id = $member AND notify_for = 'invite_" . "$field'";
			$db->setQuery($query);
			$db->query();
			return 'request_deleted';
		}
		else if( $getRelationship == 'already_received' )
		{
			$query = "DELETE FROM #__pin_notifications WHERE from_id = $member
						AND to_id = $userId AND notify_for = 'invite_" . "$field'";
			$db->setQuery($query);
			$db->query();
			return 'request_deleted';
		}
		else if( $getRelationship == 'already_exist' )
		{
			$query = "SELECT $field FROM #__pin_user_settings WHERE user_id = $userId";
			$db->setQuery($query);
			$friends = $db->loadResult();
			$friendsArray = explode(',', $friends);
			if(($key = array_search($member, $friendsArray)) !== false) {
				unset($friendsArray[$key]);
			}
			$friends = implode(',', $friendsArray);
			$query = "UPDATE #__pin_user_settings SET $field = '$friends' WHERE user_id= $userId";
			$db->setQuery($query);
			$db->query();

			$query = "SELECT $field FROM #__pin_user_settings WHERE user_id = $member";
			$db->setQuery($query);
			$friends = $db->loadResult();
			$friendsArray = explode(',', $friends);
			if(($key = array_search($userId, $friendsArray)) !== false) {
				unset($friendsArray[$key]);
			}
			$friends = implode(',', $friendsArray);
			$query = "UPDATE #__pin_user_settings SET $field = '$friends' WHERE user_id= $member";
			$db->setQuery($query);
			$db->query();

			return 'member_removed';
		}
		else
		{
			return $getRelationship;
		}
		return 'failed';
    }

	function getRelationship($member, $field) {
        $db = $this->getDBO();
        $user = JFactory::getUser();
        $userId = $user->id;

		if ( $userId <= 0 ) {
			return 'failed';
		}

		if ( $userId == $member ) {
			return 'thats_you';
		}
		else if ( $member > 0 && $field != '' )
		{
			if ( $field == 'family') {
				$field_a = 'friends';
			}
			else if ( $field == 'friends') {
				$field_a = 'family';
			}

			///check already exist or not
			$query = "SELECT $field FROM #__pin_user_settings 
						WHERE status = 1 AND user_id = $userId";
			$db->setQuery($query);
			$modeResult = $db->loadResult();
			$modeRes = explode(',', $modeResult);
			if(($key = array_search($member, $modeRes)) !== false) {
				return 'already_exist';
			}

			///check another exist or not
			$query = "SELECT $field_a FROM #__pin_user_settings 
						WHERE status = 1 AND user_id = $userId";
			$db->setQuery($query);
			$modeResult = $db->loadResult();
			$modeRes = explode(',', $modeResult);
			if(($key = array_search($member, $modeRes)) !== false) {
				return "another_exist";
			}

			///check already sent or not
			$query = "SELECT notify_id FROM #__pin_notifications 
						WHERE from_id = $userId AND to_id = $member AND notify_for = 'invite_$field' ";
			$db->setQuery($query);
			$notifyResult = $db->loadResult();
			if( $notifyResult > 0 ) {
				return 'already_sent';
			}

			///check another sent or not
			$query = "SELECT notify_id FROM #__pin_notifications 
						WHERE from_id = $userId AND to_id = $member AND notify_for = 'invite_$field_a' ";
			$db->setQuery($query);
			$notifyResult = $db->loadResult();
			if( $notifyResult > 0 ) {
				return 'another_sent';
			}

			///check already received or not
			$query = "SELECT notify_id FROM #__pin_notifications 
					WHERE from_id = $member AND to_id = $userId AND notify_for = 'invite_$field'";
			$db->setQuery($query);
			$notifyResult = $db->loadResult();
			if( $notifyResult > 0 ) {
				return 'already_received';
			}

			///check another received or not
			$query = "SELECT notify_id FROM #__pin_notifications 
					WHERE from_id = $member AND to_id = $userId AND notify_for = 'invite_$field_a'";
			$db->setQuery($query);
			$notifyResult = $db->loadResult();
			if( $notifyResult > 0 ) {
				return 'another_received';
			}

			///there is no relation
			return 'no_relation';
		}
		return 'failed';
    }
	
	///Function for confirm a request
	function confirmRequest($member, $field)
	{
	    $db = $this->getDBO();
        $user = JFactory::getUser();
        $userId = $user->id;

		$query = "UPDATE #__pin_user_settings 
					SET $field = IF($field = '', '$member', CONCAT($field,',','$member')) 
					WHERE user_id= $userId";
		$db->setQuery($query);
		if ( $db->query() ) {
			$query = "UPDATE #__pin_user_settings 
						SET $field = IF($field = '', '$userId', CONCAT($field,',','$userId')) 
						WHERE user_id = $member";
			$db->setQuery($query);
			$db->query();
			$query = "INSERT INTO #__pin_notifications( from_id, to_id, notify_for ) 
					VALUES( $userId, $member, CONCAT( 'confirm_', '$field' ) )";
			$db->setQuery($query);
			$db->query();
			$query = "DELETE FROM #__pin_notifications WHERE from_id = $member
						AND to_id = $userId AND notify_for = 'invite_" . "$field'";
			$db->setQuery($query);
			$db->query();
			
			///--MAIL Confirm 
			$query = "SELECT `email_settings` FROM `#__pin_user_settings` WHERE `user_id` = " . $member;
			$db->setQuery($query);
			$emailSettings = $db->loadResult();
			$email_settings = unserialize($emailSettings);
			if ( isset($email_settings['accept_request']) && $email_settings['accept_request'] == 1 ) {
				$this->MAIL_Request( $userId, $member, JText::_('COM_WISHLOGUE_MAIL_REQUEST_ACCEPTED'), ucwords($field) );
			}

			return 'request_confirmed';
		}
		return 'failed';
	}

	///Function for send a request
	function sendRequest($member, $field)
	{
        $db = $this->getDBO();
        $user = JFactory::getUser();
        $userId = $user->id;

		$query = "INSERT INTO #__pin_notifications( from_id, to_id, notify_for ) 
					VALUES( $userId, $member, CONCAT( 'invite_', '$field' ) )";
		$db->setQuery($query);
		if ( $db->query() ) {

			///--MAIL Sent
			$query = "SELECT `email_settings` FROM `#__pin_user_settings` WHERE `user_id` = " . $member;
			$db->setQuery($query);
			$emailSettings = $db->loadResult();
			$email_settings = unserialize($emailSettings);
			if ( isset($email_settings['accept_request']) && $email_settings['accept_request'] == 1 ) {
				$this->MAIL_Request( $userId, $member, JText::_('COM_WISHLOGUE_MAIL_REQUEST_SENT'), ucwords($field) );
			}

			return 'request_sent';
		}
		return 'failed';
	}

	function addtoFamily($member, $field)
	{
        $db = $this->getDBO();
        $user = JFactory::getUser();
        $userId = $user->id;

		/// get Relationship
		$getRelationship = $this->getRelationship($member, $field);

		if( $getRelationship == 'already_received' ) {
			return $this->confirmRequest($member, $field);
		}
		else if( $getRelationship == 'no_relation' ) {
			return $this->sendRequest($member, $field);
		}
		else {
			return $getRelationship;
		}
    }

	function addfamilysearch($membername, $field) {
        $db = $this->getDBO();
        $user = JFactory::getUser();
        $userId = $user->id;

		if ( $membername == '' || $membername == null ) {
			return 'failed';
		}
		$query = "SELECT user_id FROM #__pin_user_settings 
					WHERE status = 1 AND username = '$membername'";
		$db->setQuery($query);
		$member = $db->loadResult();

		/// get Relationship
		$getRelationship = $this->getRelationship($member, $field);
		if( $getRelationship == 'already_received' ) {
			$return = $this->confirmRequest($member, $field);
			// return $return;
		}
		else if( $getRelationship == 'no_relation' ) {
			$return = $this->sendRequest($member, $field);
			return $return;
		}
		else {
			return $getRelationship;
		}

		if ( $return == 'request_confirmed' )
		{
			$query = "SELECT username, user_image, first_name, last_name 
						FROM #__pin_user_settings
						WHERE user_id = $member";
			$db->setQuery($query);
			$DivContent = $db->loadObject();
			if ( $DivContent->user_image == ''){
				$imgPath = JURI::base() . '/components/com_wishlogue/images/no_user.png';
			}
			else{
				$imgPath = JURI::base() . '/images/wishlogue/avatars/' . $DivContent->user_image;
			}
			$query = "SELECT COUNT(pin_id) FROM #__pin_pins WHERE status=1 AND pin_user_id=" . $member;
			$db->setQuery($query);
			$pinCount = $db->loadResult();
			$query = "SELECT COUNT(board_id) FROM #__pin_boards WHERE status=1 AND user_id=" . $member;
			$db->setQuery($query);
			$boardCount = $db->loadResult();

			$returnText = "<div id='userbox_" . $DivContent->username . "'>";
			$returnText .= "<input type='hidden' id='userid_" . $DivContent->username . "' value='" . $member . "' >";
			$returnText .= '<div class="board-followername">';
			$returnText .= '<div class="board-followername_left">';
					$memURL = JRoute::_('index.php?option=com_wishlogue&view=cataloguedisplay&uid=' . $member);
			$returnText .= '<a href="' . $memURL . '">';
			$returnText .= "<img alt='' src='$imgPath' height='75' width='75' /></a></div>";
			$returnText .= '<div class="board-followername_right">';
			$returnText .= '<h4><a href="' . $memURL . '">';
			$returnText .= $DivContent->first_name . ' ' . $DivContent->last_name;
			$returnText .= '</a></h4><div class="count_items">';
			$returnText .= JText::_('COM_WISHLOGUE_BOARDS') . ' : ' . $boardCount;
			$returnText .= ' ' . JText::_('COM_WISHLOGUE_PINS') . ' : ' . $pinCount;
			$returnText .= '</div></div>';

			$returnText .= '<div class="DIVunfriend' . $DivContent->username . '" id="DIVunfriend' . $member . '" >';
					$managefamily = "managefamily('$member', '$field', 'removefromFamily')";
			$returnText .= '<input type="button" id="unfriend" onclick="' . $managefamily . '" value="' . JText::_('COM_WISHLOGUE_FAMILY_REMOVE') . '" />';
			$returnText .= '</div>';

			$returnText .= '<div class="DIVaddfriend' . $DivContent->username . '" id="DIVaddfriend' . $member . '" style="display:none;" >';
					$managefamily = "managefamily('$member', '$field', 'addtoFamily')";
			$returnText .= '<input type="button" id="addfriend" onclick="' . $managefamily . '" value="' . JText::_('COM_WISHLOGUE_FAMILY_ADD') . '" />';
			$returnText .= '</div>';

			$returnText .= '<div class="DIVacceptfriend' . $DivContent->username . '" id="DIVacceptfriend' . $member . '" style="display:none;" >';
					$managefamily = "managefamily('$member', '$field', 'addtoFamily')";
			$returnText .= '<input type="button" id="acceptfriend" onclick="' . $managefamily . '" value="' . JText::_('COM_WISHLOGUE_FAMILY_CONFIRM_REQUEST') . '" />';
					$managefamily = "managefamily('$member', '$field', 'removefromFamily')";
			$returnText .= '<input type="button" id="declinefriend" onclick="' . $managefamily . '" value="' . JText::_('COM_WISHLOGUE_FAMILY_DECLINE_REQUEST') . '" />';
			$returnText .= '</div>';

			$returnText .= '<div class="DIVremovefriend' . $DivContent->username . '" id="DIVremovefriend' . $member . '" style="display:none;" >';
					$managefamily = "managefamily('$member', '$field', 'removefromFamily')";
			$returnText .= '<input type="button" id="removefriend" onclick="' . $managefamily . '" value="' . JText::_('COM_WISHLOGUE_FAMILY_REMOVE_REQUEST') . '" />';
			$returnText .= '</div>';

			$returnText .= '<div class="DIVmessage' . $DivContent->username . '" id="DIVmessage' . $member . '" style="display:none;" >';
			$returnText .= '</div>';

			$returnText .= '</div></div>';

			return $returnText;
		}
		return 'failed';
    }

    function getMemberDetails($field) 
	{
        $db = $this->getDBO();
        $user = JFactory::getUser();
        $userId = $user->id;

		//existing
        $query = "SELECT $field FROM #__pin_user_settings 
					WHERE status = 1 AND user_id = $userId";
        $db->setQuery($query);
        $friends = $db->loadResult();
		$friends = str_replace(',,', ',', $friends);
		if( $friends != '' ) {
			if( $friends[0] == ',' ) {
				$friends = substr($friends, 1);
			}
		}

		if( $friends != '' && $friends != null ) {
			$query = "SELECT username, user_image, first_name, last_name, user_id 
						FROM #__pin_user_settings
						WHERE user_id IN ($friends) AND status = 1";
			$db->setQuery($query);
			$loadFriends = $db->loadAssocList();
		}

		if( isset($loadFriends) )
		{
			foreach( $loadFriends as $key => $friend )
			{
				$memberID = $friend['user_id'];

				$query = "SELECT COUNT(pin_id) FROM #__pin_pins WHERE status=1 AND pin_user_id=" . $memberID;
				$db->setQuery($query);
				$pinCount = $db->loadResult();
				$loadFriends[$key]['pinCount'] = $pinCount;

				$query = "SELECT COUNT(board_id) FROM #__pin_boards WHERE status=1 AND user_id=" . $memberID;
				$db->setQuery($query);
				$boardCount = $db->loadResult();
				$loadFriends[$key]['boardCount'] = $boardCount;

				$getRelationship = $this->getRelationship($memberID, $field);
				$loadFriends[$key]['friend_status'] = $getRelationship;
			}
			return $loadFriends;
		}
        return array();
    }

    function searchForFamily( $SearchTerm, $field ) {
        $db = $this->getDBO();
        $user = JFactory::getUser();
        $userId = $user->id;

		$SearchTerm = preg_replace( '/\s+/', ' ', $SearchTerm );
		$SearchTerm = trim($SearchTerm);
		$SearchTerm = str_replace('(', '', $SearchTerm);
		$SearchTerm = str_replace(')', '', $SearchTerm);

		if ( $SearchTerm != '' && $SearchTerm != null )
		{
	        $pageno = 0;
			$length = 200;
			if (JRequest::getVar('page')) {
				$pageno = JRequest::getVar('page')-1;
				$pageno = $pageno * 200;
			}
			$pageno = 0;
			$length = 200;
			$query = "SELECT username, user_image, first_name, last_name, user_id 
						FROM #__pin_user_settings
						WHERE  CONCAT(first_name, ' ', last_name, ' ', username) LIKE '%$SearchTerm%' 
						AND user_id NOT IN ($userId) AND status = 1 AND published != -2 LIMIT $pageno,$length";
			$db->setQuery($query);
			$familyDetails = $db->loadAssocList();
			if( isset($familyDetails) )
			{
				foreach( $familyDetails as $key => $familyMember )
				{
					$memberID = $familyMember['user_id'];

					$query = "SELECT COUNT(pin_id) FROM #__pin_pins WHERE status=1 AND pin_user_id=" . $memberID;
					$db->setQuery($query);
					$pinCount = $db->loadResult();
					$familyDetails[$key]['pinCount'] = $pinCount;

					$query = "SELECT COUNT(board_id) FROM #__pin_boards WHERE status=1 AND user_id=" . $memberID;
					$db->setQuery($query);
					$boardCount = $db->loadResult();
					$familyDetails[$key]['boardCount'] = $boardCount;

					$getRelationship = $this->getRelationship($memberID, $field);
					$familyDetails[$key]['friend_status'] = $getRelationship;
				}
				return $familyDetails;
			}
		}
        return array();
    }
	///rgs..

    function getFollowing() {
        $db = JFactory::getDbo();
        $user = JFactory::getUser();
        $user_id = $user->id;
        $userID = JRequest::getInt('uid');
        if ($userID != '') {
            $userId = $userID;
        } else {
            $userId = $user_id;
        }

        $query = "SELECT b.user_id, b.username,b.first_name,b.last_name,b.user_image,a.follow_user_board, (
                SELECT COUNT( board_id )
                FROM #__pin_boards
                WHERE (user_id = b.user_id OR cuser_id=b.user_id) and status=1
                ) AS bid, (
                SELECT COUNT( pin_id )
                FROM #__pin_pins
                WHERE pin_user_id = b.user_id and status=1
                ) AS pid
                FROM #__pin_follow_users AS a
                INNER JOIN #__pin_user_settings AS b ON a.follow_user_id = b.user_id
                WHERE a.user_id =$userId
        AND b.status=1 group by b.user_id";

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

        return $follow_details;
    }

    function getFollower() {
        $db = JFactory::getDbo();
        $user = JFactory::getUser();
        $user_id = $user->id;
        $userID = JRequest::getInt('uid');
        if ($userID != '') {
            $userId = $userID;
        } else {
            $userId = $user_id;
        }
        $query = "SELECT b.user_id,b.username,b.first_name,b.last_name,b.user_image,a.follow_user_board,  (SELECT COUNT( board_id )
                FROM #__pin_boards
                WHERE (user_id = b.user_id OR cuser_id=$userId) and status=1
                ) AS bid, (

                SELECT COUNT( pin_id )
                FROM #__pin_pins
                WHERE pin_user_id = b.user_id and status=1
                ) AS pid
                  FROM  #__pin_follow_users as a  INNER JOIN #__pin_user_settings as b ON a.user_id=b.user_id
                  WHERE  a.follow_user_id =$userId
        AND b.status=1 group by b.user_id";


        $db->setQuery($query);
        $follow_details = $db->loadObjectList();
        return $follow_details;
    }

    function countPins() {
        $db = $this->getDBO();
        $user = JFactory::getUser();
        $users = JRequest::getInt('uid');
        if (isset($users) & $users != '0') {
            $userId = $users;
        } else {
            $userId = $user->id;
        }
        $query = "select count(pin_id) from #__pin_pins where status=1 and pin_user_id=" . $userId;
        $db->setQuery($query);
        $pinCount = $db->loadResult();

        return $pinCount;
    }

    function totalBoard() {
        $db = $this->getDBO();
        $user = JFactory::getUser();
        $users = JRequest::getInt('uid');

        if (isset($users) & $users != '0') {
            $userId = $users;
        } else {
            $userId = $user->id;
        }

        $query = "select count(board_id)
                  from #__pin_boards where status=1 and (cuser_id=$userId OR user_id= $userId)";
        $db->setQuery($query);
        $total = $db->loadResult();

        return $total;
    }

    function getLikes() {
        $db = $this->getDBO();
        $user = JFactory::getUser();
        $users = JRequest::getInt('uid');
        if (isset($users) & $users != '0') {
            $userId = $users;
        } else {
            $userId = $user->get('id');
        }
        $query = "select DISTINCT a.* from #__pin_likes as a left join #__pin_pins as b on a.pin_id=b.pin_id where a.status=1 and b.status=1 and a.pin_like='1' and a.pin_like_user_id=" . $userId;
        $db->setQuery($query);
        $pinLikes = $db->loadObjectList();
        return $pinLikes;
    }

// Added by Sathish for get user details
    function getProfile() {
        $db = $this->getDBO();
        $user = JFactory::getUser();
        $users = JRequest::getInt('uid');

        if (isset($users) && $users != '0') {
            $userId = $users;
        } else {
            $userId = $user->get('id');
        }
        $query = "select * from #__pin_user_settings where user_id = $userId";
        $db->setQuery($query);
        $userDetails = $db->loadObjectList();
        return $userDetails;
    }

// Added by Sathish for get block status of the user
    function getblockStatus() {
        $db = $this->getDBO();
        $user = Jfactory::getUser();
        $user_id = $user->id;
        $users = JRequest::getInt('uid');
        $query = "select status from #__pin_user_block where user_id=$user_id and user_block_id = $users";
        $db->setQuery($query);
        $blockStatus = $db->loadObjectList();
        return $blockStatus;
    }

// Added by Sathish for get the reported users reported by the login user
    function getReportUsers() {
        $db = JFactory::getDBO();
        $user = JFactory::getUser();
        $user_id = $user->id;
        $query = "select * from #__pin_userreports where report_sender=$user_id GROUP BY report_receiver";
        $db->setQuery($query);
        $reportuserslist = $db->loadObjectList();
        return $reportuserslist;
    }

    static function getModRepinpinUserdetails($resultmodrepin) {
        $db = JFactory::getDBO();
        $query = "select concat(a.first_name,' ',a.last_name ) as
username,b.pin_user_id,a.user_image from #__pin_user_settings as a inner join #__pin_pins as b
on a.user_id=b.pin_user_id where b.pin_id = $resultmodrepin AND a.status = 1";
        $db->setQuery($query);
        $modrepinuserdetails = $db->loadObjectList();
        return $modrepinuserdetails;
    }

    static function Userboardscount($userid, $fuserid) {
        $db = JFactory::getDBO();
        $query = "SELECT count(board_id)
                  FROM #__pin_boards
                  WHERE status=1
                  AND (user_id=" . $fuserid . " OR cuser_id LIKE '%$fuserid%')";
        $db->setQuery($query);
        $fuser_board_count[0] = $db->loadResult();

        $query = "SELECT follow_user_board
FROM  `#__pin_follow_users`
WHERE user_id =  '$userid'
AND follow_user_id =  '$fuserid'";
        $db->setQuery($query);
        $followBoard = $db->loadResult();

        //explode the followed boards into arrays for boards selected invidually
        $boards = explode(",", $followBoard);
        $user_following_boards[0] = count($boards);
        $result_board_count = array_merge($fuser_board_count, $user_following_boards);
        return $result_board_count;
    }

    // Added by Sathish for get Repin activities of the users
    function getRepinActivities() {
        $db = $this->getDBO();
        $user = JFactory::getUser();
        $users = JRequest::getInt('uid');

        if (isset($users) && $users != '0') {
            $userId = $users;
        } else {
            $userId = $user->get('id');
        }
        $repins = array();

        if ($userId) {
            $db = JFactory::getDBO();
            // $query = "select distinct
// (a.pin_user_id),a.pin_id,a.pin_image,a.pin_description,a.pin_repin_id,a.link_type,a.created_date
// ,b.username,b.user_id,b.user_image,'Repin'
         // AS type  from #__pin_pins as a Left join #__pin_user_settings as b on
// b.user_id=a.pin_user_id where (a.pin_user_id=$userId  AND b.status=1 and a.status = 1
           // AND a.pin_repin_id <> 0)  order by a.pin_id desc limit 0,3";

	   $query = "SELECT DISTINCT(a.pin_repin_id) 
			FROM #__pin_pins a 
			INNER JOIN #__pin_pins c 
			WHERE a.pin_repin_id = c.pin_id 
			AND a.pin_user_id = $userId AND 
			a.status = 1 AND c.pin_user_id != $userId 
			GROUP BY(c.pin_user_id) DESC limit 0,3";

            $db->setQuery($query);
            $repinactivities = $db->loadObjectList();
        }

        return $repinactivities;
    }

    function getUserprofile() {
        global $pin_user_id;
        $pin_user_id = JRequest::getInt('uid');
        $user = Jfactory::getUser();
        $user_id = $user->id;
        $db = $this->getDBO();
        if ($user_id) {
            $query = "select user_id,user_image,username,first_name,last_name from #__pin_user_settings where user_id IN ($user_id ,$pin_user_id) ";
        } else {
            $query = "select user_id,user_image,username,first_name,last_name from #__pin_user_settings where user_id =$pin_user_id ";
        }

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

        return $user_result;
    }

    function displayBoard() {
        $db = $this->getDBO();
        $user = JFactory::getUser();
        $users = JRequest::getInt('uid');

        if (isset($users) && $users != '0') {
            $userId = $users;
        } else {
            $userId = $user->get('id');
        }

        $pageno = 0;
        $length = 20;
        $pins = array();
        if (JRequest::getVar('page')) {
            $pageno = JRequest::getVar('page');
            $pageno = $pageno * 20;
        }
        $colorwhere = '';
        if (JRequest::getVar('color')) {
            $color = JRequest::getVar('color');


            $colorwhere = " AND rgbcolor IN ($color) ";
        }
        //select the user boards and contributer boards
        $query = "SELECT user_id,board_id,board_name,cuser_id
                  FROM #__pin_boards
                  WHERE status=1
                  AND (user_id=" . $userId . " OR cuser_id LIKE '%$userId%') $colorwhere
                  LIMIT $pageno,$length";

        $db->setQuery($query);
        $boardDisplay = $db->loadObjectList();
        return $boardDisplay;
    }

    static function followUser($user, $fuser) {
        //select the boards from the logged user
        $db = JFactory::getDBO();
        $query = "SELECT board_id
                  FROM #__pin_boards
                  WHERE user_id='$fuser'";
        $db->setQuery($query);
        $results = $db->loadColumn();

        if (isset($results)) {
            $boardId = implode(',', $results);
        } else {
            $boardId = $results;
        }
        //select the followed boards from the user
        $inc = 0;

        $query = "SELECT follow_user_board
                  FROM #__pin_follow_users
                  WHERE status=1
                  AND user_id='$user'
                  AND follow_user_id='$fuser'";

        $db->setQuery($query);
        $followBoard = $db->loadResult();

        //explode the followed boards into arrays for boards selected invidually
        $boards = explode(",", $followBoard);
//if same return flag all
        if ($boardId == $followBoard) {
            $result = 'all';
        } else {
//return the selected boards alone
            $result = $boards;
        }

        return $result;
    }

}