<?php
/**
 * @package     SP Soccer
 * @subpackage  mod_sp_club_rankings
 *
 * @copyright   Copyright (C) 2010 - 2015 JoomShaper. All rights reserved.
 * @license     GNU General Public License version 2 or later.
 */

defined('_JEXEC') or die;

class ModSpClubRankingsHelper {

	// Get groups by tournament ID
	public static function getTournamentGroups($params) {
		$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', 'title', 'point_table' )));
		$query->from($db->quoteName('#__spsoccer_groups'));
		$query->where($db->quoteName('enabled')." = 1");

		if ($params->get('tournament', '')) {
			$query->where($db->quoteName('spsoccer_tournament_id')." = ". $params->get('tournament'));
		}
		
		$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) {
			$gameteams = json_decode($result->point_table);

			if (!empty($gameteams->pts)) {

				$result->top_team_groups = array();
				//order
				$team_key = 0;
				foreach ($gameteams->team as $id => $gameteams->team_id) {
					
					$team_info = SpsoccerModelTournaments::getTeamInfoById($gameteams->team[$id]);	
					$result->top_team_groups[$team_key] = array(
						'team_name'  => $team_info->title,
						'team_logo'  => $team_info->logo,
						'pts' 		 => $gameteams->pts[$id],
					);
					$team_key ++;
					
				}
			}		
		}
		
		return $results;		
	}

	// Sort ranks high to low
	public static function msort($array, $key, $direction = 'desc', $sort_flags = SORT_REGULAR) {

		
	    if (is_array($array) && count($array) > 0) {
	        
	    	usort($array, create_function('$a, $b', '
				$a = $a["' . $key[0] . '"];
				$b = $b["' . $key[0] . '"];

				if ($a == $b) {
					return 0;
				}

				return ($a ' . ($direction == 'desc' ? '>' : '<') .' $b) ? -1 : 1;
			'));

	    }
	    return $array;
	}


}
