<?php 

include_once 'connection.php';

#include 'header.php';
#include 'html.php';

/*Initial player goal streak query
SELECT game.idGame, game.GameDate, game.GameStartTime, PlayerAssignmentKey, IF(Goals IS NULL, 0, Goals) AS Goal, IF(Assists IS NULL, 0, Assists) AS Assist
FROM jjglover_glshockey.game JOIN jjglover_glshockey.gameattendance ON game.idGame = gameattendance.idGamekey
LEFT JOIN (SELECT idGamekey AS idGame, GoalScorer, COUNT(goalevent.idGameEvents) AS Goals
	FROM jjglover_glshockey.goalevent 
		JOIN jjglover_glshockey.gameevents ON goalevent.idGameEvents = gameevents.idGameEvents
	WHERE GoalScorer is not null and GoalScorer > 0
	GROUP BY idGame, GoalScorer) AS goalCount 
	ON goalCount.idGame = game.idGame AND goalCount.GoalScorer = gameattendance.PlayerAssignmentKey
LEFT JOIN (SELECT idGame, PlayerAssist, COUNT(idGameEvents) AS Assists 
		FROM (
			SELECT idGamekey AS idGame, "Assist", goalevent.idGameEvents, PlayerAssist
				FROM jjglover_glshockey.goalevent 
					JOIN jjglover_glshockey.gameevents ON goalevent.idGameEvents = gameevents.idGameEvents 
			WHERE PlayerAssist is not null and PlayerAssist > 0
			UNION ALL
			SELECT idGamekey AS idGame, "Assist", goalevent.idGameEvents, PlayerAssist2
				FROM jjglover_glshockey.goalevent 
					JOIN jjglover_glshockey.gameevents ON goalevent.idGameEvents = gameevents.idGameEvents
				WHERE PlayerAssist2 is not null and PlayerAssist2 > 0
				)
		AS Assist
		GROUP BY idGame, PlayerAssist) AS assistCount
		ON assistCount.idGame = game.idGame AND assistCount.PlayerAssist = gameattendance.PlayerAssignmentKey
WHERE Attend = 1;*/


##Gets necessary starting steps
$currentteam = ( isset( $_GET['teamid'] ) && is_numeric( $_GET['teamid'] ) ) ? intval( $_GET['teamid'] ) : 0;
$currentlevel = ( isset( $_GET['levelid'] ) && is_numeric( $_GET['levelid'] ) ) ? intval( $_GET['levelid'] ) : 0;
$currentdivision = isset($_GET['divid']) ? $_GET['divid'] : NULL;
$currentseason = ( isset( $_GET['seasonid'] ) && is_numeric( $_GET['seasonid'] ) ) ? intval( $_GET['seasonid'] ) : 0;
$currentsubseason = ( isset( $_GET['subseasonid'] ) && is_numeric( $_GET['subseasonid'] ) ) ? intval( $_GET['subseasonid'] ) : 0;
$currentgoalie =  isset( $_GET['goalie'] ) ? $_GET['goalie'] : "Skater";
$subgoalie = ( isset( $_GET['subgoalie'] ) && is_numeric( $_GET['subgoalie'] ) ) ? intval( $_GET['subgoalie'] ) : 0;
$pageselect = ( isset( $_GET['page'] ) && is_numeric( $_GET['page'] ) ) ? intval( $_GET['page'] ) : 1;
$sortcondition = isset($_GET['sort']) ? $_GET['sort'] : NULL;
$currentgroup = 'seasonsubseason';

function Createlink($array, $omit) {
	$setlink = '';
	$uniqueelement = 0;
	
	foreach($array as $var => $var_value) {
		if(!empty($var_value) && $var != $omit) {
			$uniqueelement ++;
			if($uniqueelement >1)
			{
				$setlink .= '&';
			}
			$setlink .= $var.'='.$var_value;
		}
	}
	return $setlink;
}

function setPage($countSQL, $link, $page) {
$pdoConnect = createDBH();

$currentteam = ( isset( $_GET['teamid'] ) && is_numeric( $_GET['teamid'] ) ) ? intval( $_GET['teamid'] ) : 0;
$currentlevel = ( isset( $_GET['levelid'] ) && is_numeric( $_GET['levelid'] ) ) ? intval( $_GET['levelid'] ) : 0;
$currentdivision = isset($_GET['divid']) ? $_GET['divid'] : NULL;
$currentseason = ( isset( $_GET['seasonid'] ) && is_numeric( $_GET['seasonid'] ) ) ? intval( $_GET['seasonid'] ) : 0;
$currentsubseason = ( isset( $_GET['subseasonid'] ) && is_numeric( $_GET['subseasonid'] ) ) ? intval( $_GET['subseasonid'] ) : 0;
$currentgoalie = ( isset( $_GET['goalie'] ) && is_numeric( $_GET['goalie'] ) ) ? intval( $_GET['goalie'] ) : 0;

	$Maxrecord = $pdoConnect->prepare($countSQL);
	if ($currentseason != 0) 
	{
		$Maxrecord->bindParam(':idseason', $currentseason, PDO::PARAM_INT);
	}
	elseif ($currentteam != 0)
	{
		$Maxrecord->bindParam(':teamid', $currentteam, PDO::PARAM_INT);
	}
	if ($currentsubseason != 0)
	{
		$Maxrecord->bindParam(':idsubseason', $currentsubseason, PDO::PARAM_INT);
	}
	if ($currentlevel != 0)
	{
		$Maxrecord->bindParam(':idlevel', $currentlevel, PDO::PARAM_INT);
	}
	if (!empty($currentdivision))
	{
		$Maxrecord->bindParam(':division', $currentdivision, PDO::PARAM_STR);
	}
	$Maxrecord->execute();
	$MaxRecordset = $Maxrecord->rowcount();
	if ($MaxRecordset >25)
	{
		$PageMax = round($MaxRecordset/25) + 1;
		$pageset = '<div class="sqlnav">
		<a href="playerstats.php?'.$link.'&page=1">First </a>|';
		if ($page-1 >= 1) {
		$pageset .= '<a href="playerstats.php?'.$link.'&page='.($page-1).'"> Previous </a>|';
		}
		if ($page+1 <= $PageMax) {
		$pageset .= '<a href="playerstats.php?'.$link.'&page='.($page+1).'"> Next </a>|';
		}
		$pageset .= '<a href="playerstats.php?'.$link.'&page='.$PageMax.'"> Last</a>';
		$pageset .= '</div>';
	} else {$pageset = '';}
	return $pageset;
}

function assemblesortmenu($goalie, $link, $currentsort) {
	$pdoConnect = createDBH();
	
	$currentgoalie = ( isset( $_GET['goalie'] ) && is_numeric( $_GET['goalie'] ) ) ? intval( $_GET['goalie'] ) : 0;
	
	$Sortmenustart = $pdoConnect->prepare('SELECT TargetSQL, StatShort FROM SortingStatTable WHERE Goalie = :goalieset ORDER BY SortPriority ASC');
	$Sortmenustart->bindParam(':goalieset', $currentgoalie, PDO::PARAM_INT);
	$Sortmenustart->execute();
	$Sortingmenu = '';
	while($rowsort = $Sortmenustart->fetch(PDO::FETCH_ASSOC))
	{
		if ($rowsort['StatShort'] != $currentsort){
		$Sortingmenu .= '<a href="playerstats.php?'.$link.'&sort='.$rowsort['StatShort'].'"> ';}
		if ($rowsort['StatShort'] == $currentsort) {
		$Sortingmenu .= '<b>'.$rowsort['StatShort'].'</b>';}
		else {$Sortingmenu .= $rowsort['StatShort'];}
		if ($rowsort['StatShort'] != $currentsort){
			$Sortingmenu .= '</a>';
		}
		$Sortingmenu .= ' | ';
	}
	return $Sortingmenu;
}

function sortinghandle($goalie, $target) {
	$pdoConnect = createDBH();

	$currentgoalie = ( isset( $_GET['goalie'] ) && is_numeric( $_GET['goalie'] ) ) ? intval( $_GET['goalie'] ) : 0;
	
	$sortcondition = isset($_GET['sort']) ? $_GET['sort'] : NULL;
	$Sortmenufetch = $pdoConnect->prepare('SELECT TargetSQL FROM SortingStatTable WHERE Goalie = :goalieset AND StatShort = :selectsort');
	$Sortmenufetch->bindParam(':goalieset', $goalie, PDO::PARAM_INT);
	$Sortmenufetch->bindParam(':selectsort', $target, PDO::PARAM_STR);
	$Sortmenufetch->execute();
	$SortTargetfetch = $Sortmenufetch->fetch(PDO::FETCH_ASSOC);	
	return $SortTargetfetch['TargetSQL'];
}

$SQLWhere = '';
$SQLGroup = ') GROUP BY playerassignid LIMIT 25 OFFSET :page';

if ($currentseason != 0) 
{
	$SQLWhere .= ' WHERE idSeasonkey = :idseason';
}
elseif ($currentteam != 0)
{
	$SQLWhere .= ' WHERE teamassignment.idTeamAssignment = :teamid';
}
if ($currentsubseason != 0)
{
	$SQLWhere .= ' AND idsubseasonkey = :idsubseason';
}
if ($currentlevel != 0)
{
	$SQLWhere .= ' AND idLevelSeasonkey = :idlevel';
}
if (!empty($currentdivision))
{
	$SQLWhere .= ' AND TeamDivision = :division';
}
#Set Query for Team

function SetMenuSubseason($startlink) {
$pdoConnect = createDBH();

$currentseason = ( isset( $_GET['seasonid'] ) && is_numeric( $_GET['seasonid'] ) ) ? intval( $_GET['seasonid'] ) : 0;
$currentteam = ( isset( $_GET['teamid'] ) && is_numeric( $_GET['teamid'] ) ) ? intval( $_GET['teamid'] ) : 0;
$currentlevel = ( isset( $_GET['levelid'] ) && is_numeric( $_GET['levelid'] ) ) ? intval( $_GET['levelid'] ) : 0;

$Subseasonfetchstart = 'SELECT DISTINCT idSubseason, SubSeasonName FROM teamassignment JOIN teamstatassignment ON teamassignment.idTeamAssignment = teamstatassignment.idTeamAssignmentkey JOIN subseason ON teamstatassignment.idsubseasonkey = subseason.idsubseason';

$SetSQLWhere = '';
if ($currentseason != 0) 
{
	$SetSQLWhere .= ' WHERE idSeasonkey = :idseason';
}
if ($currentlevel != 0)
{
	$SetSQLWhere .= ' AND idLevelSeasonkey = :idlevel';
}
elseif ($currentteam != 0)
{
	$SetSQLWhere .= ' WHERE teamassignment.idTeamAssignment = :teamid';
}
$SetSQLEnd = ' ORDER BY SortOrder';
$Subseasonfetch = $pdoConnect->prepare($Subseasonfetchstart.$SetSQLWhere.$SetSQLEnd);
if ($currentseason != 0) 
{
	$Subseasonfetch->bindParam(':idseason', $currentseason, PDO::PARAM_INT);
}
if ($currentlevel != 0) 
{
	$Subseasonfetch->bindParam(':idlevel', $currentlevel, PDO::PARAM_INT);
}
elseif ($currentteam != 0)
{
	$Subseasonfetch->bindParam(':teamid', $currentteam, PDO::PARAM_INT);
}
$Subseasonfetch->execute();
$CountSubseason = $Subseasonfetch->rowCount();
if ($CountSubseason > 1) {
	$SubseasonSelect = '<div id=SubseasonSelect">';
	while ($subseason = $Subseasonfetch->fetch(PDO::FETCH_ASSOC)) {
	$SubseasonSelect .= '<a href="playerstats.php?'.$startlink.'&subseasonid='.$subseason['idSubseason'].'">'.$subseason['SubSeasonName'].'</a> | ';
	}
	$SubseasonSelect .= '</div>';
}
return $SubseasonSelect;
}

function PlayerStatAssembly($limit, $sort, $group, $currentlink, $currentpage) {
$pdoConnect = createDBH();

$currentteam = ( isset( $_GET['teamid'] ) && is_numeric( $_GET['teamid'] ) ) ? intval( $_GET['teamid'] ) : 0;
$currentlevel = ( isset( $_GET['levelid'] ) && is_numeric( $_GET['levelid'] ) ) ? intval( $_GET['levelid'] ) : 0;
$currentdivision = isset($_GET['divid']) ? $_GET['divid'] : NULL;
$currentseason = ( isset( $_GET['seasonid'] ) && is_numeric( $_GET['seasonid'] ) ) ? intval( $_GET['seasonid'] ) : 0;
$currentsubseason = ( isset( $_GET['subseasonid'] ) && is_numeric( $_GET['subseasonid'] ) ) ? intval( $_GET['subseasonid'] ) : 0;
$currentgoalie = ( isset( $_GET['goalie'] ) && is_numeric( $_GET['goalie'] ) ) ? intval( $_GET['goalie'] ) : 0;

if ($currentlevel != 0) {
	$SQLWhere = ' WHERE idTeamAssignment IN (SELECT DISTINCT idteamassignmentkey FROM teamstatassignment';
	$SQLSubseasonSelector = ') ';
} else {
	$SQLWhere = '';
	$SQLSubseasonSelector = ' ';
}

$SQLGroup = 'GROUP BY playerassignid';
if ($group == 'season') {
	$SQLGroup .= ', idSeasonkey';
} elseif ($group == 'subseason') {
	$SQLGroup .= ', idsubseasonkey';
} elseif ($group == 'seasonsubseason') {
	$SQLGroup .= ' idSeasonkey, idsubseasonkey';
}
$SQLGroup .= ' HAVING SUM(PlayerGames) > 0';
$SQLLimit = ' LIMIT 25';
$SQLOrderBy = ' ORDER BY '.$sort;
if ($limit > 24)
{
	 $SQLLimit .= ' OFFSET :page';
}
if ($currentseason != 0) 
{
	$SQLWhere .= ' WHERE idSeasonkey = :idseason';
}
elseif ($currentteam != 0)
{
	$SQLWhere .= ' WHERE teamassignment.idTeamAssignment = :teamid';
}
if ($currentsubseason != 0)
{
	if ($currentsubseason == 99) {
		$SQLWhere .= ' AND subseason.Playoff = 1';
		#$SQLSubseasonSelector .= ' AND subseason.Playoff = 1';
	} else {
	$SQLWhere .= ' AND idsubseasonkey = :idsubseason';
	$SQLSubseasonSelector .= ' AND idsubseasonkey = :idsubseason ';
	}
}
if ($currentlevel != 0)
{
	$SQLWhere .= ' AND idLevelSeasonkey = :idlevel';
}
if (!empty($currentdivision))
{
	$SQLWhere .= ' AND TeamDivision = :division';
}

$Playerstatfetchstart = 'SELECT SQL_CALC_FOUND_ROWS DISTINCT idTeamAssignment, externalLargeImage, cssCustom, skaterstat.idPlayerAssignment AS playerassignid, TeamName, PlayerLast, PlayerFirst, PlayerNumber, jjglover_GLSHockey_NewsCss.cssplayerassignment.imagelocation AS PlayerImage, SUM(PlayerGames), SUM(PlayerGoals), SUM(PlayerAssists), SUM(PlayerPoints), SUM(PlayerPIM), SUM(PlayerPN), SUM(PlayerPPG), SUM(PlayerPPP), SUM(PlayerSHG), SUM(PlayerSHP), SUM(PlayerGWG), SUM(PlayerGWP), SUM(PlayerGTG), SUM(PlayerGTP), SUM(PlayerOTG), SUM(PlayerOTP), SUM(PlayerENG), SUM(PlayerENP) FROM skaterstat JOIN playerassignment ON playerassignment.idPlayerAssignment = skaterstat.idPlayerAssignment JOIN players ON playerassignment.idPlayerskey=players.idPlayers JOIN subseason ON skaterstat.idsubseasonkey = subseason.idsubseason JOIN teamassignment ON playerassignment.idTeamAssignmentkey = teamassignment.idTeamAssignment LEFT JOIN jjglover_GLSHockey_NewsCss.cssteamassignment ON teamassignment.idTeamAssignment = cssteamassignment.TeamidRef AND jjglover_GLSHockey_NewsCss.cssteamassignment.TeamtableRef = "teamassignment" JOIN team ON teamassignment.idTeamkey = team.idTeam LEFT JOIN jjglover_GLSHockey_NewsCss.cssplayerassignment ON playerassignment.idPlayerAssignment = cssplayerassignment.PlayeridRef AND jjglover_GLSHockey_NewsCss.cssplayerassignment.PlayertableRef = "playerassignment"';
#$SkaterStatCountSQL = $Playerstatfetchstart.$SQLWhere.$SQLSubseasonSelector.$SQLGroup;
$Playerstatquery = $pdoConnect->prepare($Playerstatfetchstart.$SQLWhere.$SQLSubseasonSelector.$SQLGroup.$SQLOrderBy.$SQLLimit);

if ($currentseason != 0) 
{
	$Playerstatquery->bindParam(':idseason', $currentseason, PDO::PARAM_INT);
}
elseif ($currentteam != 0)
{
	$Playerstatquery->bindParam(':teamid', $currentteam, PDO::PARAM_INT);
}
if ($currentsubseason != 0 && $currentsubseason != 99)
{
	$Playerstatquery->bindParam(':idsubseason', $currentsubseason, PDO::PARAM_INT);
}
if ($currentlevel != 0)
{
	$Playerstatquery->bindParam(':idlevel', $currentlevel, PDO::PARAM_INT);
}
if (!empty($currentdivision))
{
	$Playerstatquery->bindParam(':division', $currentdivision, PDO::PARAM_STR);
}
if ($limit > 24)
{
	$Playerstatquery->bindParam(':page', $limit, PDO::PARAM_INT);
}
$Playerstatquery->execute();
$getTotalRowCount = $pdoConnect->prepare('SELECT FOUND_ROWS()');
$getTotalRowCount->execute();
$TotalPossibleRecords = $getTotalRowCount->fetchColumn();

$TableSortLabel = rtrim($sort, " DESC");

$TeamplayerstatOutput = array();
while($playerOutput = $Playerstatquery->fetch(PDO::FETCH_ASSOC)) {
	if (!empty($playerOutput['cssCustom'])) {$cssTheme = $playerOutput['cssCustom'];} else {$cssTheme = '';}

	$playerOutput += ['Player' => $playerOutput['PlayerNumber'].' '.$playerOutput['PlayerFirst'].' '.$playerOutput['PlayerLast']];


	$TeamplayerstatOutput[] = array('teamid' => $playerOutput['idTeamAssignment'], 'TeamTheme' => $cssTheme, 'playerid' => $playerOutput['playerassignid'], 'Team' => $playerOutput['TeamName'], 'TeamImage' => $playerOutput['externalLargeImage'], 'Player' => $playerOutput['Player'], 'PlayerImage' => $playerOutput['PlayerImage'], 'GP' => $playerOutput['SUM(PlayerGames)'], 'G' => $playerOutput['SUM(PlayerGoals)'], 'A' => $playerOutput['SUM(PlayerAssists)'], 'Pts' => $playerOutput['SUM(PlayerPoints)'], 'PIM' => $playerOutput['SUM(PlayerPIM)'], 'PN' => $playerOutput['SUM(PlayerPN)'], 'PPG' => $playerOutput['SUM(PlayerPPG)'], 'PPP' => $playerOutput['SUM(PlayerPPP)'], 'SHG' => $playerOutput['SUM(PlayerSHG)'], 'SHP' => $playerOutput['SUM(PlayerSHP)'], 'GWG' => $playerOutput['SUM(PlayerGWG)'],  'GWP' => $playerOutput['SUM(PlayerGWP)'],'GTG' => $playerOutput['SUM(PlayerGTG)'], 'GTP' => $playerOutput['SUM(PlayerGTP)'], 'OTG' => $playerOutput['SUM(PlayerOTG)'], 'OTP' => $playerOutput['SUM(PlayerOTP)'], 'ENG' => $playerOutput['SUM(PlayerENG)'], 'ENP' => $playerOutput['SUM(PlayerENP)']);
}

return array('TotalRecords'=> round($TotalPossibleRecords/25), 'Records'=>$TeamplayerstatOutput);
}

function GoalieStatAssembly($limit, $sort, $group, $currentlink, $currentpage) {
$pdoConnect = createDBH();

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

if ($currentlevel != 0) {
	$SQLWhere = ' WHERE idTeamAssignment IN (SELECT DISTINCT idteamassignmentkey FROM teamstatassignment';
	$SQLSubseasonSelector = ') ';
} else {
	$SQLWhere = '';
	$SQLSubseasonSelector = ' ';
}

$SQLGroup = 'GROUP BY playerassignid';
if ($group == 'season') {
	$SQLGroup .= ', idSeasonkey';
} elseif ($group == 'subseason') {
	$SQLGroup .= ', idsubseasonkey';
} elseif ($group == 'seasonsubseason') {
	$SQLGroup .= ' idSeasonkey, idsubseasonkey';
}
$SQLGroup .= ' HAVING SUM(GoalieGames) > 0';
$SQLLimit = ' LIMIT 25';
$SQLOrderBy = ' ORDER BY '.$sort;
if ($limit > 24)
{
	 $SQLLimit .= ' OFFSET :page';
}

if ($currentseason != 0) 
{
	$SQLWhere .= ' WHERE idSeasonkey = :idseason';
}
elseif ($currentteam != 0)
{
	$SQLWhere .= ' WHERE teamassignment.idTeamAssignment = :teamid';
	$subgoalie = 2;
}
if ($currentsubseason != 0)
{
	if ($currentsubseason == 99) {
		$SQLWhere .= ' AND subseason.Playoff = 1';
		#$SQLSubseasonSelector .= ' AND subseason.Playoff = 1';
	} else {
	$SQLWhere .= ' AND idsubseasonkey = :idsubseason';
	$SQLSubseasonSelector .= ' AND idsubseasonkey = :idsubseason ';
	}
}
if ($currentlevel != 0)
{
	$SQLWhere .= ' AND idLevelSeasonkey = :idlevel';
}
if (!empty($currentdivision))
{
	$SQLWhere .= ' AND TeamDivision = :division';
}

if(!isset($subgoalie)) {
	$subgoalie = ( isset( $_GET['subgoalie'] ) && is_numeric( $_GET['subgoalie'] ) ) ? intval( $_GET['subgoalie'] ) : 0;
}

if ($subgoalie == 0) {$SQLWhere .= ' AND (PlayerStatus <> "Sub Goalie" OR PlayerStatus IS NULL)';}
elseif ($subgoalie == 1) {$SQLWhere .= ' AND PlayerStatus = "Sub Goalie"';}
elseif ($subgoalie == 2) {$SQLWhere .= '';}
	
$GoaliePlayerStatSQL = 'SELECT SQL_CALC_FOUND_ROWS idTeamAssignment, externalSmallImage, cssCustom, playerassignment.idPlayerAssignment AS playerassignid, TeamName, PlayerLast, PlayerFirst, Playernumber, jjglover_GLSHockey_NewsCss.cssplayerassignment.imagelocation AS PlayerImage, SUM(GoalieGames), SUM(GoalieWins), SUM(GoalieLosses), SUM(GoalieTies), SUM(GoalieOTL), SUM(GoalieShotsAgainst), (SUM(GoalieShotsAgainst)-SUM(GoalieGoalsAllowed)) AS Save, SUM(GoalieGoalsAllowed), Round(((SUM(GoalieShotsAgainst)-SUM(GoalieGoalsAllowed))/SUM(GoalieShotsAgainst)),3) AS SaveP, Round(SUM(GoalieGoalsAllowed)/SUM(GoalieGames),2) AS GAA, Round(((SUM(GoalieGoalsAllowed)-SUM(GoalieGoalsPP)-SUM(GoalieGoalsSH))/SUM(GoalieGames)),2) AS GAAEven, SUM(GoalieGoalsPP), SUM(GoalieGoalsSH), SUM(GoalieShutout) FROM goaliestat JOIN playerassignment ON goaliestat.idPlayerAssignment = playerassignment.idPlayerAssignment JOIN players ON playerassignment.idPlayerskey=players.idPlayers JOIN subseason ON goaliestat.idsubseasonkey = subseason.idsubseason JOIN teamassignment ON playerassignment.idTeamAssignmentkey = teamassignment.idTeamAssignment LEFT JOIN jjglover_GLSHockey_NewsCss.cssteamassignment ON teamassignment.idTeamAssignment = cssteamassignment.TeamidRef AND jjglover_GLSHockey_NewsCss.cssteamassignment.TeamtableRef = "teamassignment" JOIN team ON teamassignment.idTeamkey = team.idTeam LEFT JOIN jjglover_GLSHockey_NewsCss.cssplayerassignment ON playerassignment.idPlayerAssignment = cssplayerassignment.PlayeridRef AND jjglover_GLSHockey_NewsCss.cssplayerassignment.PlayertableRef = "playerassignment"';
$SetGoalieCount = $GoaliePlayerStatSQL.$SQLWhere.$SQLSubseasonSelector.$SQLGroup;
$GoaliePlayerFetch = $pdoConnect->prepare($GoaliePlayerStatSQL.$SQLWhere.$SQLSubseasonSelector.$SQLGroup.$SQLOrderBy.$SQLLimit);
#echo $GoaliePlayerStatSQL.$SQLWhere.$SQLSubseasonSelector.$SQLGroup.$SQLOrderBy.$SQLLimit;
if ($currentseason != 0) 
{
	$GoaliePlayerFetch->bindParam(':idseason', $currentseason, PDO::PARAM_INT);
}
elseif ($currentteam != 0)
{
	$GoaliePlayerFetch->bindParam(':teamid', $currentteam, PDO::PARAM_INT);
}
if ($currentsubseason != 0 && $currentsubseason != 99)
{
	$GoaliePlayerFetch->bindParam(':idsubseason', $currentsubseason, PDO::PARAM_INT);
}
if ($currentlevel != 0)
{
	$GoaliePlayerFetch->bindParam(':idlevel', $currentlevel, PDO::PARAM_INT);
}
if (!empty($currentdivision))
{
	$GoaliePlayerFetch->bindParam(':division', $currentdivision, PDO::PARAM_STR);
}
if ($limit > 24)
{
	 $GoaliePlayerFetch->bindParam(':page', $limit, PDO::PARAM_INT);
}
$GoaliePlayerFetch->execute();

$getTotalRowCount = $pdoConnect->prepare('SELECT FOUND_ROWS()');
$getTotalRowCount->execute();
$TotalPossibleRecords = $getTotalRowCount->fetchColumn();

#$CurrentNav = setPage($SetGoalieCount, $currentlink, $currentpage);
$TableSortLabel = rtrim($sort, " DESC");

$TeamgoaliestatOutput = array();
while($goalieOutput = $GoaliePlayerFetch->fetch(PDO::FETCH_ASSOC)) {
	if (!empty($goalieOutput['cssCustom'])) {$cssTheme = $goalieOutput['cssCustom'];} else {$cssTheme = '';}

	$goalieOutput += ['Player' => $goalieOutput['Playernumber'].' '.$goalieOutput['PlayerFirst'].' '.$goalieOutput['PlayerLast']];


	$TeamgoaliestatOutput[] = array('teamid' => $goalieOutput['idTeamAssignment'], 'TeamTheme' => $cssTheme, 'playerid' => $goalieOutput['playerassignid'], 'Team' => $goalieOutput['TeamName'], 'TeamImage' => $goalieOutput['externalSmallImage'], 'Player' => $goalieOutput['Player'], 'PlayerImage' => $goalieOutput['PlayerImage'], 'GP' => $goalieOutput['SUM(GoalieGames)'], 'W' => $goalieOutput['SUM(GoalieWins)'], 'L' => $goalieOutput['SUM(GoalieLosses)'], 'T' => $goalieOutput['SUM(GoalieTies)'], 'OTL' => $goalieOutput['SUM(GoalieOTL)'], 'SA' => $goalieOutput['SUM(GoalieShotsAgainst)'], 'SV' => $goalieOutput['Save'], 'GA' => $goalieOutput['SUM(GoalieGoalsAllowed)'], 'Save%' => $goalieOutput['SaveP'], 'GAA' => $goalieOutput['GAA'], 'GAA Even' => $goalieOutput['GAAEven'],  'GA PP' => $goalieOutput['SUM(GoalieGoalsPP)'],'GA SH' => $goalieOutput['SUM(GoalieGoalsSH)'], 'Shutouts' => $goalieOutput['SUM(GoalieShutout)']);
}

return array('TotalRecords'=> round($TotalPossibleRecords/25), 'Records'=> $TeamgoaliestatOutput);
}

function JSONSetMenuSubseason() {
	$pdoConnect = createDBH();
	
	$currentseason = ( isset( $_GET['seasonid'] ) && is_numeric( $_GET['seasonid'] ) ) ? intval( $_GET['seasonid'] ) : 0;
	$currentteam = ( isset( $_GET['teamid'] ) && is_numeric( $_GET['teamid'] ) ) ? intval( $_GET['teamid'] ) : 0;
	$currentlevel = ( isset( $_GET['levelid'] ) && is_numeric( $_GET['levelid'] ) ) ? intval( $_GET['levelid'] ) : 0;
	$currentdivision = isset($_GET['divid']) ? $_GET['divid'] : NULL;

	$Subseasonfetchstart = 'SELECT DISTINCT idSubseason, SubSeasonName, Playoff FROM teamassignment JOIN teamstatassignment ON teamassignment.idTeamAssignment = teamstatassignment.idTeamAssignmentkey JOIN subseason ON teamstatassignment.idsubseasonkey = subseason.idsubseason';
	
	$SetSQLWhere = '';
	if ($currentseason != 0) 
	{
		$SetSQLWhere .= ' WHERE idSeasonkey = :idseason';
	}
	if ($currentlevel != 0)
	{
		$SetSQLWhere .= ' AND idLevelSeasonkey = :idlevel';
	}
	elseif ($currentteam != 0)
	{
		$SetSQLWhere .= ' WHERE teamassignment.idTeamAssignment = :teamid';
	}
	if (!empty($currentdivision)) 
	{
		$SetSQLWhere .= ' AND TeamDivision = :division';
	}
	$SetSQLEnd = ' ORDER BY SortOrder';

	$Subseasonfetch = $pdoConnect->prepare($Subseasonfetchstart.$SetSQLWhere.$SetSQLEnd);
	if ($currentseason != 0) 
	{
		$Subseasonfetch->bindParam(':idseason', $currentseason, PDO::PARAM_INT);
	}
	if ($currentlevel != 0) 
	{
		$Subseasonfetch->bindParam(':idlevel', $currentlevel, PDO::PARAM_INT);
	}
	elseif ($currentteam != 0)
	{
		$Subseasonfetch->bindParam(':teamid', $currentteam, PDO::PARAM_INT);
	}
	if (!empty($currentdivision)) 
	{
		$Subseasonfetch->bindParam(':division', $currentdivision, PDO::PARAM_STR);
	}
	$Subseasonfetch->execute();
	$CountSubseason = $Subseasonfetch->rowCount();
	$optionsList = array();
	if ($CountSubseason > 1) {
		
		$RegularSeason = 0;
		$Playoffs = 0;

		while ($subseason = $Subseasonfetch->fetch(PDO::FETCH_ASSOC)) {
			if ($RegularSeason == 0 && $subseason['idSubseason'] == 1) {
				$RegularSeason = 1;
			} 
			if ($Playoffs == 0 && $subseason['Playoff'] == 1) {
				$Playoffs = 1;
				$optionsList[] = array('value' => '99', 'text' => 'Playoffs');
				if ($RegularSeason == 1) {
					array_unshift($optionsList, array('value' => '0', 'text' => 'Overall'));
				}
			}
			$optionsList[] = array('value'=> $subseason['idSubseason'], 'text' => $subseason['SubSeasonName']);
		}
	} 
	return $optionsList;
	}

function JSONassemblesortmenu($goalie) {
	$pdoConnect = createDBH();
	
	$Sortmenustart = $pdoConnect->prepare('SELECT StatShort, StatFullName FROM SortingStatTable WHERE Goalie = :goalieset ORDER BY SortPriority ASC');
	$Sortmenustart->bindParam(':goalieset', $goalie, PDO::PARAM_INT);
	$Sortmenustart->execute();
	$Sortingmenu = array();
	while($SortItem = $Sortmenustart->fetch(PDO::FETCH_ASSOC)) {
		$Sortingmenu[] = array('value' => $SortItem['StatShort'], 'text' =>  $SortItem['StatFullName']);
	}
	return $Sortingmenu;
}


#Adjust OFFSET based on page number_format
$Offset = (($pageselect-1)*25);	

if ($currentgoalie=='Skater') {$goalie = 0;}
elseif ($currentgoalie=='Goalie') {$goalie = 1;}
#print_r($goalie);
if ($goalie==0) {
	$sortcondition = isset($_GET['sort']) ? $_GET['sort'] : 'Pts';
	$TargetSort = sortinghandle($goalie, $sortcondition);
	$RetrivedRecords = PlayerStatAssembly($Offset, $TargetSort, 'season', null, $pageselect);
	
	$prepJSONdataArray = array(
		'dataarray' => $RetrivedRecords['Records'],
		'tableid' => 'playerstat',
		'tableclass' => 'tablesorter',
		'tablesort' => $sortcondition,
		'linkslist' => array(array('link'=>'playercard?playerteamid=','linktarget'=>'playerid','linkname'=>'Player'), array('link'=>'team?teamid=','linktarget'=>'teamid','linkname'=>'Team')),
		'imagelist' => array(array('image'=>'TeamImage', 'imagetarget'=>'Team'), array('image'=>'PlayerImage', 'imagetarget'=>'Player')),
		'filterMenu' => JSONassemblesortmenu(0),
		'subseasonMenu' => JSONSetMenuSubseason(),
		'currentPage' => $pageselect,
		'maxPage' => $RetrivedRecords['TotalRecords'],
		'starterSort' => ''
	);
} elseif ($goalie==1) {
	$sortcondition = isset($_GET['sort']) ? $_GET['sort'] : 'GAA';
	$TargetSort = sortinghandle($goalie, $sortcondition);
	$RetrivedRecords = GoalieStatAssembly($Offset, $TargetSort, 'season', null, $pageselect);
	
	$prepJSONdataArray = array(
		'dataarray' => $RetrivedRecords['Records'],
		'tableid' => 'goaliestat',
		'tableclass' => 'tablesorter',
		'tablesort' => $sortcondition,
		'linkslist' => array(array('link'=>'playercard?playerteamid=','linktarget'=>'playerid','linkname'=>'Player'), array('link'=>'team?teamid=','linktarget'=>'teamid','linkname'=>'Team')),
		'imagelist' => array(array('image'=>'TeamImage', 'imagetarget'=>'Team'), array('image'=>'PlayerImage', 'imagetarget'=>'Player')),
		'filterMenu' => JSONassemblesortmenu(1),
		'subseasonMenu' => JSONSetMenuSubseason(),
		'currentPage' => $pageselect,
		'maxPage' => $RetrivedRecords['TotalRecords'],
		'starterSort' => array(array('value'=>'0', 'text' =>'Starters'), array('value'=>'1', 'text' =>'Sub Goalies'), array('value'=>'2', 'text' =>'All Goalies'))
		);
}

echo json_encode($prepJSONdataArray);

?>