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

	@version		1.0.77
	@build			6th April, 2022
	@created		22nd July, 2020
	@package		Moojla
	@subpackage		teacherdetail.php
	@author			Lmskaran <http://Lmskaran.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;

/**
 * Moojla Teacherdetail Model
 */
class MoojlaModelTeacherdetail extends JModelItem
{
	/**
	 * Model context string.
	 *
	 * @var        string
	 */
	protected $_context = 'com_moojla.teacherdetail';

	/**
	 * 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('teacherdetail.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('teacherdetail.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 #__moojla_user_map as a
				$query->select($db->quoteName(
			array('a.id','a.asset_id','a.jid','a.userimage','a.mid','a.published','a.hits'),
			array('id','asset_id','jid','userimage','mid','published','hits')));
				$query->from($db->quoteName('#__moojla_user_map', 'a'));

				// Get from #__users as b
				$query->select($db->quoteName(
			array('b.id','b.name','b.username','b.email','b.password','b.block','b.registerDate','b.lastvisitDate','b.params'),
			array('users_id','users_name','users_username','users_email','users_password','users_block','users_registerDate','users_lastvisitDate','users_params')));
				$query->join('INNER', ($db->quoteName('#__users', 'b')) . ' ON (' . $db->quoteName('a.jid') . ' = ' . $db->quoteName('b.id') . ')');
				$query->where('a.mid = ' . (int) $pk);
				// Get where a.published is 1
				$query->where('a.published = 1');

				// 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_MOOJLA_NOT_FOUND_OR_ACCESS_DENIED'), 'warning');
					$app->redirect(JURI::root());
					return false;
				}
			// Load the JEvent Dispatcher
			JPluginHelper::importPlugin('content');
			$this->_dispatcher = JEventDispatcher::getInstance();

				// 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;
				}
			}
		}

/***[JCBGUI.dynamic_get.php_after_getitem.54.$$$$]***/
    $input = $this->app->input;
    $moodleid = $input->get('id', 0);

    $this->_item[$pk]->cv = "";

    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    $query->select($db->quoteName(array('muserfields', 'juserfields')));
    $query->from($db->quoteName('#__moojla_user_field_map'));
    $query->where($db->quoteName('iscv') . ' = 1 ');
    $query->where($db->quoteName('published') . ' = 1 ');
    $db->setQuery($query);
    $cv_field = $db->loadAssocList();

    if(is_array($cv_field))
      $cv_field = current($cv_field);
    if($cv_field)
    {
      $prefix = substr($cv_field['juserfields'], 0, 2);
      switch($prefix)
      {
        case 'sj':
          $thisuser = JFactory::getUser($data->jid);
          $field = substr($cv_field['juserfields'], 3);
          $cv = $thisuser->$field;
          break;
        case 'jf':
          $db = JFactory::getDbo();
          $query = $db->getQuery(true);
          $query
            ->select('fv.value')
            ->from($db->quoteName('#__fields', 'f'))
            ->join('INNER', $db->quoteName('#__fields_values', 'fv') . ' ON ' . $db->quoteName('f.id') . ' = ' . $db->quoteName('fv.field_id'))
            ->where($db->quoteName('fv.item_id') . ' = ' . $db->quote($data->jid));
          $db->setQuery($query);
          $cv = $db->loadResult();
          break;
        case 'cb':
          $field = substr($cv_field['juserfields'], 3);
          $db = JFactory::getDbo();
          $query = $db->getQuery(true);
          $query->select($db->quoteName($field));
          $query->from($db->quoteName('#__comprofiler'));
          $query->where($db->quoteName('user_id') . ' = ' . $db->quote($data->jid));
          $db->setQuery($query);
          $cv = $db->loadResult();
          break;
      }
      if(isset($cv))
        $this->_item[$pk]->cv = $cv;
    }
/***[/JCBGUI$$$$]***/


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

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

		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_moojla', true);
		// Get a db connection.
		$db = JFactory::getDbo();

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

		// Get from #__moojla_course as a
		$query->select($db->quoteName(
			array('a.id','a.asset_id','a.cat_id','a.cat_name','a.currency','a.self_enrolment','a.startdate','a.summary_files','a.teachers','a.cost','a.remoteid','a.guest','a.in_enrol_date','a.enddate','a.summary','a.shortname','a.fullname','a.permanent_fields','a.catid','a.course_templatestyle_forcourseconfig','a.course_detail_layout','a.loginurl','a.registrationurl','a.published','a.hits'),
			array('id','asset_id','cat_id','cat_name','currency','self_enrolment','startdate','imgurl','teachers','cost','remoteid','guest','in_enrol_date','enddate','summary','shortname','fullname','permanent_fields','catid','course_templatestyle_forcourseconfig','course_detail_layout','loginurl','registrationurl','published','hits')));
		$query->from($db->quoteName('#__moojla_course', 'a'));

		// Get from #__moojla_enrolment as b
		$query->select($db->quoteName(
			array('b.id','b.asset_id','b.moojlacourse','b.jid','b.role','b.published','b.hits'),
			array('enrolment_id','enrolment_asset_id','enrolment_moojlacourse','enrolment_jid','enrolment_role','enrolment_published','enrolment_hits')));
		$query->join('INNER', ($db->quoteName('#__moojla_enrolment', 'b')) . ' ON (' . $db->quoteName('a.remoteid') . ' = ' . $db->quoteName('b.moojlacourse') . ')');

		// Get from #__moojla_user_map as c
		$query->select($db->quoteName(
			array('c.id','c.asset_id','c.jid','c.userimage','c.mid','c.published','c.hits'),
			array('user_map_id','user_map_asset_id','user_map_jid','user_map_userimage','user_map_mid','user_map_published','user_map_hits')));
		$query->join('INNER', ($db->quoteName('#__moojla_user_map', 'c')) . ' ON (' . $db->quoteName('b.jid') . ' = ' . $db->quoteName('c.jid') . ')');
		// Get where a.published is 1
		$query->where('a.published = 1');
		// Get where b.published is 1
		$query->where('b.published = 1');
		// Get where b.role is 3
		$query->where('b.role = 3');
		// Get where c.mid is $this->input->get('id')
		$query->where('c.mid = ' . $db->quote($this->input->get('id')));

		// Reset the query using our newly populated query object.
		$db->setQuery($query);
		$items = $db->loadObjectList();
/***[JCBGUI.dynamic_get.php_after_getitems.58.$$$$]***/
    $result = new stdClass;
    $result->courses = $items;
    return $result;

/**************** with ws in older version of moojla
    $teacherid = (int) $this->input->get('id');
	$pk = $teacherid;
    require_once JPATH_ADMINISTRATOR . "/components/com_moojla/models/course.php";
    JLoader::register('MoojlaHelper', JPATH_ADMINISTRATOR.'/components/com_moojla/helpers/moojla.php');

    $user = JFactory::getUser();

    $dataObj = array(
      "wsfunction"          => "moojla_get_courses_of_teacher",
      "moodlewsrestformat"  => "json",
      "userid"				=> $teacherid
    );
    $coursesReq = MoojlaHelper::sendRequestToMoodle($dataObj);
    $courses = json_decode($coursesReq->response);
    $this->_item[$pk] = $courses;
    foreach($this->_item[$pk]->courses as $index => $course)
    {
      $db = JFactory::getDbo();
      $query = $db->getQuery(true);
      $query->select('*');
      $query->from($db->quoteName('#__moojla_course'));
      $query->where($db->quoteName('remoteid') . ' = ' . $db->quote($course->id));
      $db->setQuery($query);
      $c = $db->loadObjectList();
      if($c)
      {
        $c = $c[0];
        $this->_item[$pk]->courses[$index]->id = $c->id;
        $this->_item[$pk]->courses[$index]->enddate = $c->enddate;
        $this->_item[$pk]->courses[$index]->startdate = $c->startdate;
        $this->_item[$pk]->courses[$index]->fullname = $c->fullname;
        $this->_item[$pk]->courses[$index]->shortname = $c->shortname;
        $this->_item[$pk]->courses[$index]->imgurl = $c->summary_files;
        $this->_item[$pk]->courses[$index]->summary = $c->summary;
        $this->_item[$pk]->courses[$index]->visible = $c->published;
        $this->_item[$pk]->courses[$index]->url = JRoute::_('index.php?option=com_moojla&view=coursedetail&id='.$c->remoteid);
      }
    }
    return $this->_item[$pk];

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


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

		// Insure all item fields are adapted where needed.
		if (MoojlaHelper::checkArray($items))
		{
			// Load the JEvent Dispatcher
			JPluginHelper::importPlugin('content');
			$this->_dispatcher = JEventDispatcher::getInstance();
			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;
				// Check if we can decode permanent_fields
				if (MoojlaHelper::checkJson($item->permanent_fields))
				{
					// Decode permanent_fields
					$item->permanent_fields = json_decode($item->permanent_fields, true);
				}
				// Check if item has params, or pass whole item.
				$params = (isset($item->params) && MoojlaHelper::checkJson($item->params)) ? json_decode($item->params) : $item;
				// Make sure the content prepare plugins fire on teachers
				$_teachers = new stdClass();
				$_teachers->text =& $item->teachers; // value must be in text
				// Since all values are now in text (Joomla Limitation), we also add the field name (teachers) to context
				$this->_dispatcher->trigger("onContentPrepare", array('com_moojla.teacherdetail.teachers', &$_teachers, &$params, 0));
				// Make sure the content prepare plugins fire on imgurl
				$_imgurl = new stdClass();
				$_imgurl->text =& $item->imgurl; // value must be in text
				// Since all values are now in text (Joomla Limitation), we also add the field name (imgurl) to context
				$this->_dispatcher->trigger("onContentPrepare", array('com_moojla.teacherdetail.imgurl', &$_imgurl, &$params, 0));
				// Make sure the content prepare plugins fire on summary
				$_summary = new stdClass();
				$_summary->text =& $item->summary; // value must be in text
				// Since all values are now in text (Joomla Limitation), we also add the field name (summary) to context
				$this->_dispatcher->trigger("onContentPrepare", array('com_moojla.teacherdetail.summary', &$_summary, &$params, 0));
			}
		}
		// return items
		return $items;
	}
}
