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

	@version		1.0.77
	@build			6th April, 2022
	@created		22nd July, 2020
	@package		Moojla
	@subpackage		coursedetail.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 Coursedetail Model
 */
class MoojlaModelCoursedetail extends JModelItem
{
	/**
	 * Model context string.
	 *
	 * @var        string
	 */
	protected $_context = 'com_moojla.coursedetail';

	/**
	 * 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('coursedetail.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('coursedetail.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_course as a
				$query->select('a.*');
				$query->from($db->quoteName('#__moojla_course', 'a'));
				$query->where('a.remoteid = ' . (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;
				}
				// set remoteidCourseidSectionB to the $data object.
				$data->remoteidCourseidSectionB = $this->getRemoteidCourseidSectionAfee_B($data->remoteid);

				// 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.52.$$$$]***/
    $parameter = new JRegistry;
    $parameter->loadString($data->attribs, 'JSON');
    $attribs = $parameter;
    $template = $data->course_templatestyle_forcourseconfig;
    $layout = $data->course_detail_layout;
    $loginurl = $data->loginurl;
    $registrationurl = $data->registrationurl;
    $alterurl = $data->alterurl;

    $useglobalvideo = $data->useglobalvideo;
    $videotype = $data->videotype;
    $preventdownload = $data->preventdownload;
    $addcontrols = $data->addcontrols;
    $preloadvideo = $data->preloadvideo;
    $autoplay = $data->autoplay;
    $muted = $data->muted;

    $useglobalaudio = $data->useglobalaudio;
    $preventdownloadaudio = $data->preventdownloadaudio;
    $preloadaudio = $data->preloadaudio;
    $autoplayaudio = $data->autoplayaudio;

    $availabilityinfolink = $data->availabilityinfolink;
    $cangotomoodle = $data->cangotomoodle;
    $redirect_after_enrol = $data->redirect_after_enrol;
    $popupbutton = $data->popupbutton;
    $showlogintab = $data->showlogintab;
    $showregtab = $data->showregtab;

    $enterlbl = $data->enterlbl;
    $buylbl = $data->buylbl;
    $loginlbl = $data->loginlbl;
    $freeenterlbl = $data->freeenterlbl;
    $enrollbl = $data->enrollbl;

    $params = JComponentHelper::getParams('com_moojla');
    $course_detail_ws= trim($params->get('course_detail_ws'));
    $showenrolled= trim($params->get('showenrolled'));
    $data->enrolledusercount = -1;
    JLoader::register('MoojlaHelper', JPATH_ADMINISTRATOR.'/components/com_moojla/helpers/moojla.php');

    $moodleCourseId = $this->input->get('id', 0, 'integer');

    //  $id 	= $this->input->get('id', 0, 'integer');
    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    $query->select($db->quoteName(array('id')))
      ->from($db->quoteName('#__moojla_course'))
      ->where($db->quoteName('remoteid') . ' = ' . $db->quote($moodleCourseId));
    $db->setQuery($query);
    $id = $db->loadResult();


    //$moodleCourseId = $db->loadResult();
    $price = MoojlaHelper::getCurrentPriceByProductCode($moodleCourseId);

    if($course_detail_ws)
    {


      $dataObj = array(
        "wsfunction"			=> "moojla_get_courses",
        "moodlewsrestformat"	=> "json",
        "options"				=> array(
          "ids"					=> array(
            0					=> $moodleCourseId
          )
        )
      );
      $course = current(json_decode(MoojlaHelper::sendRequestToMoodle($dataObj)->response));

      $data = new stdClass();
      $data->id				= $id;
      $data->enrolledusercount			= $showenrolled ? $course->enrolledusercount : -1;
      $data->cat_id			= $course->categoryid;
      $data->cat_name			= $course->categoryname;
      $data->cost				= $price;
      $data->currency			= $course->currency;
      $data->enddate			= $course->enddate;
      $data->fullname			= $course->fullname;
      $data->guest			= $course->guest;
      $data->in_enrol_date	= $course->in_enrol_date;
      $data->remoteid			= $course->id;
      $data->self_enrolment	= $course->self_enrolment;
      $data->shortname		= $course->shortname;
      $data->startdate		= $course->startdate;
      $data->summary			= $course->summary;
      $data->summary_files	= $course->imgurl;
      $data->teachers	=		$course->teachers;
      $data->format = $course->format;
      $data->templatestyle = $template;
      $data->layout = $layout;
      $data->loginurl = $loginurl;
      $data->registrationurl = $registrationurl;
      $data->$alterurl = $alterurl;

      $data->useglobalvideo = $useglobalvideo;
      $data->videotype = $videotype;
      $data->preventdownload  = $preventdownload;
      $data->addcontrols = $addcontrols;
      $data->preloadvideo  =$preloadvideo;
      $data->autoplay = $autoplay;
      $data->muted = $muted;

      $data->useglobalaudio = $useglobalaudio;
      $data->preventdownloadaudio = $preventdownloadaudio;
      $data->preloadaudio = $preloadaudio;
      $data->autoplayaudio = $autoplayaudio;

      $data->availabilityinfolink = $availabilityinfolink;
      $data->cangotomoodle = $cangotomoodle;
      $data->redirect_after_enrol = $redirect_after_enrol;
      $data->popupbutton = $popupbutton;
      $data->showlogintab = $showlogintab;
      $data->showregtab = $showregtab;

      $data->enterlbl = $enterlbl;
      $data->buylbl = $buylbl;
      $data->loginlbl = $loginlbl;
      $data->freeenterlbl = $freeenterlbl;
      $data->enrollbl = $enrollbl;

      $this->_item[$pk]		= $data;

      $dataObj = array(
        "wsfunction"          	=> "moojla_get_course_contents",
        "moodlewsrestformat"  	=> "json",
        "courseid"				=> $moodleCourseId
      );
      $user = JFactory::getUser();
      if (!$user->guest)
      {
        $db= JFactory::getDbo();
        $query= $db->getQuery(true)
          ->select($db->quoteName('mid'))
          ->from($db->quoteName('#__moojla_user_map'))
          ->where($db->quoteName('jid').'='.$db->quote($user->id));
        $db->setQuery($query);
        $mid= $db->loadResult();

        $dataObj['userid'] = $mid;
      }

      $sections = json_decode(MoojlaHelper::sendRequestToMoodle($dataObj)->response);
      foreach($sections as $ind => $section)
      {
        if($section->uservisible == true && $section->visible == 1)
        {
          MoojlaHelper::changeObjectKey($section, "id", "section_id");
          MoojlaHelper::changeObjectKey($section, "modules", "section_idModule_section_idModuleC");
          if(!property_exists($section, "description"))
            $section->description = "";
          if($section->section_idModule_section_idModuleC)
          {
            foreach($section->section_idModule_section_idModuleC as $module)
            {
              MoojlaHelper::changeObjectKey($module, "id", "module_id");
              MoojlaHelper::changeObjectKey($module, "contents", "module_idContents_module_idContentD");
              if(!property_exists($module, "description"))
                $module->description = "";
              if(!property_exists($module, "url"))
                $module->url = "";
              if($module->module_idContents_module_idContentD)
              {
                foreach($module->module_idContents_module_idContentD as $content)
                {
                  if(!property_exists($content, "file"))
                    $content->file = "";
                }
              }
            }
          }
        }
        else
        {
          unset($sections[$ind]);
        }

      }
      $this->_item[$pk]->remoteidCourseidSectionB = $sections;
    }
    $dataObj = array(
      "wsfunction"			=> "moojla_get_course_custom_fields_data",
      "moodlewsrestformat"	=> "json",
      "courseid"				=> $moodleCourseId
    );

    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    $query->select(array('a.*', 'b.name AS fieldName', 'b.title AS fieldTitle'));
    $query->from($db->quoteName('#__moojla_course_field_mapper', 'a'));
    $query->join('INNER', $db->quoteName('#__fields', 'b') . ' ON ' . $db->quoteName('a.coursefield') . ' = ' . $db->quoteName('b.id'));
    $query->where($db->quoteName('a.published') . ' = 1' );
    $query->where($db->quoteName('b.context') . ' = "com_moojla.course"' );
    $db->setQuery($query);
    $coursecustomfieldsmapp = $db->loadObjectList();
    $mapper = array();
    foreach($coursecustomfieldsmapp as $cm)
    {
      $mapper[substr($cm->mcoursefields, 3)] = array('name' => $cm->fieldName, 'title' => $cm->fieldTitle, 'img' => $cm->field_icon) ;
    }

    // $coursecustomfields = json_decode(MoojlaHelper::sendRequestToMoodle($dataObj)->response);

    // if(is_array($coursecustomfields))
    // {
    // foreach($coursecustomfields as $cc)
    // {
    // if(isset($mapper[$cc->shortname]))
    // {
    // $mapper[$cc->shortname]['value'] = $cc->value;
    // }
    // }
    // }

    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    $query
      ->select(array('fv.value', 'f.title', 'f.name', 'fm.field_icon as img'))
      ->from($db->quoteName('#__fields_values', 'fv'))
      ->join('INNER', $db->quoteName('#__fields', 'f') . ' ON ' . $db->quoteName('fv.field_id') . ' = ' . $db->quoteName('f.id'))
      ->join('INNER', $db->quoteName('#__moojla_course_field_mapper', 'fm') . ' ON ' . $db->quoteName('f.id') . ' = ' . $db->quoteName('fm.coursefield'))
      ->where($db->quoteName('fv.item_id') . ' = ' . $db->quote($id));
    $db->setQuery($query);

    $mapper = $db->loadAssocList();

    $this->_item[$pk]->fieldMapper = $mapper;
    $this->_item[$pk]->attribs= $attribs;
/***[/JCBGUI$$$$]***/


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

	/**
	 * Method to get an array of Section Objects.
	 *
	 * @return mixed  An array of Section Objects on success, false on failure.
	 *
	 */
	public function getRemoteidCourseidSectionAfee_B($remoteid)
	{
		// Get a db connection.
		$db = JFactory::getDbo();

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

		// Get from #__moojla_section as b
		$query->select($db->quoteName(
			array('b.id','b.courseid','b.section_id','b.name','b.visible','b.uservisible','b.summary','b.published','b.created_by','b.modified_by','b.created','b.modified','b.hits'),
			array('id','courseid','section_id','name','visible','uservisible','summary','published','created_by','modified_by','created','modified','hits')));
		$query->from($db->quoteName('#__moojla_section', 'b'));
		$query->where('b.courseid = ' . $db->quote($remoteid));

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

		// check if there was data returned
		if ($db->getNumRows())
		{
			// Load the JEvent Dispatcher
			JPluginHelper::importPlugin('content');
			$this->_dispatcher = JEventDispatcher::getInstance();
			$items = $db->loadObjectList();

			// Convert the parameter fields into objects.
			foreach ($items as $nr => &$item)
			{
				// 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 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.coursedetail.summary', &$_summary, &$params, 0));
				// set section_idModule_section_idModuleC to the $item object.
				$item->section_idModule_section_idModuleC = $this->getSection_idModule_section_idModuleAfee_C($item->section_id);
			}
			return $items;
		}
		return false;
	}

	/**
	 * Method to get an array of Module Objects.
	 *
	 * @return mixed  An array of Module Objects on success, false on failure.
	 *
	 */
	public function getSection_idModule_section_idModuleAfee_C($section_id)
	{
		// Get a db connection.
		$db = JFactory::getDbo();

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

		// Get from #__moojla_module as c
		$query->select($db->quoteName(
			array('c.id','c.module_section_id','c.module_id','c.visible','c.uservisible','c.name','c.modname','c.url','c.description','c.modicon','c.published','c.created_by','c.modified_by','c.created','c.modified','c.hits'),
			array('id','module_section_id','module_id','visible','uservisible','name','modname','url','description','modicon','published','created_by','modified_by','created','modified','hits')));
		$query->from($db->quoteName('#__moojla_module', 'c'));
		$query->where('c.module_section_id = ' . $db->quote($section_id));

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

		// check if there was data returned
		if ($db->getNumRows())
		{
			// Load the JEvent Dispatcher
			JPluginHelper::importPlugin('content');
			$this->_dispatcher = JEventDispatcher::getInstance();
			$items = $db->loadObjectList();

			// Convert the parameter fields into objects.
			foreach ($items as $nr => &$item)
			{
				// 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 modicon
				$_modicon = new stdClass();
				$_modicon->text =& $item->modicon; // value must be in text
				// Since all values are now in text (Joomla Limitation), we also add the field name (modicon) to context
				$this->_dispatcher->trigger("onContentPrepare", array('com_moojla.coursedetail.modicon', &$_modicon, &$params, 0));
				// Make sure the content prepare plugins fire on description
				$_description = new stdClass();
				$_description->text =& $item->description; // value must be in text
				// Since all values are now in text (Joomla Limitation), we also add the field name (description) to context
				$this->_dispatcher->trigger("onContentPrepare", array('com_moojla.coursedetail.description', &$_description, &$params, 0));
				// set module_idContents_module_idContentD to the $item object.
				$item->module_idContents_module_idContentD = $this->getModule_idContents_module_idContentAfee_D($item->module_id);
			}
			return $items;
		}
		return false;
	}

	/**
	 * Method to get an array of Content Objects.
	 *
	 * @return mixed  An array of Content Objects on success, false on failure.
	 *
	 */
	public function getModule_idContents_module_idContentAfee_D($module_id)
	{
		// Get a db connection.
		$db = JFactory::getDbo();

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

		// Get from #__moojla_content as d
		$query->select($db->quoteName(
			array('d.id','d.contents_module_id','d.fileurl','d.filesize','d.mimetype','d.type','d.filename','d.file','d.published','d.created_by','d.modified_by','d.created','d.modified','d.hits'),
			array('id','contents_module_id','fileurl','filesize','mimetype','type','filename','file','published','created_by','modified_by','created','modified','hits')));
		$query->from($db->quoteName('#__moojla_content', 'd'));
		$query->where('d.contents_module_id = ' . $db->quote($module_id));

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

		// check if there was data returned
		if ($db->getNumRows())
		{
			// Load the JEvent Dispatcher
			JPluginHelper::importPlugin('content');
			$this->_dispatcher = JEventDispatcher::getInstance();
			return $db->loadObjectList();
		}
		return false;
	}



/***[JCBGUI.site_view.php_model.38.$$$$]***/
  public function getFavorite()
  {
    $user= JFactory::getUser();
    if ($user->guest)
      return [];

    $userid= $user->id;
    $db= JFactory::getDbo();
    $query= $db->getQuery(true)
      ->select($db->quoteName('courseid'))
      ->from($db->quoteName('#__moojla_favorite','f'))
      ->where($db->quoteName('userid').'='.$db->quote($userid));


    $db->setQuery($query);
    $result= $db->loadObjectList('courseid');
    return $result;
  }
  public function getRate()
  {
    $user= JFactory::getUser();
    if ($user->guest)
      return ['rate' => null, 'average' => null];

    $userid= $user->id;
    $db= JFactory::getDbo();

    $query= $db->getQuery(true)
      // courseid==remoteid
      ->select('(sum(rate)/count(*)) as average, count(*) as totalRate, courseid')
      ->from($db->quoteName('#__moojla_rate'))
      ->group('courseid');


    $db->setQuery($query);
    $average= $db->loadObjectList('courseid');


    $query= $db->getQuery(true)
      ->select('courseid, rate')
      ->from($db->quoteName('#__moojla_rate'))
      ->where($db->quoteName('userid').'='.$db->quote($userid));


    $db->setQuery($query);
    $rate= $db->loadObjectList();
    return compact('rate','average');
  }

  public function updateHits($id = 0)
  {
    if ((int) $id <= 0)
      return;
    $app = JFactory::getApplication();
    $hits = $app->getUserState('com_moojla.hits', array());
    if (!in_array($id, $hits))
    {
      $db = $this->getDbo();
      $query = $db->getQuery(true)
        ->update($db->quoteName('#__moojla_course'))
        ->set($db->qn('hits') . ' = (' . $db->qn('hits') . ' + 1)')
        ->where($db->qn('id') . ' = ' . $db->q((int) $id));
      $db->setQuery($query)->execute();

      $hits[] = $id;

      $app->setUserState('com_moojla.hits', $hits);

      if ($this->state->get('params')->get('logging', 0))
      {
        $referer = $app->input->server->get('HTTP_REFERER', '', 'string');
        $userAgent = $app->input->server->get('HTTP_USER_AGENT', '', 'string');
        $address = $app->input->server->get('REMOTE_ADDR', '', 'string');
        $visited = JFactory::getDate()->toSql();

        JModelLegacy::getInstance('Log', 'MoojlaModel')->log(
          $id,
          $referer,
          $userAgent,
          $address,
          $visited
        );
      }
    }
  }
/***[/JCBGUI$$$$]***/

}
