<?php
/**
 * @package     SP Soccer
 * @author      JoomShaper http://www.joomshaper.com
 * @copyright   Copyright (C) 2010 - 2016 JoomShaper. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die('Restricted access');

class SpsoccerModelTournaments extends FOFModel {

	public function __construct($config = array()){
		parent::__construct($config);
	}

	//Build Query
	public function buildQuery($overrideLimits = false){
		$table = $this->getTable();
		$tableName = $table->getTableName();
		$tableKey = $table->getKeyName();
		$db = $this->getDbo();
		$query = $db->getQuery(true);

		// Call the behaviors
		$this->modelDispatcher->trigger('onBeforeBuildQuery', array(&$this, &$query));
		$select = $db->qn($tableName) . '.*';
		$query->select($select)->from($db->qn($tableName));

		//Frontend
		if(FOFPlatform::getInstance()->isFrontend()) {
			//Enabled
			$query->where($db->qn('enabled')." = ".$db->quote('1'));
			//Language
			$query->where('language in (' . $db->quote(JFactory::getLanguage()->getTag()) . ',' . $db->quote('*') . ')');
			//Access
			$query->where($db->quoteName('access')." IN (" . implode( ',', JFactory::getUser()->getAuthorisedViewLevels() ) . ")");
		}

		if (!$overrideLimits){
			if(FOFPlatform::getInstance()->isFrontend()) {
				$order = 'ordering';
			} else {
				$order = $this->getState('filter_order', null, 'cmd');
			}

			if (!in_array($order, array_keys($table->getData()))) {
				$order = $tableKey;
			}

			$order = $db->qn($order);

			if(FOFPlatform::getInstance()->isFrontend()) {
				$dir = 'ASC';
			} else {
				$dir = $this->getState('filter_order_Dir', 'ASC', 'cmd');
			}

			$query->order($order . ' ' . $dir);
		}
		if(!FOFPlatform::getInstance()->isFrontend()) {
			// Call the behaviors
			$this->modelDispatcher->trigger('onAfterBuildQuery', array(&$this, &$query));
		}

		return $query;
	}

	// Get groups by tournament ID
	public function getTournamentGroups($tournament_id) {
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);

		// Select all records from the user profile table where key begins with "custom.".
		$query->select($db->quoteName(array('spsoccer_group_id', 'spsoccer_tournament_id', 'title', 'slug', 'spsoccer_gameteam_id', 'description', 'point_table')));
		$query->from($db->quoteName('#__spsoccer_groups'));
		$query->where($db->quoteName('enabled')." = 1");
		$query->where($db->quoteName('spsoccer_tournament_id')." = ".$db->quote($tournament_id));
		//Language
		$query->where('language in (' . $db->quote(JFactory::getLanguage()->getTag()) . ',' . $db->quote('*') . ')');
		//Access
		$query->where($db->quoteName('access')." IN (" . implode( ',', JFactory::getUser()->getAuthorisedViewLevels() ) . ")");
		$query->order('ordering DESC');
		// Reset the query using our newly populated query object.
		$db->setQuery($query);

		// Load the results as a list of stdClass objects (see later for more options on retrieving data).
		$results = $db->loadObjectList();

		foreach ($results as &$result) {
			$group_team_ids = json_decode($result->spsoccer_gameteam_id);
			$result->groups_teams_info = array();
			foreach ($group_team_ids as $key => $group_team_id) {
				$team_infos = $this->getTeamInfoById($group_team_id);
				$result->groups_teams_info[$key] = array(
					'team_id'		=> $team_infos->spsoccer_gameteam_id,
					'team_name' 	=> $team_infos->title,
					'team_slug' 	=> $team_infos->slug,
					'team_logo'    	=> $team_infos->logo,
					'team_url'    	=> JRoute::_('index.php?option=com_spsoccer&view=gameteam&id=' . $team_infos->spsoccer_gameteam_id . ':' . $team_infos->slug . SpsoccerHelper::getItemid('gameteams')),
				);
			}

		}

		return $results;

	}

	// Get Sessions by tournament ID
	public function getTournamentSessions($tournament_id = 0, $ordering = 'ASC') {
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);

		// Select all records from the user profile table where key begins with "custom.".
		$query->select($db->quoteName(array('spsoccer_session_id', 'title')));
		$query->from($db->quoteName('#__spsoccer_sessions'));
		$query->where($db->quoteName('enabled')." = 1");
		$query->where($db->quoteName('spsoccer_tournament_id')." = ".$db->quote($tournament_id));
		//$query->where($db->quoteName('access')." IN (" . implode( ',', JFactory::getUser()->getAuthorisedViewLevels() ) . ")");
		//Language
		$query->where('language in (' . $db->quote(JFactory::getLanguage()->getTag()) . ',' . $db->quote('*') . ')');
		//Access
		$query->where($db->quoteName('access')." IN (" . implode( ',', JFactory::getUser()->getAuthorisedViewLevels() ) . ")");
		$query->order('ordering '. $ordering);
		// Reset the query using our newly populated query object.
		$db->setQuery($query);

		// Load the results as a list of stdClass objects (see later for more options on retrieving data).
		$results = $db->loadObjectList();

		return $results;
	}

	// Get Matches by Session & Tournament ID
	public static function getSessionMatches($session_id, $tournament_id, $ordering = 'ASC', $limit = NULL) {
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);

		// Select all records from the user profile table where key begins with "custom.".
		$query->select($db->quoteName(array('spsoccer_match_id', 'title', 'slug', 'teamone', 'teamtwo', 'date', 'time', 'spsoccer_vanue_id')));
		$query->from($db->quoteName('#__spsoccer_matches'));
		$query->where($db->quoteName('enabled')." = 1");

		if (isset($session_id)) {
			$query->where($db->quoteName('spsoccer_session_id')." = ".$db->quote($session_id));
		}

		$query->where($db->quoteName('spsoccer_tournament_id')." = ".$db->quote($tournament_id));
		//$query->where($db->quoteName('access')." IN (" . implode( ',', JFactory::getUser()->getAuthorisedViewLevels() ) . ")");
		//Language
		$query->where('language in (' . $db->quote(JFactory::getLanguage()->getTag()) . ',' . $db->quote('*') . ')');
		//Access
		$query->where($db->quoteName('access')." IN (" . implode( ',', JFactory::getUser()->getAuthorisedViewLevels() ) . ")");

		if ($ordering == 'ASC'  || $ordering == 'DESC') {
			$query->order('ordering '. $ordering);
		} elseif($ordering == 'date_asc'){
			$query->order('date ASC');
			$query->order('time ASC');
		} elseif($ordering == 'date_desc') {
			$query->order('date DESC');
			$query->order('time DESC');
		}

		if ($limit) {
			$query->setLimit($limit);
		}
		// Reset the query using our newly populated query object.
		$db->setQuery($query);

		// Load the results as a list of stdClass objects (see later for more options on retrieving data).
		$results = $db->loadObjectList();

		return $results;
	}

	// Get Matches by Session & Tournament ID
	public function getSessionPlayedMatches($session_id, $tournament_id) {
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);

		// Select all records from the user profile table where key begins with "custom.".
		$query->select($db->quoteName(array('spsoccer_match_id', 'title', 'slug', 'teamone', 'teamtwo', 'date', 'time', 'spsoccer_vanue_id', 'teamone_score', 'teamtwo_score')));
		$query->from($db->quoteName('#__spsoccer_matches'));
		$query->where($db->quoteName('enabled')." = 1");
		$query->where($db->quoteName('played_game')." = 1");
		$query->where($db->quoteName('spsoccer_session_id')." = ".$db->quote($session_id));
		$query->where($db->quoteName('spsoccer_tournament_id')." = ".$db->quote($tournament_id));
		//$query->where($db->quoteName('access')." IN (" . implode( ',', JFactory::getUser()->getAuthorisedViewLevels() ) . ")");
		//Language
		$query->where('language in (' . $db->quote(JFactory::getLanguage()->getTag()) . ',' . $db->quote('*') . ')');
		//Access
		$query->where($db->quoteName('access')." IN (" . implode( ',', JFactory::getUser()->getAuthorisedViewLevels() ) . ")");
		$query->order('date DESC');
		// Reset the query using our newly populated query object.
		$db->setQuery($query);

		// Load the results as a list of stdClass objects (see later for more options on retrieving data).
		$results = $db->loadObjectList();

		return $results;
	}

	// Get teams info by team id
	public function getTeamsInfoById($team_id){
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);
		// Select all records from the user profile table where key begins with "custom.".
		$query->select($db->quoteName(array('spsoccer_gameteam_id', 'title', 'slug', 'logo')));
		$query->from($db->quoteName('#__spsoccer_gameteams'));
		//Language
		$query->where('language in (' . $db->quote(JFactory::getLanguage()->getTag()) . ',' . $db->quote('*') . ')');
		//Access
		$query->where($db->quoteName('access')." IN (" . implode( ',', JFactory::getUser()->getAuthorisedViewLevels() ) . ")");
		$query->where($db->quoteName('enabled')." = 1");
		$query->where($db->quoteName('spsoccer_gameteam_id')." = ".$db->quote($team_id));
		$query->order('ordering DESC');
		$db->setQuery($query);
		$results = $db->loadObjectList();

		return $results;

	}

	// Get Matches by Session & Tournament ID
	public function getLastPlayedMatch($tournament_id) {

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

		$query->select($db->quoteName(array('a.spsoccer_match_id', 'a.title', 'a.slug', 'a.teamone', 'a.teamtwo', 'a.image', 'a.date', 'a.time', 'a.teamone_score', 'a.teamtwo_score')));
		$query->select($db->quoteName('b.title', 'teamone_name'));
		$query->select($db->quoteName('b.logo', 'teamone_logo'));
		$query->select($db->quoteName('c.title', 'teamtwo_name'));
		$query->select($db->quoteName('c.logo', 'teamtwo_logo'));
		$query->from($db->quoteName('#__spsoccer_matches', 'a'));
		$query->join('LEFT', $db->quoteName('#__spsoccer_gameteams', 'b') . ' ON (' . $db->quoteName('a.teamone') . ' = ' . $db->quoteName('b.spsoccer_gameteam_id') . ')');
		$query->join('LEFT', $db->quoteName('#__spsoccer_gameteams', 'c') . ' ON (' . $db->quoteName('a.teamtwo') . ' = ' . $db->quoteName('c.spsoccer_gameteam_id') . ')');
		$query->order('date DESC');
		//Language
		$query->where('a.language in (' . $db->quote(JFactory::getLanguage()->getTag()) . ',' . $db->quote('*') . ')');
		//Access
		$query->where($db->quoteName('a.access')." IN (" . implode( ',', JFactory::getUser()->getAuthorisedViewLevels() ) . ")");
		$query->where($db->quoteName('a.enabled')." = 1");
		$query->where($db->quoteName('a.played_game')." = 1");
		$query->where($db->quoteName('a.spsoccer_tournament_id')." = ".$db->quote($tournament_id));

		$db->setQuery($query);

		$result = $db->loadObject();

		return $result;

	}


	// Get vanue info by vanue id
	public function getVanueInfoById($vanue_id){
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);
		// Select all records from the user profile table where key begins with "custom.".
		$query->select($db->quoteName(array('spsoccer_vanue_id', 'title', 'slug')));
		$query->from($db->quoteName('#__spsoccer_vanues'));
		//Language
		$query->where('language in (' . $db->quote(JFactory::getLanguage()->getTag()) . ',' . $db->quote('*') . ')');
		//Access
		$query->where($db->quoteName('access')." IN (" . implode( ',', JFactory::getUser()->getAuthorisedViewLevels() ) . ")");

		$query->where($db->quoteName('enabled')." = 1");
		$query->where($db->quoteName('spsoccer_vanue_id')." = ".$db->quote($vanue_id));
		$query->order('ordering DESC');
		$db->setQuery($query);
		$result = $db->loadObject();

		return $result;

	}

	// Get teams info by team id
	public static function getTeamInfoById($team_id){

		$db = JFactory::getDbo();
		$query = $db->getQuery(true);
		// Select all records from the user profile table where key begins with "custom.".
		$query->select($db->quoteName(array('spsoccer_gameteam_id', 'title', 'slug', 'logo')));
		$query->from($db->quoteName('#__spsoccer_gameteams'));
		//Language
		$query->where('language in (' . $db->quote(JFactory::getLanguage()->getTag()) . ',' . $db->quote('*') . ')');
		//Access
		$query->where($db->quoteName('access')." IN (" . implode( ',', JFactory::getUser()->getAuthorisedViewLevels() ) . ")");

		$query->where($db->quoteName('enabled')." = 1");
		$query->where($db->quoteName('spsoccer_gameteam_id')." = ".$db->quote($team_id));
		$query->order('ordering DESC');
		$db->setQuery($query);
		$result = $db->loadObject();

		return $result;
	}

	// Sort ranks high to low
	public static function msort($array, $pts = array('ptss'), $avgs = array('avgs'), $direction = 'desc', $sort_flags = SORT_REGULAR) {
	    if (is_array($array) && count($array) > 0) {

			// 	echo "<pre>";
			// 	print_r($avgs);
			// 	echo "</pre>";
			//
	    // 	usort($array, create_function('$a, $b', '
			// 	$a = $a["' . $pts[0] . '"];
			// 	$b = $b["' . $pts[0] . '"];
			// 	if ($a == $b){
			// 		return ($a ' . ('>') .' $b) ? -1 : 1;
			// 	}
			// 	return ($a ' . ($direction == 'desc' ? '>' : '<') .' $b) ? -1 : 1;
			// '));

				foreach ($array as $key => $data) {
				    $ptss[$key] = $data['ptss'];
				    $avgs[$key] = $data['avgs'];
				}
				array_multisort($ptss, SORT_DESC, $avgs, SORT_DESC, $array);

	    }
	    return $array;
	}

}
