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

	@version		1.0.77
	@build			6th April, 2022
	@created		22nd July, 2020
	@package		Moojla
	@subpackage		course_search.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 Course_search
 */
class MoojlaModelCourse_search 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; 
		// Make sure all records load, since no pagination allowed.
		$this->setState('list.limit', 0);
		// Get a db connection.
		$db = JFactory::getDbo();

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

		// Get data

/***[JCBGUI.dynamic_get.php_custom_get.59.$$$$]***/
$query->select('*, max(cost) as maxCost')
            ->from($db->quoteName('#__moojla_course','mc'));
           /***[/JCBGUI$$$$]***/


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


/***[JCBGUI.dynamic_get.php_after_getitems.59.$$$$]***/
$this->preFilter();
$items['tag']= isset($this->items['tag'])? $this->items['tag']: [];
$items['category']= isset($this->items['category'])? $this->items['category']: [];
$items['teacher']= isset($this->items['teacher'])? $this->items['teacher']: [];
$items['widget']= isset($this->items['widget'])? $this->items['widget']: [];
$items['courses']= $this->getCourses();
$items['showmycourse']= $this->items['showmycourse'];
$items['showsearchsidebar']= $this->items['showsearchsidebar'];
$items['searchinmycourse']= $this->items['searchinmycourse'];
$items['cs_display_cost']= $this->items['cs_display_cost'];
$items['jform']= $this->items['jform'];
/***[/JCBGUI$$$$]***/


		// return items
		return $items;
	}


/***[JCBGUI.site_view.php_model.41.$$$$]***/
public function get_courses_by_remoteid($remoteids=[])
{
  if (empty($remoteids))
    return [];

  $db = JFactory::getDbo();
  $query = $db->getQuery(true);

  $query->select('mc.id as id, shortname, remoteid, cat_name, catid, cost, summary_files, summary, fullname, attribs');
  $query->from($db->quoteName('#__moojla_course', 'mc'));
  $query->where($db->quoteName('remoteid').'IN ('.implode(',',$remoteids).')');

  $db->setQuery($query);
  $result = $db->loadObjectList('remoteid');
  return $result;

}
public function getTag($remoteid= null)
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true)
            ->select('tagname, tagid')
            ->from($db->quoteName('#__moojla_tag', 'mt'))
            ->where($db->quoteName('isstandard') . '= 1')
            ->group('tagid');
  
  		if ($remoteid)
        {
            $query->join('inner',$db->quoteName('#__moojla_tag_instance', 'mti').' on '.$db->quoteName('mt.tagid').'='.$db->quoteName('mti.moodletag'));
            $query->where($db->quoteName('mti.moojlacourse').'= '. $remoteid);

        }
  

        $db->setQuery($query);
        $result = $db->loadObjectList('tagid');
        return $result;
    }

      public function getCategory($remoteid= null)
    {

        $db = JFactory::getDbo();
        $query = $db->getQuery(true)
            ->select('*')
            ->from($db->quoteName('#__moojla_course', 'mc'))
            ->join('inner', $db->quoteName('#__categories', 'c') . 'on' . $db->quoteName('mc.catid') . '=' . $db->quoteName('c.id'));

        if ($remoteid)
        {
            $query->where($db->quoteName('mc.remoteid').'= '. $remoteid);
        }

        $db->setQuery($query);
        $result = $db->loadObjectList('catid');
        return $result;

    }

    public function getTeacher()
    {
        $params = JFactory::getApplication()->getParams('com_moojla');
        $role = $params->get('role');
        $db = JFactory::getDbo();
        $query = $db->getQuery(true)
            ->select('mid, name, role')
            ->from($db->quoteName('#__moojla_enrolment', 'e'))
            ->join('inner', $db->quoteName('#__moojla_user_map', 'um') . 'on ' . $db->quoteName('e.jid') . '=' . $db->quoteName('um.jid'))
            ->join('inner', $db->quoteName('#__users', 'u') . 'on ' . $db->quoteName('u.id') . '=' . $db->quoteName('e.jid'))
            ->where($db->quoteName('role') . '=' . $db->quote($role))
            ->group($db->quoteName('mid'));

        $db->setQuery($query);
        $result = $db->loadObjectList('mid');
        return $result;
    }

    public function getCourses()
    {
        $app= JFactory::getApplication();
        $menuid= $app->getMenu()->getActive()->get('id');
        $jform= array(
            'tag' => (array)$app->input->get('tag'),
            'category' => (array)$app->input->get('category'),
            'mid' => (array)$app->input->get('muser')
        );
        $this->items['jform']= $jform;
        return $this->Filter($jform, $menuid);
    }

    public function preFilter()
    {
        $app = JFactory::getApplication();
        $menuitem = $app->getMenu()->getActive();
        $params = $menuitem->getParams();

        $widgets = (array)$params->get('widget');
        $this->items['widget'] = $widgets;
        foreach ((array)$widgets as $widget) {
            if (in_array($widget, ['category', 'tag', 'teacher'])) {
                $widget_action = $params->get($widget . '_widget');
                $widget_ids = $params->get($widget);

                $widget_ids = $widget_ids ? $widget_ids : [0];
                $function = 'get' . $widget;
                switch ($widget_action) {
                    case 'all':
                        $result = $this->$function();
                        $this->items[$widget] = $result;
                        break;
                    case 'include':
                        $function2 = 'action_' . $widget_action;
                        $result = $this->$function();
                        $result = array_intersect_key($result, array_flip($widget_ids));
                        $this->items[$widget] = $result;
                        break;
                    case 'exclude':
                        $function2 = 'action_' . $widget_action;
                        $result = $this->$function();
                        $result = array_diff_key($result, array_flip($widget_ids));
                        $this->items[$widget] = $result;
                        break;
                }
            }
        }
    }

 public function doExclude(&$query, $table, $column, $keys)
    {
   		 $column= $table.'.'.$column;
         $query->where('('.$column.' NOT IN ('.implode(',',$keys).') or '.$column.' is null )');
    }
 public function doInclude(&$query, $table, $column, $keys)
    {
         $column= $table.'.'.$column;
         $query->where('('.$column.' IN ('.implode(',',$keys).') or '.$column.' is null )');
    }

public function Filter($jform=[], $menuid= null,$page= 1)
    {
  
        $app= JFactory::getApplication();
        $db= JFactory::getDbo();
        $query= $db->getQuery(true);
       
  
  if (!empty($menuid))
        {
            $menuparams= $app->getMenu()->getItem($menuid)->getParams();

            $this->items['showmycourse']= $menuparams->get('showmycourse',0);
            $this->items['showsearchsidebar']= $menuparams->get('showsearchsidebar',1);
            $this->items['searchinmycourse']= $menuparams->get('searchinmycourse', 1);
    		$this->items['cs_display_cost']= $menuparams->get('cs_display_cost', 1);


            $widgets= (array)$menuparams->get('widget');
            $filtered_widgets= [
                'category' => array('table'=> 'mc', 'column'=> 'catid'),
                'tag' => array('table'=> 'mti', 'column'=> 'moodletag'),
                'teacher' => array('table'=> 'um', 'column'=> 'mid')
            ];


            $flag= true;
            if($this->items['showmycourse'] || !empty($jform['searchinmycourse']))
            {
                $userid= JFactory::getUser()->id;
                if ($userid)
                {
                    $query2= $db->getQuery(true)
                        ->select('mid')
                        ->from($db->quoteName('#__moojla_user_map','um'))
                        ->where($db->quoteName('um.jid').'='.$db->quote($userid));

                    $db->setQuery($query2);
                    $mid= $db->loadResult();

                    $query->join('left',$db->quoteName('#__moojla_enrolment','es').'on'.$db->quoteName('mc.remoteid').'='.$db->quoteName('es.moojlacourse'));
                    $query->join('left',$db->quoteName('#__moojla_user_map','ums').'on'.$db->quoteName('es.jid').'='.$db->quoteName('ums.jid'));
                    //$query->where($db->quoteName('es.role').'= 5');
                    $query->where($db->quoteName('ums.mid').'='.$db->quote($mid));

                }
                else
                {
                    $flag= false;
                }
            }

            if (!$flag)
                return [];

            foreach ($filtered_widgets as $key=> $filtered_widget)
            {
                $widget_action= $key . '_widget';
                $widget_action = $menuparams->get($widget_action);
                $widget_ids = $menuparams->get($key);

                $widget_ids = $widget_ids ? $widget_ids : [0];
                if (in_array($key, $widgets))
                {
                    switch ($widget_action) {
                        case 'all':
                            break;
                        case 'include':
                            $this->doInclude($query,$filtered_widget['table'],$filtered_widget['column'],$widget_ids);
                            break;
                        case 'exclude':
                            $this->doExclude($query,$filtered_widget['table'],$filtered_widget['column'],$widget_ids);
                            break;
                    }
                }

            }

            $result_of_results= $menuparams->get('number_of_results',12);
            $limit= $result_of_results;
        }
  

        
            $query->select('mc.id as id, shortname, remoteid, cat_name, catid, cost, summary_files, summary, fullname, attribs')
            ->from($db->quoteName('#__moojla_course','mc'))
            ->join('left',$db->quoteName('#__moojla_tag_instance','mti').'on'.$db->quoteName('mc.remoteid').'='.$db->quoteName('mti.moojlacourse'))
            ->join('left',$db->quoteName('#__moojla_tag','mt').'on'.$db->quoteName('mti.moodletag').'='.$db->quoteName('mt.tagid'))
            ->join('left',$db->quoteName('#__moojla_enrolment','e').'on'.$db->quoteName('mc.remoteid').'='.$db->quoteName('e.moojlacourse'))
            ->join('left',$db->quoteName('#__moojla_user_map','um').'on'.$db->quoteName('e.jid').'='.$db->quoteName('um.jid'))
            ->join('left',$db->quoteName('#__users','u').'on'.$db->quoteName('e.jid').'='.$db->quoteName('u.id'))
            ->join('left',$db->quoteName('#__categories','c').'on'.$db->quoteName('mc.catid').'='.$db->quoteName('c.id'));




        if (!empty($jform['text']))
        {
            $like= $db->quote('%'.str_replace(' ','%',trim($jform['text'])).'%');
            $query->where('('.$db->quoteName('mc.shortname').' like '.$like.' OR '. $db->quoteName('mc.fullname').' like '.$like.')');
        }
        if (!empty($jform['category']))
        {
            $query->where($db->quoteName('mc.catid').' IN ('.implode(',',$jform['category']).')');
        }
        if (!empty($jform['tag']))
        {
            $query->where($db->quoteName('mti.moodletag').' IN ('.implode(',',$jform['tag']).')');
        }
        if (!empty($jform['mid']))
        {
            $query->where($db->quoteName('um.mid').' IN ('.implode(',',$jform['mid']).')');
            $query->where($db->quoteName('e.role').'= 3');
        }
        if (!empty($jform['minRange']))
        {
            $query->where($db->quoteName('mc.cost').' >= '. $db->quote($jform['minRange']));
            $query->where($db->quoteName('mc.cost').' <= '. $db->quote($jform['maxRange']));
        }


        $query->where($db->quoteName('mc.published').'=1');
  
   		if (empty($jform['sort']))
            $jform['sort']= 'remoteid__desc';

        list($sort_by, $order)= explode('__',$jform['sort']);
        $query->order('mc.'.$sort_by.' '.$order);
  
        $query->group('remoteid');
  
  
         if (isset($jform['limit']))
            $limit= $jform['limit'];
  
         if (!empty($limit))
       {
           $offset= ($page- 1) * $limit;
           $query->setLimit($limit, $offset);
       }
        


        $db->setQuery($query);
        $result= $db->loadObjectList('remoteid');

        return $result;
    }/***[/JCBGUI$$$$]***/

}
