<?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 Controller
 */
class MoojlaControllerCoursedetail extends JControllerForm
{
	/**
	 * Current or most recently performed task.
	 *
	 * @var    string
	 * @since  12.2
	 * @note   Replaces _task.
	 */
	protected $task;

	public function __construct($config = array())
	{
		$this->view_list = 'courses'; // safeguard for setting the return view listing to the default site view.
		parent::__construct($config);
	}


/***[JCBGUI.site_view.php_controller.38.$$$$]***/
  public function enrol()
  {
    JLoader::register('MoojlaHelper', JPATH_ADMINISTRATOR.'/components/com_moojla/helpers/moojla.php');
    $mainframe = JFactory::getApplication();
    $user = JFactory::getUser();

    $itemid = (int) $this->input->get('itemid');// joomla course id
    $type = $this->input->get('type', '');// enrolment type
    $params = JComponentHelper::getParams('com_moojla');

    $course_detail_ws= trim($params->get('course_detail_ws'));
    if(!$course_detail_ws)
    {
      $db = JFactory::getDbo();
      $query = $db->getQuery(true);
      $query->select($db->quoteName(array('remoteid', 'self_enrolment')))
        ->from($db->quoteName('#__moojla_course'))
        ->where($db->quoteName('id') . ' = ' . $db->quote($itemid));
      $db->setQuery($query);
      $moodleCourse = $db->loadAssocList();
      // dump($moodleCourse, "moodleCourse");
    }
    else
    {
      $db = JFactory::getDbo();
      $query = $db->getQuery(true);
      $query->select($db->quoteName(array('remoteid')))
        ->from($db->quoteName('#__moojla_course'))
        ->where($db->quoteName('id') . ' = ' . $db->quote($itemid));
      $db->setQuery($query);
      $moodleCourseId = $db->loadResult();

      JLoader::register('MoojlaHelper', JPATH_ADMINISTRATOR.'/components/com_moojla/helpers/moojla.php');
      $dataObj = array(
        "wsfunction"			=> "moojla_get_courses",
        "moodlewsrestformat"	=> "json",
        "options"				=> array(
          "ids"					=> array(
            0					=> $moodleCourseId
          )
        )
      );
      $course = current(json_decode(MoojlaHelper::sendRequestToMoodle($dataObj)->response));
      // dump($course, "course");
      $moodleCourse = array(["self_enrolment" => $course->self_enrolment, "remoteid" => $moodleCourseId]);
    }

    if($moodleCourse)
    {
      if(current($moodleCourse)["self_enrolment"])
      {
        $moodleCourseId = current($moodleCourse)["remoteid"];
        $return = 'index.php?option=com_moojla&view=coursedetail&id='.$moodleCourseId;
        $loginUrl =JRoute::_(moojlaHelper::getLoginUrl($return));

        if (!$user->id)
          $mainframe->redirect($loginUrl);

        $user = JFactory::getUser();
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select($db->quoteName(array('mid')))
          ->from($db->quoteName('#__moojla_user_map'))
          ->where($db->quoteName('jid') . ' = ' . $db->quote($user->id));
        $db->setQuery($query);
        $moodleUserId = $db->loadResult();
        if($moodleUserId)
        {
          $dataObj = array(
            "wsfunction"			=> "moojla_enrol_user",
            "moodlewsrestformat"	=> "json",
            "enrolments"			=> array(
              array(
                "roleid"			=> 5, // for student
                "userid"			=> $moodleUserId,
                "courseid"			=> $moodleCourseId
              )
            )
          );
          if($type == 'self')
          {
            $dataObj["enrolments"][0]["type"] = $type;
          }
          $enrolreq = json_decode(MoojlaHelper::sendRequestToMoodle($dataObj)->response, true); // enrol
          $params = JComponentHelper::getParams('com_moojla');
          $moodle_url= trim($params->get('moodle_url'));
          $moodleCourseUrl = $moodle_url."course/view.php?id=".$moodleCourseId;
          
          $db = JFactory::getDbo();
          $query = $db->getQuery(true);
          $query->select('*')
            ->from($db->quoteName('#__moojla_course'))
            ->where($db->quoteName('id') . ' = ' . $db->quote($itemid));
          $db->setQuery($query);
          $coursedb = $db->loadAssoc();

          if($coursedb['redirect_after_enrol'] == 2)
            $force_redirect = $params->get('redirect_after_enrol', 0);
          else
            $force_redirect = $coursedb['redirect_after_enrol'];

          if(isset($enrolreq["exception"]))
          {
            $message = $enrolreq["message"];
            $mainframe->enqueueMessage($message, 'error');
            $mainframe->redirect(JRoute::_($return, false));
          }

          $uri = JUri::getInstance(); 
          // $returnurl = $returnurl;
          // Save failed, go back to the screen and display a notice.
          if($force_redirect == 1)
          {
            $mainframe->redirect($moodleCourseUrl);
          }
          else
          {
            $mainframe->redirect(JRoute::_($return, false));
          }
        }
        else
        {
          $message = JText::_('MOOJLA_MOODLE_USER_NOT_FOUND_IN_MAPPING_FOR_ENROL'); // translate_need
          $mainframe->enqueueMessage($message, 'error');
          $mainframe->redirect('/');
        }
      }
      else
      {
        $message = JText::_('MOOJLA_SELF_ENROL_NOT_PERMITTED'); // translate_need
        $mainframe->enqueueMessage($message, 'error');
        $mainframe->redirect('/');
      }
    }
  }


  public function getPageContent(){
    $courseid = (int) $this->input->get('courseid');// moodle course id
    $pageid = (int) $this->input->get('pageid');// page id
    JLoader::register('MoojlaHelper', JPATH_ADMINISTRATOR.'/components/com_moojla/helpers/moojla.php');
    $dataObj = array(
      "wsfunction"			=> "moojla_get_pages_by_courses",
      "moodlewsrestformat"	=> "json",
      "courseid"				=> $courseid,
      "pageid"				=> $pageid,
    );
    $page = current(json_decode(MoojlaHelper::sendRequestToMoodle($dataObj)->response)->page);
    echo str_replace('/webservice/', '/', $page->content);
    die();
  }/***[/JCBGUI$$$$]***/


	/**
	 * Method to check if you can edit an existing record.
	 *
	 * Extended classes can override this if necessary.
	 *
	 * @param   array   $data  An array of input data.
	 * @param   string  $key   The name of the key for the primary key; default is id.
	 *
	 * @return  boolean
	 *
	 * @since   12.2
	 */
	protected function allowEdit($data = array(), $key = 'id')
	{
		// to insure no other tampering
		return false;
	}

        /**
	 * Method override to check if you can add a new record.
	 *
	 * @param   array  $data  An array of input data.
	 *
	 * @return  boolean
	 *
	 * @since   1.6
	 */
	protected function allowAdd($data = array())
	{
		// to insure no other tampering
		return false;
	}

	/**
	 * Method to check if you can save a new or existing record.
	 *
	 * Extended classes can override this if necessary.
	 *
	 * @param   array   $data  An array of input data.
	 * @param   string  $key   The name of the key for the primary key.
	 *
	 * @return  boolean
	 *
	 * @since   12.2
	 */
	protected function allowSave($data, $key = 'id')
	{
		// to insure no other tampering
		return false;
	}

	/**
	 * Function that allows child controller access to model data
	 * after the data has been saved.
	 *
	 * @param   JModelLegacy  $model      The data model object.
	 * @param   array         $validData  The validated data.
	 *
	 * @return  void
	 *
	 * @since   12.2
	 */
	protected function postSaveHook(JModelLegacy $model, $validData = array())
	{
	}
}
