<?php
require_once('global.php');
require_once(ABSOLUTE_PATH.'/class/ChampionHelper.php');
require_once(ABSOLUTE_PATH.'/class/Paginator.php');
require_once(ABSOLUTE_PATH.'/class/SalesManager.php');
require_once(ABSOLUTE_PATH.'/class/ToplistManager.php');

$championName = ((isset($_GET['championName']))&&($_GET['championName']!='')) ? trim($_GET['championName']) : null;

$ch = ChampionHelper::getInstance();
$id = $ch->getChampionIdByName($championName);
if($id==null){
	header('Location: '.DYNAMIC_PATH.'/champions');
	exit;
}

$skinId = ((isset($_GET['skinId']))&&($_GET['skinId']!='')) ? intval($_GET['skinId']) : 0;
if(!$ch->exists($id, $skinId)){
	$skinId = 0;
}

$tm = ToplistManager::getInstance();

// Build ContentMap
$contentMap = [
	'summary' => 'Summary',
	'about' => 'About',
#	'stats' => 'Stats',
#	'matchups' => 'matchups',
#	'spells' => 'spells',
#	'items' => 'items',
#	'skillorder' => 'skillorder',
	'leaderboards' => 'Leaderboards',
#	'setups' => 'Setups'
];

$content = 'summary';
if(isset($_GET['content']) && isset($contentMap[$_GET['content']])){
	$content = $_GET['content'];
}

$meta_title = $ch->getDisplayName($id).', '.$ch->getTitle($id).' &ndash; Champions &ndash; LoLSkill';
$meta_description = 'Statistics, abilities, information, skins, store details and more for '.$ch->getDisplayName($id).', '.$ch->getTitle($id).', a League of Legends champion.';
$template_og['url'] = DYNAMIC_PATH.'/champion/'.$championName.'/'.$content;
$template_og['title'] = $ch->getDisplayName($id).', '.$ch->getTitle($id).' &ndash; Champions &ndash; LoLSkill';
$template_og['image'] = $ch->getSkinImage($id, $skinId, 'splash');
$template_og['description'] = 'Statistics, abilities, information, skins, store details and more for '.$ch->getDisplayName($id).', '.$ch->getTitle($id).', a League of Legends champion.';

// Rates
$championStats = $ch->getChampionStats($id, ChampionHelper::STATS);
$championAvg = $ch->getChampionStats($id, ChampionHelper::AVERAGE);
if($championAvg!==false){
	$pickrate = number_format(100 * $championAvg['pickrate'], 1, '.', ',').'%';
	$banrate = number_format(100 * $championAvg['banrate'], 1, '.', ',').'%';
	$winrate = number_format(100 * $championAvg['winrate'], 1, '.', ',').'%';
}else $pickrate = $banrate = $winrate = '???';

// Set background image
$template_body_class = 'background-champion';
$template_css_inline.= '
	body {
		background-image:url('.$ch->getSkinImage($id, 0, 'background').');
	}
';

// Display
$template_content = $am->getLeaderboard();
$template_content.= '<section id="championPage">';
$template_content.= '	<section id="champion-header">
		<div class="container">
			<div id="champion-page-header" class="champion-header" style="background-image:url('.$ch->getSkinImage($id, 0, 'splash').');">
				<div class="overlay">
					<div class="info-row d-flex align-items-center w-100">
						<div class="icon border-secondary d-inline-block" style="background-image:url('.$ch->getChampionImage($id, 64).');">&nbsp;</div>
						<div class="info-text d-inline-flex flex-column justify-content-center">
							<div>
								<span class="title">'.$ch->getDisplayName($id).'</span>
							</div>
							<div class="subtitle">
								<span class="text-muted">'.$ch->getTitle($id).'</span>
							</div>
						</div>
						<div class="rate ml-auto text-center">
							<div class="value">'.$pickrate.'</div>
							<div class="label text-muted">Pick Rate</div>
						</div>
						<div class="rate text-center">
							<div class="value">'.$banrate.'</div>
							<div class="label text-muted">Ban Rate</div>
						</div>
						<div class="rate text-center">
							<div class="value">'.$winrate.'</div>
							<div class="label text-muted">Win Rate</div>
						</div>
					</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' : '';
	if($key=='setups'){
		// FIXME setups is set as coming soon
		$template_content.= '						<span class="nav-span">'.$value.'&nbsp;<span class="color-secondary">(Coming Soon)</span></span>';
	}else{
		$template_content.= '						<a class="nav-link'.$active.'" href="champion/'.$championName.'/'.$key.'">'.$value.'</a>';
	}
}
$template_content.= '					</div>
				</div>
			</nav>
		</div>
	</section>';

// Content
switch($content){
	case 'summary':
	default:
		$template_content.= '		<section id="champion-summary">
			<div class="container">';

		$roles = $ch->getChampionStats($id, ChampionHelper::ROLES);
		$matchups = $ch->getChampionStats($id, ChampionHelper::MATCHUPS);
		if($matchups!==false && $roles!==false){
			$template_content.= '				<div class="row">
					<div class="col-12 col-md-4">';

			// Matchups
			$championMainRole = key($roles);
			// Find Best Matchup
			$bestMatchup = key($matchups['enemy']);
			foreach($matchups['enemy'] as $matchupChampion => $matchupData){
				$matchupRoles = $ch->getChampionStats($matchupChampion, ChampionHelper::ROLES);
				if($matchupRoles==null){
					continue;
				}
				if(!isset($matchupRoles[$championMainRole])){
					continue;
				}
				$highestRoleValue = max($matchupRoles);
				$percent = floor(100 * $matchupRoles[$championMainRole] / $highestRoleValue);
				if($percent > 15){
					$bestMatchup = $matchupChampion;
					break;
				}
			}
			$bestMatchupWinRate = number_format(100 * $matchups['enemy'][$bestMatchup]['wins'] / $matchups['enemy'][$bestMatchup]['games'], 1, '.', ',');

			// Find Worst Matchup
			end($matchups['enemy']);
			$worstMatchup = key($matchups['enemy']);
			foreach(array_reverse($matchups['enemy']) as $matchupChampion => $matchupData){
				$matchupRoles = $ch->getChampionStats($matchupChampion, ChampionHelper::ROLES);
				if($matchupRoles==null){
					continue;
				}
				$highestRoleValue = max($matchupRoles);
				$percent = floor(100 * $matchupRoles[$championMainRole] / $highestRoleValue);
				if($percent > 15){
					$worstMatchup = $matchupChampion;
					break;
				}
			}
			$worstMatchupWinRate = number_format(100 * $matchups['enemy'][$worstMatchup]['wins'] / $matchups['enemy'][$worstMatchup]['games'], 1, '.', ',');

			$template_content.= '						<div class="champion-matchup" style="background-image:url('.$ch->getSkinImage($bestMatchup, 0, 'splash').');">
							<div class="overlay d-flex flex-column">
								<div class="text color-secondary">Easiest Lane Matchup</div>
								<div class="champion-name">'.$ch->getDisplayName($bestMatchup).'</div>
								<div class="rate text text-muted">'.$bestMatchupWinRate.'% Win Rate</div>
							</div>
						</div>
						<div class="champion-matchup" style="background-image:url('.$ch->getSkinImage($worstMatchup, 0, 'splash').');">
							<div class="overlay d-flex flex-column">
								<div class="text color-secondary">Hardest Lane Matchup</div>
								<div class="champion-name">'.$ch->getDisplayName($worstMatchup).'</div>
								<div class="rate text text-muted">'.$worstMatchupWinRate.'% Win Rate</div>
							</div>
						</div>';

			$template_content.= '					</div>
					<div class="col-12 col-md-8">';

			// Role Chart
			$template_content.= '						<div class="role-chart d-flex flex-column justify-content-center text-right">';
			if($roles!==false && array_sum($roles) > 0){
				$highestRoleValue = max($roles);
				$roleSum = array_sum($roles);
				$rolesList = ['top','jungle','mid','marksman','support'];
				foreach($rolesList as $role){
					$roleValue = $roles[$role];
					$percent = floor(100 * $roleValue / $highestRoleValue);
					$printRoleValue = (number_format(100 * $roleValue / $roleSum, 1, '.', ',') + 0).'%';
					$template_content.= '							<div class="d-flex align-items-center">
								<div class="icon"><img src="'.STATIC_PATH.'/img/roles/32/'.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">'.$printRoleValue.'</div>
								</div>
								<div class="role ml-auto">'.ucfirst($role).'</div>
							</div>';
				}
			}
			$template_content.=	'						</div>
					</div>';

			$template_content.= '				</div>';

			$template_content.= '			<div class="row champion-row-bestbuilds">
				<div class="col-12 col-md-4 d-flex justify-content-center">';
			$template_content.= $am->getMediumRectangle();
			$template_content.= '				</div>';

			// Best Builds
			$template_content.= '				<div class="col-12 col-md-8">
					<div class="bestbuilds d-flex flex-column justify-content-center text-right">';
			$amount = 3;
			$championItemBuilds = $ch->getChampionStats($id, ChampionHelper::ITEMBUILD);
			$championTrinkets = $ch->getChampionStats($id, ChampionHelper::TRINKETS);
			$championSpellCombinations = $ch->getChampionStats($id, ChampionHelper::SPELLCOMBINATION);
			if($championItemBuilds!==false){
				$topBuilds = array_fill(0, $amount, [
					'items' => '',
					'spells' => '',
					'trinket' => ''
				]);
				$i = 0;
				foreach($championItemBuilds as $key => $value){
					$topBuilds[$i]['items'] = $key;
					if(++$i==$amount){
						break;
					}
				}
				$i = 0;
				foreach($championSpellCombinations as $key => $value){
					$topBuilds[$i]['spells'] = $key;
					if(++$i==$amount){
						break;
					}
				}
				foreach($topBuilds as $key => $build){
					$place = $key + 1;
					$printSpells = '';
					$spells = explode('S', $build['spells']);
					foreach($spells as $spell){
						if($spell==''){
							continue;
						}
						$printSpells.= $sh->getSpell($spell);
					}
					$printItems = '';
					$items = explode('I', $build['items']);
					foreach($items as $item){
						if($item==''){
							continue;
						}
						$printItems.= $sh->getItem($item);
					}
					if($championTrinkets!==false){
						$printItems.= $sh->getItem(key($championTrinkets));
					}
					$popularity = 100 * ($championItemBuilds[$build['items']] / array_sum($championItemBuilds));
					$popularity = number_format($popularity, 1, '.', ',') + 0;
					$template_content.= '						<div class="build d-flex align-items-center">
							<div class="text-left">
								<p class="title">Most Popular Build #'.$place.'</p>
								<p class="popularity color-secondary">'.$popularity.'% Popularity</p>
							</div>
							'.$printSpells.'
							'.$printItems.'
						</div>';
				}
			}
			$template_content.=	'					</div>
				</div>';
			$template_content.=	'			</div>';
		}

		// Abilities
		$template_content.= '				<div class="abilities row">';
		foreach($ch->getAbilities($id) as $spellId => $ability){
			$template_content.= '					<div class="col-12">
						<div class="ability d-flex">
							<div class="icon">
								<img src="'.$ch->getAbilityImage($id, $spellId, 64).'" alt="">
							</div>
							<div class="text">
								<h5>'.$ability['name'].' ('.$ch->getAbilityHotkey($spellId).')</h5>
								<div class="attributes row">
									<p class="col-12 col-lg-4">'.$ch->getPrintableAbilityCooldown($ability['cooldown']).'</p>
									<p class="col-12 col-lg-4 ml-auto">'.$ch->getPrintableAbilityCost($ability['cost']).'</p>
									<p class="col-12 col-lg-4 ml-auto">'.$ch->getPrintableAbilityRange($ability['range']).'</p>
								</div>
								<p>'.$ch->getPrintableAbilityDescription($ability['description']).'</p>
							</div>
						</div>
					</div>';
		}
		$template_content.= '				</div>';

		$template_content.= '			</div>
		</section>';
		break;
	case 'about':
		include('champion_about.php');
		break;
	case 'stats':
		include('champion_stats.php');
		break;
	case 'matchups':
		$championRoles = $ch->getChampionStats($id, ChampionHelper::ROLES);
		$template_content.= '			<div class="container">
				<div class="body">
					<div class="messagebox info mini">
						<p>This list shows how well '.$ch->getDisplayName($id).' performs against all other champions in ranked games.</p>
					</div>
				</div>
			</div>
			<div class="container" id="filter">
				<div class="head"><h3>Filters</h3></div>
				<div class="body">
					<input type="radio" name="roleFilter" id="roleTop" class="matchupsRoleFilter" value="top"'.((key($championRoles)=='top') ? ' checked' : '').'> <label for="roleTop">Top-Lane</label>
					<input type="radio" name="roleFilter" id="roleJungle" class="matchupsRoleFilter" value="jungle"'.((key($championRoles)=='jungle') ? ' checked' : '').'> <label for="roleJungle">Jungle</label>
					<input type="radio" name="roleFilter" id="roleMid" class="matchupsRoleFilter" value="mid"'.((key($championRoles)=='mid') ? ' checked' : '').'> <label for="roleMid">Mid-Lane</label>
					<input type="radio" name="roleFilter" id="roleMarksman" class="matchupsRoleFilter" value="marksman"'.((key($championRoles)=='marksman') ? ' checked' : '').'> <label for="roleMarksman">Marksmen</label>
					<input type="radio" name="roleFilter" id="roleSupport" class="matchupsRoleFilter" value="support"'.((key($championRoles)=='support') ? ' checked' : '').'> <label for="roleSupport">Support</label>
					<input type="radio" name="roleFilter" id="roleAll" class="matchupsRoleFilter" value="all"> <label for="roleAll">All</label>
				</div>
			</div>
			<table class="skinned">
				<tr>
					<th style="width:1px;">Rank</th>
					<th class="left" colspan="2">Champion</th>
					<th class="left">'.$ch->getDisplayName($id).'\'s win rate in this matchup</th>
					<th style="width:48px;"></th>
				</tr>';
		$i = 0;
		$championMatchups = $ch->getChampionStats($id, ChampionHelper::MATCHUPS);
		$championMatchupsEnemies = $championMatchups['enemy'];
		foreach($championMatchupsEnemies as $champion => $data){
			if($data['games']<100){
				continue;
			}
			$roles = [];
			foreach($ch->getChampionStats($champion, ChampionHelper::ROLES) as $role => $count){
				$stats = $ch->getChampionStats($champion, ChampionHelper::STATS);
				if($count / $stats['games'] >= 0.15){
					$roles[] = $role;
				}
			}
			$winrate = (isset($data['wins'])) ? 100 * ($data['wins'] / $data['games']) : 0;
			$template_content.='				<tr class="championMatchup" data-roles="'.implode(',', $roles).'">
					<td>'.(++$i).'</td>
					<td class="icononly champion tooltip" data-champion-id="'.$champion.'"><a href="champion/'.$ch->getChampionCode($champion).'"><img src="'.$ch->getChampionImage($champion, 32).'" alt=""></a></td>
					<td class="left champion tooltip" data-champion-id="'.$champion.'"><a href="champion/'.$ch->getChampionCode($champion).'">'.$ch->getDisplayName($champion).'</a></td>
					<td class="bar"><div style="width:'.min($winrate, 100).'%;">&nbsp;</div></td>
					<td>'.number_format($winrate, 1, '.', ',').'%</td>
				</tr>';
		}
		$template_content.= '			</table>
			<script>
				$(function(){
					updateMatchupRoleFilter();
				});
			</script>';
		break;
	case 'spells':
		require_once('cache/spells.php');
		$template_content.= '			<h1>Most Popular Summoner Spells</h1>
			<table class="skinned">
				<tr>
					<th style="width:1px;">Rank</th>
					<th class="left" colspan="2">Summoner Spell</th>
					<th class="left">Popularity</th>
					<th style="width:48px;"></th>
				</tr>';
		$i = 0;
		$championSpells = $ch->getChampionStats($id, ChampionHelper::SPELLS);
		foreach($championSpells as $spell => $count){
			if(!isset($cacheSpells[$spell])){
				continue;
			}
			$popularity = 100 * ($count / $championStats['games']);
			$printPopularity = ($popularity >= 0.1) ? number_format($popularity, 1, '.', ',').'%' : '< 0.1%';
			$template_content.='				<tr>
					<td>'.(++$i).'</td>
					<td class="icononly spell tooltip" data-spell-id="'.$spell.'"><img src="'.STATIC_PATH.'/img/spells/32/'.$spell.'.png" alt=""></td>
					<td class="left spell tooltip" data-spell-id="'.$spell.'">'.$cacheSpells[$spell]['name'].'</td>
					<td class="bar"><div style="width:'.min($popularity, 100).'%;">&nbsp;</div></td>
					<td>'.$printPopularity.'</td>
				</tr>';
		}
		$template_content.= '			</table>';
		break;
	case 'items':
		require_once('cache/items.php');
		// Item Builds
		$template_content.= '			<h1>Most Popular Item Builds</h1>
			<table class="skinned">
				<tr>
					<th style="width:1px;">Rank</th>
					<th class="left">Item Build</th>
					<th class="left">Popularity</th>
					<th style="width:48px;"></th>
				</tr>';
		$i = 0;
		$championItemBuild = $ch->getChampionStats($id, ChampionHelper::ITEMBUILD);
		foreach($championItemBuild as $itemBuild => $count){
			if($i==10){
				break;
			}
			$popularity = 100 * ($count / array_sum($championItemBuild));
			$printPopularity = ($popularity >= 0.1) ? number_format($popularity, 1, '.', ',').'%' : '< 0.1%';
			$build = '';
			foreach(explode('I', $itemBuild) as $item){
				if($item=='') continue;
				$build.= '<img class="item tooltip" data-item-id="'.$item.'" src="'.STATIC_PATH.'/img/items/32/'.$item.'.png" alt="">';
			}
			$template_content.='				<tr>
					<td>'.(++$i).'</td>
					<td class="left itembuild">'.$build.'</td>
					<td class="bar"><div style="width:'.min($popularity, 100).'%;">&nbsp;</div></td>
					<td>'.$printPopularity.'</td>
				</tr>';
		}
		$template_content.= '			</table>
			<br><br>';
		// Trinkets
		$template_content.= '			<h1>Most Popular Trinkets</h1>
			<table class="skinned">
				<tr>
					<th style="width:1px;">Rank</th>
					<th class="left" colspan="2">Item</th>
					<th class="left">Popularity</th>
					<th style="width:48px;"></th>
				</tr>';
		$i = 0;
		$championTrinkets = $ch->getChampionStats($id, ChampionHelper::TRINKETS);
		foreach($championTrinkets as $item => $count){
			$popularity = 100 * ($count / array_sum($championTrinkets));
			$printPopularity = ($popularity >= 0.1) ? number_format($popularity, 1, '.', ',').'%' : '< 0.1%';
			$template_content.='				<tr>
					<td>'.(++$i).'</td>
					<td class="icononly item tooltip" data-item-id="'.$item.'"><img src="'.STATIC_PATH.'/img/items/32/'.$item.'.png" alt=""></td>
					<td class="left item tooltip" data-item-id="'.$item.'">'.$cacheItems[$item]['name'].'</td>
					<td class="bar"><div style="width:'.min($popularity, 100).'%;">&nbsp;</div></td>
					<td>'.$printPopularity.'</td>
				</tr>';
		}
		$template_content.= '			</table>
			<br><br>';
		// Items
		$template_content.= '			<h1>Most Popular Items</h1>
			<table class="skinned">
				<tr>
					<th style="width:1px;">Rank</th>
					<th class="left" colspan="2">Item</th>
					<th class="left">Popularity</th>
					<th style="width:48px;"></th>
				</tr>';
		$i = 0;
		$championItems = $ch->getChampionStats($id, ChampionHelper::ITEMS);
		foreach($championItems as $item => $count){
			if($i==25){
				break;
			}
			$popularity = 100 * ($count / $championStats['games']);
//			$popularity = 100 * ($count / (array_sum($championItems) / 6));
			$printPopularity = ($popularity >= 0.1) ? number_format($popularity, 1, '.', ',').'%' : '< 0.1%';
			$template_content.='				<tr>
					<td>'.(++$i).'</td>
					<td class="icononly item tooltip" data-item-id="'.$item.'"><img src="'.STATIC_PATH.'/img/items/32/'.$item.'.png" alt=""></td>
					<td class="left item tooltip" data-item-id="'.$item.'">'.$cacheItems[$item]['name'].'</td>
					<td class="bar"><div style="width:'.min($popularity, 100).'%;">&nbsp;</div></td>
					<td>'.$printPopularity.'</td>
				</tr>';
		}
		$template_content.= '			</table>';
		break;
	case 'skillorder':
		$template_content.= '			<h1>Most Popular Skill Orders</h1>
			<table class="skinned">
				<tr>
					<th style="width:1px;">Rank</th>
					<th class="left">Skill Order</th>
					<th class="left">Popularity</th>
					<th style="width:48px;"></th>
				</tr>';
		$i = 0;
		$championSkillOrder = $ch->getChampionStats($id, ChampionHelper::SKILLORDER);
		foreach($championSkillOrder as $skillOrder => $count){
			if($i==20){
				break;
			}
			$popularity = 100 * ($count / array_sum($championSkillOrder));
			$printPopularity = ($popularity >= 0.1) ? number_format($popularity, 1, '.', ',').'%' : '< 0.1%';
			$skillIcons = '';
			foreach(str_split($skillOrder, 2) as $skill){
				if($skill[0]=='N'){
					$skillIcons.= '<img class="tooltip" title="'.$ch->getAbilityName($id, $skill[1]).' ('.$ch->getAbilityHotkey($skill[1]).')" src="'.$ch->getAbilityImage($id, $skill[1], 32).'" alt="">';
				}
			}
			$template_content.='				<tr>
					<td>'.(++$i).'</td>
					<td class="left skillorder">'.$skillIcons.'</td>
					<td class="bar"><div style="width:'.min($popularity, 100).'%;">&nbsp;</div></td>
					<td>'.$printPopularity.'</td>
				</tr>';
		}
		$template_content.= '			</table>';
		break;
	case 'leaderboards':
		include('champion_leaderboards.php');
		break;
}

$template_content.= '</section>';
$template_content.= $am->getLeaderboard();

include_once(ABSOLUTE_PATH.'/template.php');
?>