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

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

        /**
	 * 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 item main id
		$id = $this->input->getInt('id', null);
		$this->setState('healthcheck.id', $id);

		// Load the parameters.
		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();
		// check if this user has permission to access item
		if (!$this->user->authorise('healthcheck.access', 'com_moojla'))
		{
			$app = JFactory::getApplication();
			$app->enqueueMessage(JText::_('Not authorised!'), 'error');
			// redirect away if not a correct to cPanel/default view
			$app->redirect('index.php?option=com_moojla');
			return false;
		}
		$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('healthcheck.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 data

/***[JCBGUI.dynamic_get.php_custom_get.57.$$$$]***/
        $plugins = new stdClass();
        $plugins->joomla = array();
        $plugins->thirdparties = array();
        $moojla_joomla_plugins_name = array( // translate need
          "moojlaaditionalfields_moojlaaditionnalfieldcb" => "Its important for syncing users with joomla fields",
          "moojlaaditionalfields_moojlaaditionnalfieldnative" => "Its important for syncing users with cb fields",
          "user_moojlasso_j2m" => "Its important for syncing users login status from joomla to moodle",
          "moojlaevents_moojlasso_m2j" => "Its important for syncing users login status from moodle to joomla",
          "user_moojlausersyncer_j2m" => "Its important for syncing users from joomla to moodle",
          "moojlaevents_moojlausersyncer_m2j" => "Its important for syncing users from moodle to joomla",
          "moojlaevents_moojlacoursesyncer_m2j" => "Its important for syncing course from moodle to joomla",
          "system_moojlahikashoporder" => "Its important enrolling users in hikashop products(courses)",
          "moojlaevents_moojlaenrolmentmethod" => "Its important for syncing course enrolment instances",
          "moojlashopintegration_moojlahikashopproduct_m2j" => "Its important for syncing course product in hikashop",
          "search_moojlasearchbycourse" => "Its important for search course by name",
          "search_moojlasearchbycategory" => "Its important for search course by category",
          "user_moojlaautologingwithredirect" => "for login user after creation",
          "moojlaevents_moojlacourse_events" => "for showing particles like kommento in moojla coursedetil view",
          "moojlaevents_moojlagroup_manager" => "Its important for creating groups after course creation",
          "user_moojlaenrolwithgroups_j2m" => "Its important for enrrol(unenrol) users with joinig(leaving) groups",
          "moojlaevents_moojlatagsyncer_m2j" => "for creating and syncing coursetags from moodle to joomla",
          "moojlaevents_moojlaenrolment_m2j" => "Its important for syncing moojla enroments",
        );
        foreach($moojla_joomla_plugins_name as $mjp => $importancy)
        {
          $plugins->joomla[$mjp] = new stdClass();
          $plugins->joomla[$mjp]->installed = false;
          $plugins->joomla[$mjp]->enabled = false;
          $plugins->joomla[$mjp]->importancy = $importancy;
        }


        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('*');
        $query->from($db->quoteName('#__extensions'));
        $query->where($db->quoteName('name') . ' IN ("plg_' . implode('","plg_', array_keys($moojla_joomla_plugins_name)) . '")');
        $db->setQuery($query);
        $extensions_res = $db->loadObjectList('name');

        foreach(array_keys($moojla_joomla_plugins_name) as $mjp)
        {
          if(isset($extensions_res['PLG_' . strtoupper($mjp)]))
          {
            $plugins->joomla[$mjp]->installed = true;
            $plugins->joomla[$mjp]->enabled = (($extensions_res['PLG_' . strtoupper($mjp)]->enabled) == 1);
          }
        }

        $moojla_cb_plugins_name = array( // translate need
          "moojlacbeventforwarder" => "Its important for syncing users with cb fields"
        );

        foreach($moojla_cb_plugins_name as $mcp => $importancy)
        {
          $plugins->thirdparties['cb'][$mcp] = new stdClass();
          $plugins->thirdparties['cb'][$mcp]->installed = false;
          $plugins->thirdparties['cb'][$mcp]->enabled = false;
          $plugins->thirdparties['cb'][$mcp]->importancy = $importancy;
        }

        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('*');
        $query->from($db->quoteName('#__comprofiler_plugin'));
        $query->where($db->quoteName('element') . ' IN ("' . implode('","', array_keys($moojla_cb_plugins_name)) . '")');
        $db->setQuery($query);
        try {
          $comprofiler_plugin = $db->loadObjectList('element');
          foreach(array_keys($moojla_cb_plugins_name) as $mcp)
          {
            if(isset($comprofiler_plugin[$mcp]))
            {
              $plugins->thirdparties['cb'][$mcp]->installed = true;
              $plugins->thirdparties['cb'][$mcp]->enabled = (($comprofiler_plugin[$mcp]->published) == 1);
            }
          }
        } catch (Exception $e) {
          $plugins->thirdparties['cb'] = array();
        }
        $this->_item[$pk] = array("plugins" => $plugins);

        $uri = JUri::getInstance();

        $params = JComponentHelper::getParams('com_moojla');
        $moodle_url = trim($params->get('moodle_url'));
        $joomla_token = trim($params->get('joomla_token'));

        $curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => $moodle_url.'auth/moojla/requestHandler.php',
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'POST',
          CURLOPT_POSTFIELDS => array('joomla_url' => $uri->root(),'joomla_token' => $joomla_token),
        ));

        $response = curl_exec($curl);

        $this->_item[$pk]['component'] = json_decode($response);
        curl_close($curl);
        JLoader::register('MoojlaHelper', JPATH_ADMINISTRATOR.'/components/com_moojla/helpers/moojla.php');
        $dataObj = array(
          "wsfunction"          =>  "moojla_health_check",
          "moodlewsrestformat"  =>  "json",
        );
        $tokenReq = MoojlaHelper::sendRequestToMoodle($dataObj);
        $token_status = json_decode($tokenReq->response);
        $this->_item[$pk]['component']->moodleToken = $token_status->message === 1 ? true : false;
        if($token_status->message !== 1)
        {
          $this->_item[$pk]['component']->error->moodleToken = 'Moodle token should be exactly what set to moojla service in yourmoodle.com/admin/settings.php?section=webservicetokens'; // translate need
        }

        JLoader::register('MoojlaHelper', JPATH_ADMINISTRATOR.'/components/com_moojla/helpers/moojla.php');
        $dataObj = array(
          "wsfunction"          =>  "moojla_get_users_minimal",
          "moodlewsrestformat"  =>  "json",
          "notadmin"            =>  1
        );
        $moodleusers = json_decode(MoojlaHelper::sendRequestToMoodle($dataObj)->response, true);
        $mids = array_column($moodleusers, 'id');

        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('mid');
        $query->from($db->quoteName('#__moojla_user_map'));
        $query->where($db->quoteName('mid') . ' <> 0');
        $query->where($db->quoteName('jid') . ' <> 0');
        $query->where($db->quoteName('published') . ' = 1');
        $db->setQuery($query);
        $map = $db->loadColumn();
        $diff = array_diff($mids ,$map);

        $this->_item[$pk]['moodleusersdiff'] = $diff;


        JLoader::register('MoojlaHelper', JPATH_ADMINISTRATOR.'/components/com_moojla/helpers/moojla.php');
        $dataObj = array(
          "wsfunction"          =>  "moojla_get_mapped_users",
          "moodlewsrestformat"  =>  "json",
        );
        $moodlemoojlamap = json_decode(MoojlaHelper::sendRequestToMoodle($dataObj)->response, true);
        $jids = array_column($moodlemoojlamap, 'jid');


        $db = JFactory::getDbo();
        $query = "SELECT u.id FROM #__users AS u WHERE u.id NOT IN ( SELECT uum.user_id FROM #__user_usergroup_map AS uum INNER JOIN #__usergroups AS uu ON uu.id = uum.group_id WHERE uu.title IN ('Super Users', 'Administrator'))";

        $db->setQuery($query);
        $jmap = $db->loadColumn();

        $jdiff = array_diff($jmap, $jids);
        $this->_item[$pk]['joomlausersdiff'] = $jdiff;


        JLoader::register('MoojlaHelper', JPATH_ADMINISTRATOR.'/components/com_moojla/helpers/moojla.php');
        $dataObj = array(
          "wsfunction"          =>  "moojla_get_courses",
          "moodlewsrestformat"  =>  "json",
        );
        $moodlecourses = json_decode(MoojlaHelper::sendRequestToMoodle($dataObj)->response, true);
        $remoteids = array_column($moodlecourses, 'id');

        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('remoteid');
        $query->from($db->quoteName('#__moojla_course'));
        $query->where($db->quoteName('published') . ' = 1');
        $db->setQuery($query);
        $cmap = $db->loadColumn();

        $coursedif = array_diff($remoteids, $cmap);
        $this->_item[$pk]['coursedif'] = $coursedif;

        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('mcatid');
        $query->from($db->quoteName('#__moojla_category_map'));
        $query->where($db->quoteName('published') . ' = 1');
        $db->setQuery($query);
        $catmap = $db->loadColumn();

        $dataObj = array(
          "wsfunction"          => "moojla_get_course_categories",
          "moodlewsrestformat"  => "json",
        );
        $course_cats = json_decode(MoojlaHelper::sendRequestToMoodle($dataObj)->response);
        $categories = array_column($course_cats, 'id');
        $catdif = array_diff($categories, $catmap);
        $this->_item[$pk]['catdif'] = $catdif;

        return $this->_item[$pk];
/***[/JCBGUI$$$$]***/


				// 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('index.php?option=com_moojla');
					return false;
				}

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

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