<?php
/*----------------------------------------------------------------------------------|  www.vdm.io  |----/
				fdsh 
/-------------------------------------------------------------------------------------------------------/

	@version		1.0.39
	@build			4th April, 2023
	@created		17th December, 2020
	@package		Reservation
	@subpackage		messages.php
	@author			farhad shahbazi <http://farhad.com>	
	@copyright		Copyright (C) 2015. All Rights Reserved
	@license		GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html
  ____  _____  _____  __  __  __      __       ___  _____  __  __  ____  _____  _  _  ____  _  _  ____ 
 (_  _)(  _  )(  _  )(  \/  )(  )    /__\     / __)(  _  )(  \/  )(  _ \(  _  )( \( )( ___)( \( )(_  _)
.-_)(   )(_)(  )(_)(  )    (  )(__  /(__)\   ( (__  )(_)(  )    (  )___/ )(_)(  )  (  )__)  )  (   )(  
\____) (_____)(_____)(_/\/\_)(____)(__)(__)   \___)(_____)(_/\/\_)(__)  (_____)(_)\_)(____)(_)\_) (__) 

/------------------------------------------------------------------------------------------------------*/

// No direct access to this file
defined('_JEXEC') or die('Restricted access');

use Joomla\Utilities\ArrayHelper;

/**
 * Reservation Messages Model
 */
class ReservationModelMessages extends JModelItem
{
	/**
	 * Model context string.
	 *
	 * @var        string
	 */
	protected $_context = 'com_reservation.messages';

	/**
	 * Model user data.
	 *
	 * @var        strings
	 */
	protected $user;
	protected $userId;
	protected $guest;
	protected $groups;
	protected $levels;
	protected $app;
	protected $input;
	protected $uikitComp;

	/**
	 * @var object item
	 */
	protected $item;

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @since   1.6
	 *
	 * @return void
	 */
	protected function populateState()
	{
		$this->app = JFactory::getApplication();
		$this->input = $this->app->input;
		// Get the itme main id
		$id = $this->input->getInt('id', null);
		$this->setState('messages.id', $id);

		// Load the parameters.
		$params = $this->app->getParams();
		$this->setState('params', $params);
		parent::populateState();
	}

	/**
	 * Method to get article data.
	 *
	 * @param   integer  $pk  The id of the article.
	 *
	 * @return  mixed  Menu item data object on success, false on failure.
	 */
	public function getItem($pk = null)
	{
		$this->user = JFactory::getUser();
		$this->userId = $this->user->get('id');
		$this->guest = $this->user->get('guest');
		$this->groups = $this->user->get('groups');
		$this->authorisedGroups = $this->user->getAuthorisedGroups();
		$this->levels = $this->user->getAuthorisedViewLevels();
		$this->initSet = true;

		$pk = (!empty($pk)) ? $pk : (int) $this->getState('messages.id');

/***[JCBGUI.dynamic_get.php_before_getitem.40.$$$$]***/
 		$view= JFactory::getApplication()->input->get('view', 0);
		$uid= JFactory::getApplication()->input->get('uid', 0);
        $pid= JFactory::getApplication()->input->get('pid', 0);
        $userid= JFactory::getUser()->get('id', 0);
		$seid= JFactory::getApplication()->input->get('seid', 0);

// Trigger the beforeChat (chatterAuth) event.
        \JPluginHelper::importPlugin('chat');
        $dispatcher = \JEventDispatcher::getInstance();
        $dispatcher->trigger('beforeChat',array($uid, $pid, $userid, $seid));

/***[/JCBGUI$$$$]***/

		
		if ($this->_item === null)
		{
			$this->_item = array();
		}

		if (!isset($this->_item[$pk]))
		{
			try
			{
				// Get a db connection.
				$db = JFactory::getDbo();

				// Create a new query object.
				$query = $db->getQuery(true);

				// Get from #__reservation_consultant as a
				$query->select($db->quoteName(
			array('a.id','a.asset_id','a.nationalnumber','a.userid','a.experience','a.image','a.alt','a.msn','a.catid','a.capitalid','a.video','a.phonenumber','a.introduction'),
			array('id','asset_id','nationalnumber','userid','experience','image','alt','msn','catid','capital','video','phonenumber','introduction')));
				$query->from($db->quoteName('#__reservation_consultant', 'a'));

				// Get from #__users as u
				$query->select($db->quoteName(
			array('u.id','u.name'),
			array('users_id','users_name')));
				$query->join('RIGHT', ($db->quoteName('#__users', 'u')) . ' ON (' . $db->quoteName('a.userid') . ' = ' . $db->quoteName('u.id') . ')');

				// Get from #__reservation_sick as s
				$query->select($db->quoteName(
			array('s.id','s.asset_id','s.alt','s.capitalid','s.cardnumber','s.cityid','s.image','s.phonenumber','s.userid'),
			array('reservation_sick_id','reservation_sick_asset_id','reservation_sick_alt','reservation_sick_capitalid','reservation_sick_cardnumber','reservation_sick_cityid','reservation_sick_image','reservation_sick_phonenumber','reservation_sick_userid')));
				$query->join('LEFT', ($db->quoteName('#__reservation_sick', 's')) . ' ON (' . $db->quoteName('u.id') . ' = ' . $db->quoteName('s.userid') . ')');

				// Get from #__categories as c
				$query->select($db->quoteName(
			array('c.title'),
			array('categories_title')));
				$query->join('LEFT', ($db->quoteName('#__categories', 'c')) . ' ON (' . $db->quoteName('a.catid') . ' = ' . $db->quoteName('c.id') . ')');
				// Check if $uid is a string or numeric value.
				$checkValue = $uid;
				if (isset($checkValue) && ReservationHelper::checkString($checkValue))
				{
					$query->where('u.id = ' . $db->quote($checkValue));
				}
				elseif (is_numeric($checkValue))
				{
					$query->where('u.id = ' . $checkValue);
				}
				else
				{
					return false;
				}

				// Reset the query using our newly populated query object.
				$db->setQuery($query);
				// Load the results as a stdClass object.
				$data = $db->loadObject();

				if (empty($data))
				{
					$app = JFactory::getApplication();
					// If no data is found redirect to default page and show warning.
					$app->enqueueMessage(JText::_('COM_RESERVATION_NOT_FOUND_OR_ACCESS_DENIED'), 'warning');
					$app->redirect(JURI::root());
					return false;
				}
			// Load the JEvent Dispatcher
			JPluginHelper::importPlugin('content');
			$this->_dispatcher = JEventDispatcher::getInstance();
				// Check if item has params, or pass whole item.
				$params = (isset($data->params) && ReservationHelper::checkJson($data->params)) ? json_decode($data->params) : $data;
				// Make sure the content prepare plugins fire on introduction
				$_introduction = new stdClass();
				$_introduction->text =& $data->introduction; // value must be in text
				// Since all values are now in text (Joomla Limitation), we also add the field name (introduction) to context
				$this->_dispatcher->trigger("onContentPrepare", array('com_reservation.messages.introduction', &$_introduction, &$params, 0));

				// set data object to item.
				$this->_item[$pk] = $data;
			}
			catch (Exception $e)
			{
				if ($e->getCode() == 404)
				{
					// Need to go thru the error handler to allow Redirect to work.
					JError::raiseWarning(404, $e->getMessage());
				}
				else
				{
					$this->setError($e);
					$this->_item[$pk] = false;
				}
			}
		}

 //get plan
		 $this->_item[$pk]->plan= $this->getPlan($pid);

	 if($view=='messages')
     {
         // get session knowledge
         $this->_item[$pk]->session= $this->getSession($seid) ;


         // get messages
         $this->_item[$pk]->messages= $this->getMessage($seid, $uid, $userid);/***[/JCBGUI$$$$]***/

         //read messages
         // $this->readMessage($userid, $uid);
     }

		return $this->_item[$pk];
	}


/***[JCBGUI.site_view.php_model.26.$$$$]***/
    public function readMessage($userid, $uid)
    {
      $db= JFactory::getDbo();
      $query= $db->getQuery(true)
        ->update($db->quoteName('#__reservation_message'))
        ->set($db->quoteName('read'). '= 1' )
        ->where($db->quoteName('from'). '='. $db->quote($uid) )
        ->where($db->quoteName('to'). '='. $db->quote($userid) );

      $db->setQuery($query);
      $db->execute($query);
    }
    public function readSingleMessage($mid)
    {
      $db= JFactory::getDbo();
      $query= $db->getQuery(true)
        ->update($db->quoteName('#__reservation_message'))
        ->set($db->quoteName('read'). '= 1' )
        ->where($db->quoteName('id'). '='. $db->quote($mid) );

      $db->setQuery($query);
      $db->execute($query);
    }
    public function getMessage($seid, $uid, $userid)
    {
      $db = JFactory::getDbo();
      $query = $db->getQuery(true);

      $query->select($db->quoteName(array('message', 'created', 'from', 'to', 'id', 'read', 'reply')));
      $query->from($db->quoteName('#__reservation_message'));
      $query->where($db->quoteName('seid').'='.$seid);
      $query->where($db->quoteName('published').'=1');
      $query->where('(('.$db->quoteName('from').'='.$uid.' and '.$db->quoteName('to').'='.$userid. ') or ('.$db->quoteName('from').'='.$userid.' and '.$db->quoteName('to').'='.$uid. '))');

      $query->order('id ASC');

      $db->setQuery($query);
      return $db->loadObjectList('id');
    }

    public function getSession($seid)
    {
      $db = JFactory::getDbo();
      $query = $db->getQuery(true)
        ->select($db->quoteName(array('id','finish')))
        ->from($db->quoteName('#__reservation_session','se'))
        ->where($db->quoteName('se.id').'='.$seid);

      $db->setQuery($query);
      return $db->loadObject();
    }
    public function getPlan($pid)
    {
      $db = JFactory::getDbo();
      $query = $db->getQuery(true)
        ->select($db->quoteName('id'))
        ->from($db->quoteName('#__reservation_plan','p'))
        ->where($db->quoteName('p.id').'='.$pid);

      $db->setQuery($query);
      return $db->loadObject();
    }
    public function getPrivateChannelToken()
    {
      $seid= JFactory::getApplication()->input->get('seid');
      $db = JFactory::getDbo();
      $query = $db->getQuery(true)
        ->select($db->quoteName('channel_token'))
        ->from($db->quoteName('#__reservation_session','s'))
        ->where($db->quoteName('s.id').'='.$seid);

      $db->setQuery($query);

      return $db->loadResult();
    }

/***[/JCBGUI$$$$]***/

}
