<?php
require_once('global.php');
require_once(ABSOLUTE_PATH.'/class/BadgeManager.php');
require_once(ABSOLUTE_PATH.'/class/ChampionHelper.php');
require_once(ABSOLUTE_PATH.'/class/MatchManager.php');
require_once(ABSOLUTE_PATH.'/class/Paginator.php');
require_once(ABSOLUTE_PATH.'/class/StaticHelper.php');
require_once(ABSOLUTE_PATH.'/class/SummonerManager.php');
require_once(ABSOLUTE_PATH.'/class/ToplistManager.php');
require_once(ABSOLUTE_PATH.'/class/Validator.php');
require_once(ABSOLUTE_PATH.'/cache/platforms.php');

$ch = ChampionHelper::getInstance();
$mm = MatchManager::getInstance();
$sh = StaticHelper::getInstance();

/*
$template_content.= '<section id="errorPage">
	<div class="container">
		<br><br><br><br>Summoner pages are currently under maintenance. Please try again later.<br><br><br><br>
	</div>
</section>';
include_once(ABSOLUTE_PATH.'/template.php');
exit;
*/

$error = null;
$displayName = htmlspecialchars($name);
if((empty($name))||(empty($platform))){
	// Bad Request
	$error = '<h2>Bad Request</h2>
				<p>Something went wrong with your search. Please try again.</p>
				<p>If this problem persists for you, please <a href="contact">contact us</a> and let us know what exactly you tried to search.</p>';
}elseif($platform==null){
	// Invalid Region
	$error = '<h2>Invalid Platform</h2>
				<p>You did not select a valid platform.</p>
				<p>Did you follow an invalid link?</p>';
}elseif(!Validator::checkSummonerName($name)){
	// Invalid Summoner Name
	$error = '<h2>Invalid Summoner Name</h2>
				<p>&raquo;'.$displayName.'&laquo; is not a valid summoner name.</p>
				<p class="m-0">Did you misspell the summoner name?</p>
				<p>Did you follow an invalid link?</p>';
}

$updateReply = null;
if($error==null){
	$sm = SummonerManager::getInstance();
	$summoner = $sm->getSummaryData($platform, $name);
	if($summoner==null){
		if($sh->isMatchQueueStatusOk($platform)){
			$updateReply = $sm->update($platform, $name);
			if($updateReply===false){
				$error = '<h2>Summoner Not Found</h2>
							<p>We could not find &raquo;'.$displayName.'&laquo; in the region &raquo;'.$platformName.'&laquo;.</p>
							<p class="m-0">Did you select the wrong region?</p>
							<p>Did you mistype the summoner name?</p>';
			}
			$summoner = $sm->getSummaryData($platform, $name);
		}else{
				$error = '<h2>Server Overload</h2>
							<p>Our servers are currently under heavy load for '.$platformName.'. Updating summoner profiles is currently not available in this region.</p>
							<p>Please try again later.</p>';
		}
	}
	if($summoner==null){
		if($error==null){
			$error = '<h2>Summoner Not Found</h2>
						<p>We could not find &raquo;'.$displayName.'&laquo; in the region &raquo;'.$platformName.'&laquo;.</p>
						<p class="m-0">Did you select the wrong region?</p>
						<p>Did you mistype the summoner name?</p>';
		}
	}else{
		// Fix profiles being stuck in update process
		// If they're stuck for 30+ minutes, treat them as 'done', so we can requeue them
		if($summoner['status']=='updatePending' && strtotime($summoner['lastUpdate']) <= strtotime('-30 minutes')){
			$summoner['status'] = 'done';
		}

		// Build ContentMap
		$contentMap = [
			'summary' => 'Summary',
			'current-game' => 'Current Game'
		];
		$skillScores = $sm->getChampionStats($summoner['id']);
		if($skillScores!=null){
			$contentMap['champions'] = 'Champion Performance';
		}
		$leagueData = $sm->getLeagueData($summoner['id']);
		$contentMap['leagues'] = 'Leagues';
		$rankedStats = $sm->getRankedStats($summoner['id']);
		$queueStats = $sm->getQueueStats($summoner['id']);
		if($rankedStats!=null || $queueStats!=null){
			$contentMap['stats'] = 'Stats';
		}
		$matchList = $mm->getLastMatchesFromDatabase($platform, $summoner['accountId']);
		if($matchList!=null){
			$contentMap['matches'] = 'Matches';
		}
/*
		$runePages = $sm->getRunePages($summoner['id']);
		$masteryPages = $sm->getMasteryPages($summoner['id']);
		if($runePages!=null || $masteryPages!=null){
			$contentMap['runes-and-masteries'] = 'Runes & Masteries';
		}
*/
		if($summoner['stream_platform']!=null){
			$contentMap['stream'] = 'Stream';
		}

		$content = 'summary';
		if(isset($_GET['content']) && isset($contentMap[$_GET['content']])){
			$content = $_GET['content'];
		}
	}
}

if($error!=null){
	// Error Page
	$template_body_class.= 'background-global';
	$template_content = $am->getLeaderboard();
	$template_content.= '	<section id="errorPage">
		<div class="container">
			'.$error.'
		</div>
	</section>';
	$template_content.= $am->getLeaderboard();
#}elseif($summoner['status']=='pending'){
#	// Summoner Profile is pending
#	$template_body_class.= 'background-global';
#	$template_content = $am->getLeaderboard();
#	$template_content.= '	<section id="errorPage">
#		<div class="container">
#			<h2>Summoner Profile pending</h2>
#			<p>This summoner profile is still being initialized. Please try again later.</p>
#		</div>
#	</section>';
#	$template_content.= $am->getLeaderboard();
}else{
	// Success
	$displayName = $summoner['name'];
	$internalName = $summoner['internalName'];
	$champmasteries = $sm->getChampMasteries($summoner['id']);
	
	$summonerOwned = (($um->isUser())&&($thisUser['id']==$summoner['userId']));
	$um->addRecentSummonerToCookie($platform, $displayName);

	$meta_title = $displayName.' &ndash; '.$platformName.' &ndash; Summoner Lookup &ndash; LoLSkill';
	$meta_description = 'Summoner Lookup with statistics, ratings, LoLSkillScore and more for '.$displayName.', a League of Legends summoner on '.$platformName.'.';
	$template_og['url'] = DYNAMIC_PATH.'/summoner/'.strtoupper($platformName).'/'.rawurlencode($displayName);
	$template_og['title'] = $displayName.' &ndash; '.$platformName.' &ndash; Summoner Lookup &ndash; LoLSkill';
	$template_og['image'] = STATIC_PATH.'/img/tiers/192/'.$summoner['tier'].'.png';
	$template_og['description'] = 'Summoner Lookup with statistics, ratings, LoLSkillScore and more for '.$displayName.', a League of Legends summoner on '.$platformName.'.';

	$backgroundChampion = 0;
	if($backgroundChampion==0){
		// If there is no ranked champion, use random champion
		$backgroundChampion = $ch->getRandomChampion();
	}

	$template_content = $am->getLeaderboard();
	$template_content.= '	<section id="summonerProfile">';
	if($um->isModerator()){
		$template_content.= '		<div class="container">
			<div class="alert alert-info">
				<h5>Moderator Information & Actions:</h5>
				Internal SummonerId: '.$summoner['id'].' - Real SummonerId: '.$summoner['summonerId'].' - AccountID: '.$summoner['accountId'].' - Puuid: '.$summoner['puuid'].'<br>
				<button id="forceSummonerUpdate" class="btn btn-outline-primary">Force Update</button>
			</div>
		</div>';
	}
	if(($summoner['background_champion']!==null)&&($summoner['background_skin']!==null)){
		$background = $ch->getSkinImage($summoner['background_champion'], $summoner['background_skin'], 'splash');
	}
	if($sh->isMatchQueueStatusOk($platform) && $summoner['status']=='done' && $sm->isUpdateRequired($platform, $summoner['internalName'])){
		$template_js.= '	<script>
			$(function(){
				updateSummoner(\''.$platform.'\', \''.$displayName.'\', 0);
			});
		</script>';
	}

// Header
	// Roles
	$mainRoles = ['top' => $summoner['role_top'], 'jungle' => $summoner['role_jungle'], 'mid' => $summoner['role_mid'], 'marksman' => $summoner['role_marksman'], 'support' => $summoner['role_support']];
	arsort($mainRoles);
	$roleIcons = '';
	$roleSum = array_sum($mainRoles);
	if($roleSum > 0){
		foreach($mainRoles as $mainRole => $games){
			if($games / $roleSum > 0.15){
				$roleIcons.= '<img class="role tip" src="'.STATIC_PATH.'/img/roles/32/'.strtolower($mainRole).'.png" title="'.ucfirst($mainRole).'" alt="'.ucfirst($mainRole).'">';
			}
		}
	}
	if($roleIcons!=''){
		$rolesOrLevel = ($roleIcons!='') ? '<span class="text-muted">MAINS</span>'.$roleIcons : '';
	}else{
		$rolesOrLevel = '<span class="text-muted">LEVEL '.$summoner['level'].'</span>';
	}

	// Best Champions
	$bestChampions = [];
	if(isset($skillScores) && !empty($skillScores)){
		$i=1;
		foreach($skillScores as $skillScore){
			$champRank = '#'.number_format($skillScore['rank'], 0, '.', ',');
if($skillScore['rank'] > 1000){ // FIXME remove line
	$champRank = ''; // FIXME remove line
} // FIXME remove line
			$champSkillscore = number_format($skillScore['skillscore'], 0, '.', ',');
			$moreClasses = '';
			if($i > 3){
				$moreClasses.= ' hidden-sm-down';
			}
			$bestChampions[] = '<div id="summoner-page-header-champion-'.$skillScore['champion'].'" class="summoner-page-header-champion d-inline-block'.$moreClasses.'" data-champion-id="'.$skillScore['champion'].'" data-champion-name="'.$ch->getDisplayName($skillScore['champion']).'" data-champion-image="'.$ch->getSkinImage($skillScore['champion'], 0, 'splash').'" data-skillscore="'.$champSkillscore.'" data-champion-rank="'.$champRank.'" style="background-image:url('.$ch->getChampionImage($skillScore['champion'], 64).');">
				<div class="overlay">&nbsp;</div>
			</div>';
			if($i==1){
				// Set best-champion-banner for best champion
				$template_js.= '<script>
					$(function(){
						updateSummonerPageHeaderArt('.$skillScore['champion'].');
					});
				</script>';

				// Set background image for best champion
				$backgroundChampion = $skillScore['champion'];
			}
			if($i>=5){
				break;
			}
			$i++;
		}
	}

	// Set background image
	$template_body_class = 'background-champion';
	$template_css_inline.= '
		body {
			background-image:url('.$ch->getSkinImage($backgroundChampion, 0, 'background').');
		}
	';

	// Display
	$template_content.= '		<section id="summoner-header">
			<div class="container">
				<div id="summoner-page-header" class="champion-header" style="background-image:url('.$ch->getSkinImage($backgroundChampion, 0, 'splash').');">
					<div class="overlay">
						<div id="summoner-page-header-champion-feature" class="text-center">
							<h2 class="skillscore"><span class="champion-skillscore"></span> LSS</h2>
							<h5 class="rank color-secondary text-uppercase"><span class="champion-rank"></span> <span class="champion-name"></span></h5>
						</div>
						<div class="info-row d-flex align-items-center w-100">
							<div class="icon border-secondary d-inline-block" style="background-image:url('.$sm->getProfileIcon($summoner['profileIconId'], 64).');">&nbsp;</div>
							<div class="info-text d-inline-flex flex-column justify-content-center">
								<div>
									<span class="text-muted">'.$platformName.'</span>
									<span class="title">'.$displayName.'</span>
								</div>
								<div class="subtitle">
									'.$rolesOrLevel.'
								</div>
							</div>';
	if(!empty($bestChampions)){
		$template_content.= '							<div class="best-champions ml-auto">
								'.implode($bestChampions).'
							</div>';
	}
	$template_content.= '						</div>
					</div>
				</div>
				<nav class="nav nav-content navbar-expand-lg flex-wrap align-items-stretch">
					<button class="navbar-toggler hidden-lg-up btn btn-outline-primary" type="button" data-toggle="collapse" data-target="#nav-content-responsive" aria-controls="nav-content-responsive" aria-expanded="false" aria-label="Toggle navigation">
						'.$contentMap[$content].'
					</button>
					<div class="collapse navbar-collapse" id="nav-content-responsive">
						<div class="nav nav-content flex-wrap align-items-stretch w-100">';
	foreach($contentMap as $key => $value){
		$active = ($content==$key) ? ' active' : '';
		$template_content.= '							<a class="nav-link'.$active.'" href="summoner/'.$platformName.'/'.rawurlencode($displayName).'/'.$key.'">'.$value.'</a>';
	}
	$template_content.= '						</div>
					</div>
				</nav>
			</div>
		</section>';

	if($summoner['status']=='updatePending'){
		$template_content.= '		<div class="container">
			<div class="alert alert-info" role="alert">
				This summoner profile is currently being updated. This process usually takes less than a minute.
			</div>
		</div>';
	}elseif(!$sh->isMatchQueueStatusOk($platform)){
		$template_content.= '		<div class="container">
			<div class="alert alert-info" role="alert">
				Our servers are currently under heavy load for '.$platformName.'. Updating summoner profiles is currently not available in this region.
			</div>
		</div>';
	}
/*
	if($updateReply!=null){
		if(isset($updateReply['matchesSentToQueue']) && $updateReply['matchesSentToQueue'] > 0){
			$template_content.= '		<div class="container">
			<div class="alert alert-info" role="alert">
				Stats for this summoner are still being calculated. Please try to refresh this page in a few moments to see updated stats. (#'.$updateReply['matchesSentToQueue'].')
			</div>
		</div>';
		}
	}*/

	// Summoner updated popup
	$template_content.= '		<div id="summoner-updated-message" class="container">
			<div class="alert alert-info" role="alert">
				This summoner profile has been updated!
			</div>
		</div>';

// Content
	switch($content){
	case 'summary':
	default:
		// Badges
		$badges = BadgeManager::getInstance()->getAllBadges($platform, $summoner['summonerId'], $displayName);
		if(!empty($badges)){
			$template_content.= '		<div class="container">
			<div class="row badges">
				<div class="col-12">';
			foreach($badges as $badge){
				$template_content.= '					<div class="badge tip" title="'.$badge['description'].'" data-html="true" style="background-image:url('.$badge['image'].');">
						<div class="text">'.$badge['text'].'</div>
					</div>';
			}
			$template_content.= '				</div>
			</div>
		</div>';
		}

		// Ranking Leagues
		$leaguesToDisplay = ['RANKED_SOLO_5x5', 'RANKED_FLEX_SR', 'RANKED_FLEX_TT'];
		$template_content.= '		<div class="container">
			<div class="row summoner-row-ranks">
				<div class="col-12 col-lg-4 ranks">';
		foreach($leaguesToDisplay as $leagueToDisplay){
			if(isset($leagueData[$leagueToDisplay])){
				// Has League (= Ranked)
				$league = $leagueData[$leagueToDisplay];
				$tier = ucfirst($league['tier']).' '.$league['division'];
				$template_content.= '					<div class="rank d-flex align-items center">
						<div class="d-flex align-items-center">
							<img src="'.STATIC_PATH.'/img/tiers/192/'.$league['tier'].'.png" alt="">
						</div>
						<div class="d-flex align-items-center">
							<div class="content text-left">
								<p class="type color-secondary">'.parseQueue($leagueToDisplay).'</p>
								<p class="tier">'.$tier.'</p>
								<p class="leaguepoints">
									'.number_format($league['leaguePoints'], 0, '.', ',').' LP
									&nbsp;&nbsp;&nbsp;
									<span class="wins">'.number_format($league['wins'], 0, '.', ',').'</span>
									&ndash;
									<span class="losses">'.number_format($league['losses'], 0, '.', ',').'</span>
								</p>
							</div>
						</div>
					</div>';
			}else{
				// Has No League (= Unranked)
				$template_content.= '					<div class="rank d-flex align-items center">
						<div class="d-flex align-items-center">
							<img src="'.STATIC_PATH.'/img/tiers/192/unranked.png" alt="">
						</div>
						<div class="d-flex align-items-center">
							<div class="content text-left">
								<p class="type color-secondary">'.parseQueue($leagueToDisplay).'</p>
								<p class="tier">Unranked</p>
								<p class="leaguepoints">&nbsp;</p>
							</div>
						</div>
					</div>';
			}
		}
		$template_content.= '				</div>';

		// Last Matches
		$template_content.= '				<div class="col-12 col-lg-8 match-history">';
		$i=0;
		if(!empty($matchList)){
			foreach($matchList as $match){
				// Show exactly twice as many matches as leagues
				if($i >= 2 * count($leaguesToDisplay)){
					break;
				}
				$i++;

				$template_content.= $mm->getPrintableMatch($match, $summoner['summonerId']);
			}
		}
		$template_content.= '				</div>
			</div>
		</div>
		<div class="container">
			<div class="row summoner-row-chart">
				<div class="col-12 col-md-4 d-flex justify-content-center">';
		$template_content.= $am->getMediumRectangle();
		$template_content.= '				</div>';

		// Role Chart
		if(array_sum($mainRoles) > 0){
			$template_content.= '				<div class="col-12 col-md-8">
					<div class="role-chart d-flex flex-column justify-content-center text-right">';
			$highestRoleValue = max($mainRoles);
			$rolesList = ['top','jungle','mid','marksman','support'];
			foreach($rolesList as $role){
				$roleValue = $mainRoles[$role];
				$percent = floor(100 * $roleValue / $highestRoleValue);
				$roleStyle = ($roleValue==$highestRoleValue) ? '' : '-grey';
				$template_content.= '						<div class="d-flex align-items-center">
							<div class="icon"><img src="'.STATIC_PATH.'/img/roles/32'.$roleStyle.'/'.strtolower($role).'.png" alt=""></div>
							<div class="bar-area d-flex align-items-center">
								<div class="bar d-flex align-items-center justify-content-end" style="width:'.$percent.'%;"></div>
								<div class="number">'.$roleValue.'</div>
							</div>
							<div class="role ml-auto">'.ucfirst($role).'</div>
						</div>';
			}
			$template_content.=	'					</div>
				</div>';
		}
		$template_content.=	'			</div>
		</div>';
		break;
	case 'current-game':
		include('summoner_game.php');
		break;
	case 'leagues':
		include('summoner_leagues.php');
		break;
	case 'champions':
		include('summoner_champions.php');
		break;
	case 'stats':
		include('summoner_stats.php');
		break;
	case 'matches':
		include('summoner_matches.php');
		break;
	case 'runes-and-masteries':
		include('summoner_runes_masteries.php');
		break;
	case 'stream':
		include('summoner_stream.php');
		break;
	}

	$template_content.= '		</section>';
	$template_content.= $am->getLeaderboard();
}

include_once(ABSOLUTE_PATH.'/template.php');
?>