<?php
include_once 'connection.php';

include 'goallinefunctionsJSON.php';


function JSONfullStandings() {
	$setPDO = createDBH();

	#Get current state
	$currentteam = ( isset( $_GET['teamid'] ) && is_numeric( $_GET['teamid'] ) ) ? intval( $_GET['teamid'] ) : 0;
	$currentseason = ( isset( $_GET['seasonid'] ) && is_numeric( $_GET['seasonid'] ) ) ? intval( $_GET['seasonid'] ) : 0;
	$currentsubseason = ( isset( $_GET['subseasonid'] ) && is_numeric( $_GET['subseasonid'] ) ) ? intval( $_GET['subseasonid'] ) : 0;
	$currentlevel = ( isset( $_GET['levelid'] ) && is_numeric( $_GET['levelid'] ) ) ? intval( $_GET['levelid'] ) : 0;
	$currentdivision = isset($_GET['divid']) ? $_GET['divid'] : NULL;
	$standingstablesHTML = '';
	$nextlevelHTML = '';

	$outputArray = array();

	#If only a team is specified
	if ($currentteam != 0)
	{
		$seasonlevelFetch = $DBH->prepare('SELECT idSeason, idLevelSeason, Division FROM teamstatview WHERE idTeamAssignment = :teamid LIMIT 1');
		$seasonlevelFetch->bindParam(':teamid', $currentteam, PDO::PARAM_INT);
		$seasonlevelFetch->execute();
		$seasonlevelFetched = $seasonlevelFetch->fetch(PDO::FETCH_ASSOC);
		$currentseason = $seasonlevelFetched['idSeason'];
		$currentlevel = $seasonlevelFetched['idLevelSeason'];
		$currentdivision = $seasonlevelFetched['Division'];
	}

	#Determines groupings by level, each detected level creates a standings group
	$standingslevelstart = 'SELECT DISTINCT idLevel, Level FROM SeasonLevels JOIN level ON SeasonLevels.idLevel = level.idLevelSeason WHERE idSeason = :seasonid';
	if ($currentlevel != 0)
	{
		$standingslevelstart .= ' AND idLevel = :levelid';
	}
	$standingslevelstart .= ' ORDER BY SortPriority';
	$StandingsGroupFetch = $setPDO->prepare($standingslevelstart);
	$StandingsGroupFetch->bindParam(':seasonid', $currentseason, PDO::PARAM_INT);
	if ($currentlevel != 0)
	{
		$StandingsGroupFetch->bindParam(':levelid', $currentlevel, PDO::PARAM_INT);
	}
	$StandingsGroupFetch->execute();

	$StandingGroupSQLcount = $StandingsGroupFetch->rowCount();
	#echo 'Standings Count = '.$StandingGroupSQLcount;

	while ($levelrow = $StandingsGroupFetch->fetch(PDO::FETCH_ASSOC))
	{
		#$levelcontainer = '<h1>'.$levelrow['Level'].'</h1>';
		#Query to create list of possible subseasons per level
		$Subseasonstart = 'SELECT DISTINCT idsubseasonkey, SubSeasonName, DivisionsNumber, GamesRegularSeason, PlayoffsClinch, Wildcards, PlayoffDetails FROM SeasonLevels JOIN subseason ON SeasonLevels.idsubseasonkey = subseason.idsubseason WHERE idSeason = :seasonid AND idLevel = :levelid AND (StartDate <= CURDATE() OR StartDate IS NULL)';
		if ($currentsubseason != 0)
			{$Subseasonstart .= ' AND idsubseasonkey = :idsubseason';}
		$Subseasonend = ' ORDER BY SortOrder DESC';
		$SubseasonSQL = $setPDO->prepare($Subseasonstart.$Subseasonend);
		$SubseasonSQL->bindParam(':seasonid', $currentseason, PDO::PARAM_INT);
		$SubseasonSQL->bindParam(':levelid', $levelrow['idLevel'], PDO::PARAM_INT);
		if ($currentsubseason != 0) 
		{
			$SubseasonSQL->bindParam(':idsubseason', $currentsubseason, PDO::PARAM_INT);
		}
		$SubseasonSQL->execute();
		
		$SubseasonSQLcount = $SubseasonSQL->rowCount();
		#echo 'Subseason Count = '.$SubseasonSQLcount;
		$sublevel = array();
		while ($subseasonrow = $SubseasonSQL->fetch(PDO::FETCH_ASSOC))
		{	
			#Fetch any divisions
			$standingsfinddiv = 'SELECT DISTINCT TeamDivision FROM teamstatassignment JOIN teamassignment ON teamstatassignment.idTeamAssignmentkey = teamassignment.idTeamAssignment WHERE idSeasonkey = :seasonid AND idLevelSeasonkey = :levelid AND idsubseasonkey = :idsubseason';
			
			#if division is specified
			if (!empty($currentdivision)) {$standingsfinddiv .= ' AND TeamDivision = :divid';}
			
			$standingsdivfetch = $setPDO->prepare($standingsfinddiv);
			$standingsdivfetch->bindParam(':seasonid', $currentseason, PDO::PARAM_INT);
			$standingsdivfetch->bindParam(':levelid', $levelrow['idLevel'], PDO::PARAM_INT);
			$standingsdivfetch->bindParam(':idsubseason', $subseasonrow['idsubseasonkey'], PDO::PARAM_INT);
			if (!empty($currentdivision)) {$standingsdivfetch->bindParam(':divid', $currentdivision, PDO::PARAM_STR);}
			$standingsdivfetch->execute();
			$standingsdivcount = $standingsdivfetch->rowCount();
			#echo 'Standings DIV Count = '.$standingsdivcount;
			
			
			if ($standingsdivcount > 0) #Check if subseason+divison is viable
				{
				
				$subseasoncontainer = '<h2>'.$subseasonrow['SubSeasonName'].'</h2>';
				
				while ($divisionrow = $standingsdivfetch->fetch(PDO::FETCH_ASSOC))
					{
					$standingsTableArray = array();
						
					#Team-by-Team Standings Query Builder
					$StandingsSectionSQL = 'SELECT idTeamAssignment, TeamDivision, TeamName, teamPrefix, TeamGamesPlayed, TeamWins, TeamLoss, TeamTie, TeamOTLoss, TeamPts, TeamGoals, TeamGoalsAgainst, TeamShots, TeamShotsAgainst, TeamPIM, teamPlayoffMarker, externalLargeImage, cssCustom, imageForceWhiteBackground, teamCurrentStreak FROM teamassignment JOIN teamstatassignment ON teamassignment.idTeamAssignment = teamstatassignment.idTeamAssignmentkey LEFT JOIN jjglover_GLSHockey_NewsCss.cssteamassignment ON idTeamAssignmentkey = cssteamassignment.TeamidRef AND jjglover_GLSHockey_NewsCss.cssteamassignment.TeamtableRef = "teamassignment" JOIN team ON teamassignment.idTeamkey = team.idTeam WHERE idSeasonkey =:seasonid AND idsubseasonkey = :subseasonid AND idLevelSeasonkey = :levelid';

					if (!empty($divisionrow['TeamDivision']))
						{$StandingsSectionSQL .= ' AND TeamDivision LIKE :divisionid'; }
				
					$StandingsSectionSQL .= ' AND ((teamstatassignment.teamStartDate IS NULL) OR (CURDATE() BETWEEN teamstatassignment.teamStartDate AND teamstatassignment.teamEndDate) OR (CURDATE() >= teamstatassignment.teamStartDate AND teamstatassignment.teamEndDate IS NULL))  ORDER BY TeamPts DESC, teamPlayoffMarker DESC, TeamGamesPlayed ASC, TeamWins DESC, TeamLoss ASC, teamPrefix';
					$StandingsFetch = $setPDO->prepare($StandingsSectionSQL);
					$StandingsFetch->bindParam(':seasonid', $currentseason, PDO::PARAM_INT);
					$StandingsFetch->bindParam(':subseasonid', $subseasonrow['idsubseasonkey'], PDO::PARAM_INT);
					$StandingsFetch->bindParam(':levelid', $levelrow['idLevel'], PDO::PARAM_INT);
				
					if (!empty($divisionrow['TeamDivision']))
						{$StandingsFetch->bindParam(':divisionid', $divisionrow['TeamDivision'], PDO::PARAM_STR); }
					$StandingsFetch->execute();
					
					$standingsTableArray += [
						'tableclass' => null,
						'linkslist' => array(array('link' => 'team?teamid=', 'linktarget' => 'teamid', 'linkname' => 'Team')), 
						'imagelist' => array(array('image'=>'teamimage', 'imagetarget'=>'Team')),
						'tableid' => null,
						'priority' => null, 
						'subseason' => $subseasonrow['SubSeasonName'],
						'division' => $divisionrow['TeamDivision']
						];

					$standingsDataArray = array();
					$currentstanding = 0;
					$MagicNumber = 0;
					$gamesseason = $subseasonrow['GamesRegularSeason'];
					$TeamsPlayoffs = 0;
					$lastPlayoffTeam = 0;
					#If there is a certain number advancing to the next round, adds a Magic Number
					while($Standingsrow = $StandingsFetch->fetch(PDO::FETCH_ASSOC)) {
						
						#Increases standing by 1 for every row
						$currentstanding++;
						#If a 'z - ' is detected in playoff marker, that team is not participating in a normal playoff and is excluded
						if ($Standingsrow['teamPlayoffMarker'] == 'z - ')
							{$currentstanding--;}
						#When the current standing is beyond a playoff team, potential points is calculated for that team. The highest value from these teams is a Magic Number
						if ($subseasonrow['PlayoffsClinch'] == $currentstanding) {
							$lastPlayoffTeam = $Standingsrow['TeamPts']; 
						}
						if ($subseasonrow['PlayoffsClinch']+1 <= $currentstanding) 
							{ $PotentialPoints = (($gamesseason - $Standingsrow['TeamGamesPlayed'])*2)+$Standingsrow['TeamPts'];
								if ($lastPlayoffTeam >= $PotentialPoints && $lastPlayoffTeam > $MagicNumber) {
									$MagicNumber = $lastPlayoffTeam;
								} elseif ($PotentialPoints >= $MagicNumber)
									{$MagicNumber = $PotentialPoints+1;}
							}
						#Adds one for each team clinched for playoffs.  Used below to determine if a magic number is needed
						if ($Standingsrow['teamPlayoffMarker'] == 'x - ' || $Standingsrow['teamPlayoffMarker'] == 'y - ')
							{$TeamsPlayoffs++;}	

												
						if ($subseasonrow['idsubseasonkey'] == 1) {
							$currentStreak = $Standingsrow['teamCurrentStreak'];
						} else {$currentStreak = null;}

						$teamName = $Standingsrow['TeamName'];
						if (!empty($Standingsrow['cssCustom'])) {$cssTheme = $Standingsrow['cssCustom'];} else {$cssTheme = '';}
						if (!empty($Standingsrow['teamPlayoffMarker'])) {$teamName = $Standingsrow['teamPlayoffMarker'].' '.$teamName;}
						if (!empty($Standingsrow['teamPrefix'])) {$teamName = '('.$Standingsrow['teamPrefix'].') '.$teamName;}

						$standingsData = array(
							'teamid' => $Standingsrow['idTeamAssignment'], 
							'teamimage' => $Standingsrow['externalLargeImage'],
							'TeamTheme' => $cssTheme,
							'TeamWhiteBackground' => $Standingsrow['imageForceWhiteBackground'],
							'Team' => $teamName, 
							'GP' => $Standingsrow['TeamGamesPlayed'], 
							'W' => $Standingsrow['TeamWins'],
							'L' => $Standingsrow['TeamLoss'],
							'T' => $Standingsrow['TeamTie'], 
							'OTL' => $Standingsrow['TeamOTLoss'],
							'Pts' => $Standingsrow['TeamPts'],
							'GF' => $Standingsrow['TeamGoals'],
							'GA' => $Standingsrow['TeamGoalsAgainst'],
							'SF' => $Standingsrow['TeamShots'],
							'SA' => $Standingsrow['TeamShotsAgainst'],
							'PIM' => $Standingsrow['TeamPIM'],
							'Streak' => $currentStreak
						);

						
						$standingsDataArray[] = $standingsData;
					}

			#If in the regular season, add playoff information to column on the right
				#Adds Magic number if there are teams to clinch and not all teams are determined
				if ($subseasonrow['PlayoffsClinch'] > 0 AND $subseasonrow['idsubseasonkey'] == 1)
					{$magicNumber = 'Magic Number to Clinch Division Playoff Spot: '.$MagicNumber;} else {$magicNumber = null;}
				
				$standingsTableArray += [
					'dataarray' => $standingsDataArray,
					'playoffkey' => $magicNumber,
					'playoffdetails' => $subseasonrow['PlayoffDetails']
				];

				$sublevel[] = $standingsTableArray;
				}
			}
		}
		$outputArray[] = array(
			'level'=> $levelrow['Level'],
			'datalevel' => $sublevel
		);
	}
return $outputArray;
}

$JavascriptTablesort = '
<script>$(document).ready(function() 
    { 
        $("#standings").tablesorter(); 
    } 
)</script>';

$getStandings = JSONfullStandings();

echo json_encode($getStandings);

?>