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

	@version		1.0.77
	@build			6th April, 2022
	@created		22nd July, 2020
	@package		Moojla
	@subpackage		ajax.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 Ajax Model
 */
class MoojlaModelAjax extends JModelList
{
	protected $app_params;

	public function __construct()
	{
		parent::__construct();
		// get params
		$this->app_params = JComponentHelper::getParams('com_moojla');

	}

	// Used in course

/***[JCBGUI.admin_view.php_ajaxmethod.129.$$$$]***/
public function shop_requirement($shop_name)
{
    $shop_integration = $shop_name;
    $res= [];
    if ($shop_integration == 'hk') {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);

        $query->select('extension_id, enabled, name');
        $query->from($db->quoteName('#__extensions'));
        $query->where('(' . $db->quoteName('folder') . '=' . $db->quote('editors-xtd') . ' and ' . $db->quoteName('element') . '=' . $db->quote('hikashopproduct') . ') or (' . $db->quoteName('folder') . '=' . $db->quote('system') . ' and ' . $db->quoteName('element') . '=' . $db->quote('hikashopproductinsert') . ')');

        $db->setQuery($query);
        $results = $db->loadObjectList('name');

        $required_plugins = ['Hikashop product tag insertion plugin', 'HikaShop product tag translation plugin'];

        foreach ($required_plugins as $required_plugin) {

            if ($results[$required_plugin]) {
                if ($results[$required_plugin]->enabled == 1)
                    $res['messages'][]=['message'=> $results[$required_plugin]->name . ' is installed and enabled', 'class'=>'success'];
                else
                    $res['messages'][]=['message'=> $results[$required_plugin]->name . ' is installed but not enabled', 'class'=>'error'];
            } else
                $res['messages'][]=['message'=> $results[$required_plugin]->name . ' is not installed', 'class'=>'error'];
        }
        $res['component']= 'hikashop';
        return $res;
    }
  
}/***[/JCBGUI$$$$]***/


	// Used in coursedetail

/***[JCBGUI.site_view.php_ajaxmethod.38.$$$$]***/
  public function favorite($courseid)
  {
    $xml = new SimpleXMLElement('<field name="courseid" validate="exists" exists_table="#__moojla_course" exists_column="remoteid" />');
    $rule = JFormHelper::loadRuleType('exists');
    $validate = $rule->test($xml, $courseid);

    if (!$validate)
      return false;


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

    $db->setQuery($query);
    $result= $db->loadResult();

    if (!empty($result))
    {
      $action= -1;
      $query= $db->getQuery(true)
        ->delete($db->quoteName('#__moojla_favorite'))
        ->where($db->quoteName('userid').'='.$db->quote($userid))
        ->where($db->quoteName('courseid').'='.$db->quote($courseid));
      $db->setQuery($query);
      $result= $db->execute();
    }
    else
    {
      $action= 1;
      $obj= new stdClass();
      $obj->userid= $userid;
      $obj->courseid= $courseid;
      $result= $db->insertObject('#__moojla_favorite',$obj);
    }
    return $action;
  }

  public function rate($courseid, $rate)
  {
    $xml = new SimpleXMLElement('<field name="courseid" validate="exists" exists_table="#__moojla_course" exists_column="remoteid" />');
    $rule = JFormHelper::loadRuleType('exists');
    $validate = $rule->test($xml, $courseid);

    if (!$validate)
      return false;


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

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

    $db->setQuery($query);
    $result= $db->loadResult();

    if (empty($result))
    {
      $obj= new stdClass();
      $obj->userid= $userid;
      $obj->courseid= $courseid;
      $obj->rate= $rate;
      $db->insertObject('#__moojla_rate',$obj);
    }
    else
    {
      $query = $db->getQuery(true);
      $fields = array(
        $db->quoteName('rate') . ' = ' . $db->quote($rate),
      );
      $conditions = array(
        $db->quoteName('userid') . ' ='.$db->quote($userid),
        $db->quoteName('courseid') . ' ='.$db->quote($courseid)
      );
      $query->update($db->quoteName('#__moojla_rate'))->set($fields)->where($conditions);
      $db->setQuery($query);
      $db->execute();
    }

    return true;
  }

  public function viewActivity($userid, $moduleid)
  {
    JLoader::register('MoojlaHelper', JPATH_ADMINISTRATOR.'/components/com_moojla/helpers/moojla.php');
    $dataObj = array(
      "wsfunction"          =>  "moojla_view_module",
      "moodlewsrestformat"  =>  "json",
      "moduleid"            =>  $moduleid,
      "userid"              =>  $userid
    );

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

    return $result;
  }

  public function fixMyCourse($userid)
  {
    $thisuserid = JFactory::getUser()->id;
    JLoader::register('MoojlaHelper', JPATH_ADMINISTRATOR.'/components/com_moojla/helpers/moojla.php');
    $mid = MoojlaHelper::joomlaToMoodleID($thisuserid);
    $dataObj = array(
      "wsfunction"          =>  "moojla_get_user_courses",
      "moodlewsrestformat"  =>  "json",
      "userid"              =>  $mid
    );

    $results = json_decode(MoojlaHelper::sendRequestToMoodle($dataObj)->response);
    foreach($results as $res)
    {
      $courseid = $res->id;
      $role = $res->role;
      JPluginHelper::importPlugin("moojlaevents");
      $dispatcher = JEventDispatcher::getInstance();
      $dispatch_res1	= $dispatcher->trigger("addEnrolment", array($courseid, $mid, $role, time()));
      $dispatch_res2	= $dispatcher->trigger("addGroupMember", array($course_id, $mid, $role));
    }
    return $results;
  }
/***[/JCBGUI$$$$]***/


	// Used in course_search

/***[JCBGUI.site_view.php_ajaxmethod.41.$$$$]***/
public function Filter($jform, $menuid, $page= 1)
  {

    $app= JFactory::getApplication();

    require 'components/com_moojla/models/course_search.php';
    $model= new MoojlaModelCourse_search();
    $result= $model->Filter($jform, $menuid, $page);

  	if (empty($result))
        return ['content' => null];

    

    require_once 'components/com_moojla/views/course_search/view.html.php';
    $view = new moojlaViewCourse_search;
   
  require_once JPATH_SITE.'/components/com_moojla/models/coursedetail.php';
	$courseDetailModel= new MoojlaModelCoursedetail;
	
    $view->courses= $result;
	$view->params= JComponentHelper::getParams('com_moojla');
	$view->favorite= $courseDetailModel->getFavorite();
  
   \JPluginHelper::importPlugin('moojlacourse');
      $view->dispatcher = JEventDispatcher::getInstance();

      require_once JPATH_ADMINISTRATOR.'/components/com_moojla/models/course.php';
      $mmc= new MoojlaModelCourse;
      $view->table= $mmc->getTable();
  

       $menuTmpl= $app->getMenu()->getItem($menuid)->getParams()->get('course_search_tmpl');
      if (!$menuTmpl)
      {
          $tmpl= JComponentHelper::getParams('com_moojla')->get('course_search_tmpl');
          $tmpl= ($tmpl==  -1 || !$tmpl)? 'default_card':  preg_replace('/\.php$/','',$tmpl);
      }
      else
      {
          $tmpl= $menuTmpl;
          $tmpl=  preg_replace('/\.php$/','',$tmpl);
      }

    $view->setLayout($tmpl);
    $content= $view->loadTemplate();


    return ['content' => $content];


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

}
