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

	@version		1.0.77
	@build			6th April, 2022
	@created		22nd July, 2020
	@package		Moojla
	@subpackage		courselist.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 Model for Courselist
 */
class MoojlaModelCourselist extends JModelList
{
	/**
	 * Model user data.
	 *
	 * @var        strings
	 */
	protected $user;
	protected $userId;
	protected $guest;
	protected $groups;
	protected $levels;
	protected $app;
	protected $input;
	protected $uikitComp;

	/**
	 * Method to build an SQL query to load the list data.
	 *
	 * @return      string  An SQL query
	 */
	protected function getListQuery()
	{
		// Get the current user for authorisation checks
		$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->app = JFactory::getApplication();
		$this->input = $this->app->input;
		$this->initSet = 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.published','a.created_by','a.modified_by','a.created','a.modified','a.version','a.hits','a.ordering'),
			array('id','asset_id','cat_id','cat_name','currency','self_enrolment','startdate','summary_files','teachers','cost','remoteid','guest','in_enrol_date','enddate','summary','shortname','fullname','permanent_fields','published','created_by','modified_by','created','modified','version','hits','ordering')));
		$query->from($db->quoteName('#__moojla_course', 'a'));
		// Get where a.published is 1
		$query->where('a.published = 1');

		// return the query object
		return $query;
	}

	/**
	 * Method to get an array of data items.
	 *
	 * @return  mixed  An array of data items on success, false on failure.
	 */
	public function getItems()
	{
		$user = JFactory::getUser();
		// load parent items
		$items = parent::getItems();

		// Get the global params
		$globalParams = JComponentHelper::getParams('com_moojla', true);

		// 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.courselist.teachers', &$_teachers, &$params, 0));
				// Make sure the content prepare plugins fire on summary_files
				$_summary_files = new stdClass();
				$_summary_files->text =& $item->summary_files; // value must be in text
				// Since all values are now in text (Joomla Limitation), we also add the field name (summary_files) to context
				$this->_dispatcher->trigger("onContentPrepare", array('com_moojla.courselist.summary_files', &$_summary_files, &$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.courselist.summary', &$_summary, &$params, 0));
			}
		}


/***[JCBGUI.dynamic_get.php_after_getitems.56.$$$$]***/
		$mycourses = $this->state->get('parameters.menu')->get('mycourses');
		$moodle_course_category = $this->state->get('parameters.menu')->get('moodle_course_category');
		if($mycourses)
        {
          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_user_courses",
            "moodlewsrestformat"	=> "json",
            "userid"				=> MoojlaHelper::joomlaToMoodleID($user->id)
          );
          $coursesReq = MoojlaHelper::sendRequestToMoodle($dataObj);
          $courses = json_decode($coursesReq->response);
          $ids = array();
          if(is_array($courses))
          {
			foreach($courses as $course)
            {
              $ids[] = (int)($course->id);
            }
          }
          foreach($items as $index => $item)
          {
            if(!in_array((int)$item->remoteid, $ids))
              unset($items[$index]);
          }
        }
        else if($moodle_course_category)
        {
          foreach($items as $index => $item)
          {
            if((int)$item->cat_id != $moodle_course_category)
              unset($items[$index]);
          }
        }/***[/JCBGUI$$$$]***/


		// return items
		return $items;
	}
}
