<?php

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

jimport('joomla.plugin.plugin');

$app = JFactory::getApplication();
if($app->isClient('administrator')){
	return true;
}

class plgSystemGuruStudentActivity extends JPlugin {

    public function __construct (& $subject, $config) {
        parent::__construct($subject, $config);
    }

    /**
     * This method should handle any login logic and report back to the subject
     * For Joomla 1.6, onLoginUser is now onUserLogin
     *
     * @access	public
     * @param 	array 	holds the user data
     * @param 	array    extra options
     * @return	boolean	True on success
     * @since	1.6
     */
    public function onAfterDispatch(){
    	$input = JFactory::getApplication()->input;
		$option = $input->get("option", "");
		if($option != "com_guru"){
			return true;
		}
		
		$user = JFactory::getUser();
		$this->addStream((array)$user);
    }
	
	function checkEnrollAction($user_id, $old_courses_id, $installed_plugin_user){
		$db = JFactory::getDBO();
		if(count($old_courses_id) == 0){
			$old_courses_id = array("0");
		}
		$sql = "select distinct(`course_id`) from #__guru_buy_courses where `userid`=".intval($user_id)." and `price`='0' and `course_id` not in (".implode(",", $old_courses_id).") and `buy_date` >= '".$installed_plugin_user."'";
		$db->setQuery($sql);
		$result = $db->loadColumn();
		
		return $result;
	}
	function checkBuyAction($user_id, $old_courses_id, $installed_plugin_user){
		$db = JFactory::getDBO();
		if(count($old_courses_id) == 0){
			$old_courses_id = array("0");
		}
		$sql = "select bc.`course_id` from  #__guru_buy_courses bc, #__guru_order o where o.id=bc.order_id and bc.price>0 and bc.`userid`=".intval($user_id)." and o.`status`='Paid' and bc.`course_id` not in (".implode(",", $old_courses_id).") and o.`order_date` >= '".$installed_plugin_user."'";
		$db->setQuery($sql);
		$result = $db->loadColumn();
		
		return $result;
	}
	
	function checkCertificateAction($user_id, $old_courses_id, $installed_plugin_user){
		$db = JFactory::getDBO();
		if(count($old_courses_id) == 0){
			$old_courses_id = array("0");
		}
		$sql = "select `course_id` from #__guru_mycertificates where `user_id`=".intval($user_id)." and `course_id` not in (".implode(",", $old_courses_id).") and `datecertificate` >= '".date("Y-m-d", strtotime($installed_plugin_user))."'";
		$db->setQuery($sql);
		$result = $db->loadColumn();
		
		return $result;
	}
	
	function checkFinishAction($user_id, $old_courses_id, $installed_plugin_user){
		$db = JFactory::getDBO();
		if(count($old_courses_id) == 0){
			$old_courses_id = array("0");
		}
		$sql = "select `pid` from #__guru_viewed_lesson where `user_id`=".intval($user_id)." and `pid` not in (".implode(",", $old_courses_id).") and `completed`=1 and `date_completed` >= '".date("Y-m-d", strtotime($installed_plugin_user))."'";
		$db->setQuery($sql);
		$result = $db->loadColumn();
		
		return $result;
	}
	
	function checkQuizzAction($user_id, $old_courses_id, $installed_plugin_user){
		$db = JFactory::getDBO();
		
		if(count($old_courses_id) == 0){
			$old_courses_id = array("0");
		}
		$sql = "select q.`name`, q.`max_score`, qt.`quiz_id`, qt.`score_quiz`, qt.`pid` from #__guru_quiz q INNER JOIN  #__guru_quiz_question_taken_v3 qt ON q.`id` = qt.`quiz_id` where `user_id`=".intval($user_id)." and q.is_final=0 and qt.`pid` not in (".implode(",", $old_courses_id).") and qt.`date_taken_quiz` >= '".$installed_plugin_user."' order by qt.`id` desc limit 0,1";
		$db->setQuery($sql);
		$result = $db->loadAssocList();
				
		return $result;
	}
	
	function checkFinalQuizzAction($user_id, $old_courses_id, $installed_plugin_user){
		$db = JFactory::getDBO();
		
		if(count($old_courses_id) == 0){
			$old_courses_id = array("0");
		}
		$sql = "select q.`name`, q.`max_score`, qt.`quiz_id`, qt.`score_quiz`, qt.`pid` from #__guru_quiz q INNER JOIN  #__guru_quiz_question_taken_v3 qt ON q.`id` = qt.`quiz_id` where `user_id`=".intval($user_id)." and q.is_final=1 and qt.`pid` not in (".implode(",", $old_courses_id).") and qt.`date_taken_quiz` >= '".$installed_plugin_user."' order by qt.`id` desc limit 0,1";

		$db->setQuery($sql);
		$result = $db->loadAssocList();
				
		return $result;
	}
	
    private function addStream($user) {
    	$input = JFactory::getApplication()->input;
		$lang = JFactory::getLanguage();
        $lang->load('plg_system_gurustudentactivity', JPATH_ADMINISTRATOR); /* $this->loadLanguage(); can't call this on Joomla! 1.5 */
		$db = JFactory::getDBO();
		$sql = "select count(*) from #__extensions where element='com_guru' and `enabled`=1";
		$db->setQuery($sql);
		$count = $db->loadColumn();
		$count_guru = $count["0"];
		
		$sql = "select count(*) from #__extensions where element='com_community' and `enabled`=1";
		$db->setQuery($sql);
		$count = $db->loadColumn();
		$count_comm = $count["0"];
		
		if ( $count_guru >0 && $count_comm >0){
			require_once JPATH_ROOT .'/components/com_community/libraries/core.php';
			CFactory::load('libraries', 'activities');
			$id = CUserHelper::getUserId($user['username']);
			$my = CFactory::getUser($id);
			CFactory::setActiveProfile($id);
			$jnow = JFactory::getDate();
			$current_date_string = $jnow->toSQL();
			
			$sql = "select `installed_plugin_user` from #__guru_config";
			$db->setQuery($sql);
			$installed_plugin_user = $db->loadColumn();
			$installed_plugin_user = @$installed_plugin_user["0"];
			
			$sql = "select * from #__guru_buy_courses where `userid`=".intval($my->id);
			$db->setQuery($sql);
			$all_courses_of_student = $db->loadAssocList();
			$actions = array("buy", "enroll", "certificate", "finish", "quizz", "exam");	
			$item_id = $input->get('Itemid', 0);
			$_SESSION["ITEMID"] = $item_id;
	
			foreach($actions as $key=>$action){
				if($action == "enroll" && $this->params->get("showenroll", "1") == 1){
					$sql = "select `params` from #__guru_jomsocialstream where `userid`=".intval($my->id);
					$db->setQuery($sql);
					$params = $db->loadAssocList();
					
					$new_user = true;
					if(isset($params) && count(@$params["0"]) > 0){
						$new_user = false;
					}
					$params = json_decode(@$params["0"]["params"], true);
					
					$old_courses_id = array();
					if(isset($params["enroll"])){
						$old_courses_id = explode(",", trim($params["enroll"]));
					}
	
					$new_courses_id = $this->checkEnrollAction(intval($my->id), $old_courses_id, $installed_plugin_user);
					
					if(is_array($new_courses_id) && count($new_courses_id) > 0){
						$sum = array_merge($old_courses_id, $new_courses_id);
						$params["enroll"] = implode(",", $sum);
						
						if(isset($params["buy"])){
							$old_courses_id_buy = explode(",", trim($params["buy"]));
							$sum_buy = array_merge($old_courses_id_buy, $new_courses_id);
							$params["buy"] = implode(",", $sum_buy);
						}
						
						if(!$new_user){
							$sql = "update #__guru_jomsocialstream set params='".json_encode($params)."' where `userid`=".intval($my->id);
							$db->setQuery($sql);
							$db->execute();
						}
						else{
							$sql = "insert into #__guru_jomsocialstream (`userid`, `params`) values (".intval($my->id).", '".json_encode($params)."')";
							$db->setQuery($sql);
							$db->execute();
						}
						$sitebase = JURI::root();
						$sitebase = explode("/", $sitebase);
						$sitebase = $sitebase[0]."//".$sitebase[2];
						
						
						foreach($new_courses_id as $key=>$course_id){
							$sql = "select `name`, `alias` from #__guru_program where `id`=".intval($course_id);
							$db->setQuery($sql);
							$course_detail = $db->loadAssocList();
			
							$act = new stdClass();
							$act->cmd  = 'wall.write';
							$act->actor = $my->id;
							$act->target = 0; // no target
							$course_link = JRoute::_('index.php?option=com_guru&view=guruPrograms&task=view&cid='.$course_id."-".$course_detail["0"]["alias"]."&Itemid=".intval(@$item_id));
							$text =  JText::_('PLG_GURUSTUDEACTIVITY_ENROLL');
							$act->title = JText::_('{actor} '.$text.' <a href="'.$course_link.'">'.$course_detail["0"]["name"].'</a>'.'.');
							$act->content = '';
							$act->app = 'wall';
							$act->cid = 0;
							$act->params = '';
							CFactory::load('libraries', 'activities');
							$act->comment_type = 'gurustudentactivity.comment';
							$act->comment_id = CActivities::COMMENT_SELF;
							 
							$act->like_type = 'gurustudentactivity.like';
							$act->like_id = CActivities::LIKE_SELF;
							CActivityStream::add($act);
						}
					}
				}
				elseif($action == "buy" && $this->params->get("showbuy", "1") == 1){
					$sql = "select `params` from #__guru_jomsocialstream where `userid`=".intval($my->id);
					$db->setQuery($sql);
					$params = $db->loadAssocList();
					
					$new_user = true;
					if(isset($params) && count(@$params["0"]) > 0){
						$new_user = false;
					}
					$params = json_decode(@$params["0"]["params"], true);
					
					$old_courses_id = array();
					if(isset($params["buy"])){
						$old_courses_id = explode(",", trim($params["buy"]));
					}
					$new_courses_id = $this->checkBuyAction(intval($my->id), $old_courses_id, $installed_plugin_user);
					
					if(is_array($new_courses_id) && count($new_courses_id) > 0){
						$sum = array_merge($old_courses_id, $new_courses_id);
						$params["buy"] = implode(",", $sum);
						
						if(isset($params["enroll"])){
							$old_courses_id_enroll = explode(",", trim($params["enroll"]));
							$sum_enroll = array_merge($old_courses_id_enroll, $new_courses_id);
							$params["enroll"] = implode(",", $sum_enroll);
						}
						
						if(!$new_user){
							$sql = "update #__guru_jomsocialstream set params='".json_encode($params)."' where `userid`=".intval($my->id);
							$db->setQuery($sql);
							$db->execute();
						}
						else{
							$sql = "insert into #__guru_jomsocialstream (`userid`, `params`) values (".intval($my->id).", '".json_encode($params)."')";
							$db->setQuery($sql);
							$db->execute();
						}
						
						foreach($new_courses_id as $key=>$course_id){
							$sql = "select `name`, `alias`, `author` from #__guru_program where `id`=".intval($course_id);
							$db->setQuery($sql);
							$course_detail = $db->loadAssocList();
							
							$act = new stdClass();
							$act->cmd  = 'wall.write';
							$act->actor = $my->id;
							$act->target = 0; // no target
							$course_link = JRoute::_('index.php?option=com_guru&view=guruPrograms&task=view&cid='.$course_id."-".$course_detail["0"]["alias"]."&Itemid=".intval(@$item_id));
							$text =  JText::_('PLG_GURUSTUDEACTIVITY_ENROLL');
							
							$act->title = JText::_('{actor} '.$text.' '.'<a href="'.$course_link.'">'.$course_detail["0"]["name"].'</a>'.'.');
							$act->content = '';
							$act->app = 'wall';
							$act->cid = 0;
							$act->params = '';
							CFactory::load('libraries', 'activities');
							$act->comment_type = 'gurustudentactivity.comment';
							$act->comment_id = CActivities::COMMENT_SELF;
							 
							$act->like_type = 'gurustudentactivity.like';
							$act->like_id = CActivities::LIKE_SELF;
							CActivityStream::add($act);
						}
					}
				}
				elseif($action == "certificate" && $this->params->get("showcert", "1") == 1){
					$sql = "select `params` from #__guru_jomsocialstream where `userid`=".intval($my->id);
					$db->setQuery($sql);
					$params = $db->loadAssocList();
					
					$new_user = true;
					if(isset($params) && count(@$params["0"]) > 0){
						$new_user = false;
					}
					$params = json_decode(@$params["0"]["params"], true);
					
					$old_courses_id = array();
					if(isset($params["certificate"])){
						$old_courses_id = explode(",", trim($params["certificate"]));
					}
					$new_courses_id = $this->checkCertificateAction(intval($my->id), $old_courses_id, $installed_plugin_user);
					
					if(is_array($new_courses_id) && count($new_courses_id) > 0){
						$sum = array_merge($old_courses_id, $new_courses_id);
						$params["certificate"] = implode(",", $sum);
						
						if(!$new_user){
							$sql = "update #__guru_jomsocialstream set params='".json_encode($params)."' where `userid`=".intval($my->id);
							$db->setQuery($sql);
							$db->execute();
						}
						else{
							$sql = "insert into #__guru_jomsocialstream (`userid`, `params`) values (".intval($my->id).", '".json_encode($params)."')";
							$db->setQuery($sql);
							$db->execute();
						}
						
						foreach($new_courses_id as $key=>$course_id){
							$sql = "select `name`, `alias`, `author` from #__guru_program where `id`=".intval($course_id);
							$db->setQuery($sql);
							$course_detail = $db->loadAssocList();
							
							$act = new stdClass();
							$act->cmd  = 'wall.write';
							$act->actor = $my->id;
							$act->target = 0; // no target
							$course_link = JRoute::_('index.php?option=com_guru&view=guruPrograms&task=view&cid='.$course_id."-".$course_detail["0"]["alias"]."&Itemid=".intval(@$item_id));
							$text =  JText::_('PLG_GURUSTUDEACTIVITY_CERTIFICATE');
							
							$act->title = JText::_('{actor} '.$text.' '.'<a href="'.$course_link.'">'.$course_detail["0"]["name"].'</a>'.'.');
							$act->content = '';
							$act->app = 'wall';
							$act->cid = 0;
							$act->params = '';
							CFactory::load('libraries', 'activities');
							$act->comment_type = 'gurustudentactivity.comment';
							$act->comment_id = CActivities::COMMENT_SELF;
							 
							$act->like_type = 'gurustudentactivity.like';
							$act->like_id = CActivities::LIKE_SELF;
							CActivityStream::add($act);
						}
					}
				}
				elseif($action == "finish" && $this->params->get("showfinish", "1") == 1){
					$sql = "select `params` from #__guru_jomsocialstream where `userid`=".intval($my->id);
					$db->setQuery($sql);
					$params = $db->loadAssocList();
					
					$new_user = true;
					if(isset($params) && count(@$params["0"]) > 0){
						$new_user = false;
					}
					$params = json_decode(@$params["0"]["params"], true);
					
					$old_courses_id = array();
					if(isset($params["finish"])){
						$old_courses_id = explode(",", trim($params["finish"]));
					}
					$new_courses_id = $this->checkFinishAction(intval($my->id), $old_courses_id, $installed_plugin_user);
					
					if(is_array($new_courses_id) && count($new_courses_id) > 0){
						$sum = array_merge($old_courses_id, $new_courses_id);
						$params["finish"] = implode(",", $sum);
						
						if(!$new_user){
							$sql = "update #__guru_jomsocialstream set params='".json_encode($params)."' where `userid`=".intval($my->id);
							$db->setQuery($sql);
							$db->execute();
						}
						else{
							$sql = "insert into #__guru_jomsocialstream (`userid`, `params`) values (".intval($my->id).", '".json_encode($params)."')";
							$db->setQuery($sql);
							$db->execute();
						}
						
						foreach($new_courses_id as $key=>$course_id){
							$sql = "select `name`, `alias` from #__guru_program where `id`=".intval($course_id);
							$db->setQuery($sql);
							$course_detail = $db->loadAssocList();
							
							$act = new stdClass();
							$act->cmd  = 'wall.write';
							$act->actor = $my->id;
							$act->target = 0; // no target
							$course_link = JRoute::_('index.php?option=com_guru&view=guruPrograms&task=view&cid='.$course_id."-".$course_detail["0"]["alias"]."&Itemid=".intval(@$item_id));
							$text =  JText::_('PLG_GURUSTUDEACTIVITY_FINISH');
							$act->title = JText::_('{actor} '.$text.' <a href="'.$course_link.'">'.$course_detail["0"]["name"].'</a>'.'.');
							$act->content = '';
							$act->app = 'wall';
							$act->cid = 0;
							$act->params = '';
							CFactory::load('libraries', 'activities');
							$act->comment_type = 'gurustudentactivity.comment';
							$act->comment_id = CActivities::COMMENT_SELF;
							 
							$act->like_type = 'gurustudentactivity.like';
							$act->like_id = CActivities::LIKE_SELF;
							CActivityStream::add($act);
						}
					}
				}
				elseif($action == "quizz" && $this->params->get("showrquiz", "1") == 1){
					$sql = "select `params` from #__guru_jomsocialstream where `userid`=".intval($my->id);
					$db->setQuery($sql);
					$params = $db->loadAssocList();
					
					$new_courses_array = array();
					$new_courses_id = array();
					
					$new_user = true;
					if(isset($params) && count(@$params["0"]) > 0){
						$new_user = false;
					}
					$params = json_decode(@$params["0"]["params"], true);
					
					$old_courses_id = array();
					$old_courses_id2 = array();
					if(isset($params["quizz"])){
						$old_courses_id = explode(",", trim($params["quizz"]));
						$old_courses_id_temp = explode(",", trim($params["quizz"]));
						foreach($old_courses_id_temp as $key=>$value){
							$value_temp = explode("-", $value);
							$old_courses_id2[] = intval($value_temp["0"]);
						}
					}
					
					$all_quizzes_data = $this->checkQuizzAction(intval($my->id), $old_courses_id2, $installed_plugin_user);
					
					foreach($all_quizzes_data as $key=>$quizz_calculation){
						$score = $quizz_calculation["score_quiz"];
						$score = explode("|", $score);
						$final_score = 0;
						if(isset($score[1]) && $score[1] != 0){
							$final_score = intval(($score[0]/$score[1])*100);
						}
						if($final_score >= $quizz_calculation["max_score"]){
							$new_courses_array[] = $quizz_calculation;
							$new_courses_id[] = $quizz_calculation["pid"]."-".$quizz_calculation["quiz_id"];
						}
					}
					
					if(is_array($new_courses_array) && count($new_courses_array) > 0){
						$sum = array_merge($old_courses_id, $new_courses_id);
						$params["quizz"] = implode(",", $sum);
						
						if(!$new_user){
							$sql = "update #__guru_jomsocialstream set params='".json_encode($params)."' where `userid`=".intval($my->id);
							$db->setQuery($sql);
							$db->execute();
						}
						else{
							$sql = "insert into #__guru_jomsocialstream (`userid`, `params`) values (".intval($my->id).", '".json_encode($params)."')";
							$db->setQuery($sql);
							$db->execute();
						}
						
						foreach($new_courses_array as $key=>$courses_quizzes){
							$sql = "select `name`, `alias` from #__guru_program where `id`=".intval($courses_quizzes["pid"]);
							$db->setQuery($sql);
							$course_detail = $db->loadAssocList();
							
							$act = new stdClass();
							$act->cmd  = 'wall.write';
							$act->actor = $my->id;
							$act->target = 0; // no target
							$course_link = JRoute::_('index.php?option=com_guru&view=guruPrograms&task=view&cid='.$course_id."-".$course_detail["0"]["alias"]."&Itemid=".intval(@$item_id));
							$text =  JText::_('PLG_GURUSTUDEACTIVITY_QUIZZ1');
							$text2 =  JText::_('PLG_GURUSTUDEACTIVITY_QUIZZ2');
							$act->title = JText::_('{actor} '.$text.' '.'"'.$courses_quizzes["name"].'"'.' '.$text2.' '.'<a href="'.$course_link.'">'.$course_detail["0"]["name"].'</a>'.'.');
							$act->content = '';
							$act->app = 'wall';
							$act->cid = 0;
							$act->params = '';
							CFactory::load('libraries', 'activities');
							$act->comment_type = 'gurustudentactivity.comment';
							$act->comment_id = CActivities::COMMENT_SELF;
							 
							$act->like_type = 'gurustudentactivity.like';
							$act->like_id = CActivities::LIKE_SELF;
							CActivityStream::add($act);
						}
					}
				}
				elseif($action == "exam" && $this->params->get("showfexam", "1") == 1){
					$sql = "select `params` from #__guru_jomsocialstream where `userid`=".intval($my->id);
					$db->setQuery($sql);
					$params = $db->loadAssocList();
					
					$new_courses_array = array();
					$new_courses_id = array();
					
					$new_user = true;
					if(isset($params) && count(@$params["0"]) > 0){
						$new_user = false;
					}
					$params = json_decode(@$params["0"]["params"], true);
					
					$old_courses_id = array();
					$old_courses_id2 = array();
					if(isset($params["exam"])){
						$old_courses_id = explode(",", trim($params["exam"]));
						$old_courses_id_temp = explode(",", trim($params["exam"]));
						foreach($old_courses_id_temp as $key=>$value){
							$value_temp = explode("-", $value);
							$old_courses_id2[] = intval($value_temp["0"]);
						}
					}
					
					$all_quizzes_data = $this->checkFinalQuizzAction(intval($my->id), $old_courses_id2, $installed_plugin_user);
					
					foreach($all_quizzes_data as $key=>$quizz_calculation){
						$score = $quizz_calculation["score_quiz"];
						$score = explode("|", $score);
						
						//$final_score = intval(($score[0]/$score[1])*100);

						$final_score = 0;

						if(isset($score[0]) && isset($score[1]) && $score[0] > 0 && $score[1] > 0 ){
							$final_score = intval(($score[0]/$score[1])*100);
						}

						if($final_score >= $quizz_calculation["max_score"]){
							$new_courses_array[] = $quizz_calculation;
							$new_courses_id[] = $quizz_calculation["pid"]."-".$quizz_calculation["quiz_id"];
						}
					}
					
					if(is_array($new_courses_array) && count($new_courses_array) > 0){
						$sum = array_merge($old_courses_id, $new_courses_id);
						$params["exam"] = implode(",", $sum);
						
						if(!$new_user){
							$sql = "update #__guru_jomsocialstream set params='".json_encode($params)."' where `userid`=".intval($my->id);
							$db->setQuery($sql);
							$db->execute();
						}
						else{
							$sql = "insert into #__guru_jomsocialstream (`userid`, `params`) values (".intval($my->id).", '".json_encode($params)."')";
							$db->setQuery($sql);
							$db->execute();
						}
						
						foreach($new_courses_array as $key=>$courses_quizzes){
							$sql = "select `name`, `alias` from #__guru_program where `id`=".intval($courses_quizzes["pid"]);
							$db->setQuery($sql);
							$course_detail = $db->loadAssocList();
							
							$act = new stdClass();
							$act->cmd  = 'wall.write';
							$act->actor = $my->id;
							$act->target = 0; // no target
							$course_link = JRoute::_('index.php?option=com_guru&view=guruPrograms&task=view&cid='.$courses_quizzes["pid"]."-".$course_detail["0"]["alias"]."&Itemid=".intval(@$item_id));
							$text =  JText::_('PLG_GURUSTUDEACTIVITY_FEXAM');
							$text2 =  JText::_('PLG_GURUSTUDEACTIVITY_QUIZZ2');
							$act->title = JText::_('{actor} '.$text.' '.'"'.$courses_quizzes["name"].'"'.' '.$text2.' '.'<a href="'.$course_link.'">'.$course_detail["0"]["name"].'</a>'.'.');
							$act->content = '';
							$act->app = 'wall';
							$act->cid = 0;
							$act->params = '';
							CFactory::load('libraries', 'activities');
							$act->comment_type = 'gurustudentactivity.comment';
							$act->comment_id = CActivities::COMMENT_SELF;
							 
							$act->like_type = 'gurustudentactivity.like';
							$act->like_id = CActivities::LIKE_SELF;
							CActivityStream::add($act);
						}
					}
				}
			}
		}	
	}	
}

?>