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

	@version		1.0.39
	@build			4th April, 2023
	@created		17th December, 2020
	@package		Reservation
	@subpackage		consultant_plan.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 Consultant_plan Model
 */
class ReservationModelConsultant_plan extends JModelItem
{
	/**
	 * Model context string.
	 *
	 * @var        string
	 */
	protected $_context = 'com_reservation.consultant_plan';

	/**
	 * 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('consultant_plan.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('consultant_plan.id');
		
		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.userid','a.nationalnumber','a.phonenumber','a.officephone','a.capitalid','a.cityid','a.account','a.introduction','a.msn','a.catid','a.experience','a.image','a.alt','a.video','a.presence','a.address','a.published','a.created_by','a.modified_by','a.created','a.modified','a.version','a.hits','a.ordering'),
			array('coid','asset_id','userid','nationalnumber','phonenumber','officephone','capitalid','cityid','account','introduction','msn','catid','experience','image','alt','video','presence','address','published','created_by','modified_by','created','modified','version','hits','ordering')));
				$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('INNER', ($db->quoteName('#__users', 'u')) . ' ON (' . $db->quoteName('a.userid') . ' = ' . $db->quoteName('u.id') . ')');
				// Get where a.userid is $this->userId
				$query->where('a.userid = ' . $db->quote($this->userId));

				// 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 address
				$_address = new stdClass();
				$_address->text =& $data->address; // value must be in text
				// Since all values are now in text (Joomla Limitation), we also add the field name (address) to context
				$this->_dispatcher->trigger("onContentPrepare", array('com_reservation.consultant_plan.address', &$_address, &$params, 0));
				// Make sure the content prepare plugins fire on presence
				$_presence = new stdClass();
				$_presence->text =& $data->presence; // value must be in text
				// Since all values are now in text (Joomla Limitation), we also add the field name (presence) to context
				$this->_dispatcher->trigger("onContentPrepare", array('com_reservation.consultant_plan.presence', &$_presence, &$params, 0));
				// 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.consultant_plan.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;
				}
			}
		}

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

	/**
	 * Custom Method
	 *
	 * @return mixed  An array of objects on success, false on failure.
	 *
	 */
	public function getUserPlans()
	{

		if (!isset($this->initSet) || !$this->initSet)
		{
			$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;
		}

		// Get the global params
		$globalParams = JComponentHelper::getParams('com_reservation', true);
		// Get a db connection.
		$db = JFactory::getDbo();

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

		// Get from #__reservation_plan as a
		$query->select($db->quoteName(
			array('a.id','a.asset_id','a.plantype','a.consultantid','a.price','a.time','a.waitingtime','a.published'),
			array('id','asset_id','plantype','consultantid','price','time','waitingtime','published')));
		$query->from($db->quoteName('#__reservation_plan', 'a'));

		// Get from #__reservation_consultant as b
		$query->select($db->quoteName(
			array('b.id','b.asset_id','b.userid'),
			array('consultant_id','consultant_asset_id','consultant_userid')));
		$query->join('INNER', ($db->quoteName('#__reservation_consultant', 'b')) . ' ON (' . $db->quoteName('a.consultantid') . ' = ' . $db->quoteName('b.id') . ')');
		// Get where b.userid is $this->userId
		$query->where('b.userid = ' . $db->quote($this->userId));

		// Reset the query using our newly populated query object.
		$db->setQuery($query);
		$items = $db->loadObjectList();

		if (empty($items))
		{
			return false;
		}

		// Insure all item fields are adapted where needed.
		if (ReservationHelper::checkArray($items))
		{
			foreach ($items as $nr => &$item)
			{
				// Always create a slug for sef URL's
				$item->slug = (isset($item->alias) && isset($item->id)) ? $item->id.':'.$item->alias : $item->id;
			}
		}
		// return items
		return $items;
	}
}
