<?php
/**
 *    This file is part of "Liberty Gaming NQ Stats Analyzer".
 *
 *    "Liberty Gaming NQ Stats Analyzer" is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    "Liberty Gaming NQ Stats Analyzer" is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


$max_favorite_victims=25;
$max_worst_enemies=25;
$max_recent_games=50;

if (!isset($player_key)) $player_key='';


$gameclient=new PCPIN_GameClient($session);
$game=new PCPIN_Game($session);
$gameclientteamclass=new PCPIN_GameClientTeamClass($session);
$gameclientsuicide=new PCPIN_GameClientSuicide($session);
$gameclientkill=new PCPIN_GameClientKill($session);
$gameclientdeath=new PCPIN_GameClientDeath($session);


$_body_onload[]='initHRows(\'classes_tbl\')';
$_body_onload[]='initHRows(\'player_stats_tbl\')';
$_body_onload[]='initHRows(\'player_aliases_tbl\')';
$_body_onload[]='initHRows(\'weapon_stats_tbl\')';
$_body_onload[]='initHRows(\'favorite_victims_tbl\')';
$_body_onload[]='initHRows(\'worst_enemies_tbl\')';
$_body_onload[]='initHRows(\'recent_games_tbl\')';
$_body_onload[]='initThumbs()';


// Get player stats
$list=$gameclient->listPlayers($exclude_guids, '', '', '', 0, 0, $player_key);


$avg_ping=-1;
$classes=array();
$favorite_team=3;
$favorite_class=0;
$favorite_weapon='MOD_UNKNOWN';
$weapons=array();
$img_nr=0;

if (!empty($list['ListedResults'])) {
  $player_data=reset($list['ListedResults']);
  // Get average ping
  $avg_ping=$gameclient->getAvgPing($player_data['GUID']);
  // Get played classes
  $classes=$gameclientteamclass->getPlayedClasses($player_data['GUID']);
  // Calculate favorite class and team + percentages
  $max_time=0;
  foreach ($classes as $key=>$data) {
    $classes[$key]['Pct']=$player_data['TimePlayed']>0? $data['TimeTotal']/$player_data['TimePlayed']*100 : 0;
    if ($max_time<$data['TimeTotal']) {
      $max_time=$data['TimeTotal'];
      $favorite_team=$data['TimeAxis']>$data['TimeAllies']? 1 : 2;
      $favorite_class=$data['Class'];
    }
  }
  // Get favorite weapon for favorite team and class
  $favorite_weapons_team_class=$gameclientkill->countKillsByTeamClass($player_data['GUID'], $favorite_team);
  if (!empty($favorite_weapons_team_class[$favorite_team])) {
    reset($favorite_weapons_team_class[$favorite_team]);
    if (!empty($favorite_weapons_team_class[$favorite_team][$favorite_class])) {
      reset($favorite_weapons_team_class[$favorite_team][$favorite_class]);
      $favorite_weapon=key($favorite_weapons_team_class[$favorite_team][$favorite_class]);
    } else {
      $most_used_class=key($favorite_weapons_team_class[$favorite_team]);
      reset($favorite_weapons_team_class[$favorite_team][$most_used_class]);
      $favorite_weapon=key($favorite_weapons_team_class[$favorite_team][$most_used_class]);
    }
  }
  // Get suicides/weapon stats
  $weapon_suicides=$gameclientsuicide->getSuicidesWeapon($player_data['GUID']);
  // Get stats of MODs which are not in WS
  $mod_stats=array();
  $mod_stats_kill=$gameclientkill->getKillsMOD($player_data['GUID']);
  foreach ($mod_stats_kill as $data) {
    $mod_stats[$data['MOD']]=$data;
  }
  $mod_stats_death=$gameclientdeath->getDeathsMOD($player_data['GUID']);
  foreach ($mod_stats_death as $data) {
    if (!isset($mod_stats[$data['MOD']])) {
      $mod_stats[$data['MOD']]=$data;
    } else {
      foreach ($data as $key=>$val) {
        $mod_stats[$data['MOD']][$key]=$val;
      }
    }
  }
  // Get favorite victims
  $favorite_victims=$gameclientkill->getFavoriteVictims($player_data['GUID'], 25);
  // Get worst enemies
  $worst_enemies=$gameclientkill->getWorstEnemies($player_data['GUID'], 25);
  // Get last played games
  $recent_games=$game->listGames('nr', 'desc', 0, $max_recent_games, 0, $player_data['GUID']);
}

$tpl=new PcpinTpl();
$tpl->setBasedir(PCPIN_DIR_OFFSET.'/template');
$tpl->readTemplatesFromFile('player_stats.tpl');
$tpl->addGlobalVars(array('formlink'=>PCPIN_FORMLINK,
                          ));

$tpl->addVar('profile_page', 'display', $list['TotalResults']>0);

if (!empty($list['ListedResults'])) {
  // Player image and title
  $player_img=PCPIN_DIR_OFFSET.'/image/players/'.$favorite_team.'/'.$favorite_class.'/'.$favorite_team.'-'.$favorite_class.'-'.$favorite_weapon.'.gif';
  $player_img_title=htmlspecialchars($player_data['NameTxt']).' : '.getTeamName($favorite_team).' '.getClassName($favorite_class).' with '.MODToWeaponName($favorite_weapon);
  if (!file_exists($player_img)) {
    $player_img=PCPIN_DIR_OFFSET.'/image/players/'.$favorite_team.'/'.$favorite_class.'/'.$favorite_team.'-'.$favorite_class.'-DEFAULT.gif';
    $player_img_title=htmlspecialchars($player_data['NameTxt']).' : '.getTeamName($favorite_team).' '.getClassName($favorite_class);
    if (!file_exists($player_img)) {
      $player_img=PCPIN_DIR_OFFSET.'/image/players/'.$favorite_team.'/'.$favorite_team.'-DEFAULT-DEFAULT.gif';
      $player_img_title=htmlspecialchars($player_data['NameTxt']).' : '.getTeamName($favorite_team);
      if (!file_exists($player_img)) {
        $player_img=PCPIN_DIR_OFFSET.'/image/players/0/0-DEFAULT-DEFAULT.gif';
        $player_img_title=htmlspecialchars($player_data['NameTxt']);
      }
    }
  }
  $tpl->addVars('profile_page', array('name'=>coloredToHTML($player_data['Name']),
                                      'player_img'=>$player_img,
                                      'player_img_title'=>htmlspecialchars($player_img_title),
                                      'kills'=>htmlspecialchars($player_data['KilledEnemies']),
                                      'deaths'=>htmlspecialchars($player_data['Deaths']),
                                      'teamkills'=>htmlspecialchars($player_data['KilledTeammates']),
                                      'teamdeaths'=>htmlspecialchars($player_data['KilledByTeammates']),
                                      'dynamite_plant'=>htmlspecialchars($player_data['DynamitePlantTotal']),
                                      'dynamite_diffuse'=>htmlspecialchars($player_data['DynamiteDiffuseTotal']),
                                      'repairs'=>htmlspecialchars($player_data['RepairsTotal']),
                                      'disguises'=>htmlspecialchars($player_data['DisguisesTotal']),
                                      'objectives_taken'=>htmlspecialchars($player_data['ObjectivesTakenTotal']),
                                      'revives'=>htmlspecialchars($player_data['RevivesTotal']),
                                      'health_given'=>htmlspecialchars($player_data['HealthGivenTotal']),
                                      'ammo_given'=>htmlspecialchars($player_data['AmmoGivenTotal']),
                                      'health_taken'=>htmlspecialchars($player_data['HealthTakenTotal']),
                                      'ammo_taken'=>htmlspecialchars($player_data['AmmoTakenTotal']),
                                      'avg_ping'=>htmlspecialchars(round($avg_ping)),
                                      'kill_sprees'=>htmlspecialchars($player_data['KillSprees']),
                                      'longest_kill_spree'=>htmlspecialchars($player_data['LongestKillSpree']),
                                      'death_sprees'=>htmlspecialchars($player_data['DeathSprees']),
                                      'longest_death_spree'=>htmlspecialchars($player_data['LongestDeathSpree']),
                                      'first_killer'=>htmlspecialchars($player_data['FirstKillTotal']),
                                      'first_victim'=>htmlspecialchars($player_data['FirstDeathTotal']),
                                      'time_axis'=>htmlspecialchars(makeTimeFromSeconds($player_data['TimeAxis'])),
                                      'time_allies'=>htmlspecialchars(makeTimeFromSeconds($player_data['TimeAllies'])),
                                      'time_spectator'=>htmlspecialchars(makeTimeFromSeconds($player_data['TimeSpectator'])),
                                      'time_total'=>htmlspecialchars(makeTimeFromSeconds($player_data['TimeTotal'])),
                                      ));
  $row=1;
  foreach ($classes as $data) {
    $tpl->addVars('team_classes', array('display'=>true,
                                        'row'=>htmlspecialchars($row),
                                        'class'=>htmlspecialchars(getClassName($data['Class'])),
                                        'time'=>htmlspecialchars(makeTimeFromSeconds($data['TimeTotal'])),
                                        'pct'=>htmlspecialchars(number_format(round($data['Pct'], 1), 1, '.', '')),
                                        ));
    $tpl->parseTemplate('team_classes', 'a');
    $row^=3;
  }
  
  $row=1;
  foreach ($player_data['UsedNames'] as $name_data) {
    $tpl->addVars('player_aliases', array('display'=>true,
                                          'row'=>htmlspecialchars($row),
                                          'name'=>coloredToHTML($name_data['Name']),
                                          ));
    $tpl->parseTemplate('player_aliases', 'a');
    $row^=3;
  }

  // Show weapon stats
  $row=1;
  foreach ($mod_stats as $data) {
    $img=PCPIN_DIR_OFFSET.'/image/mods/'.$data['MOD'].'.gif';
    if (!file_exists($img)) {
      $img=PCPIN_DIR_OFFSET.'/image/mods/UNKNOWN.gif';
    }
    $tpl->addVars('weapon_stats', array('display'=>true,
                                        'row'=>htmlspecialchars($row),
                                        'img_nr'=>htmlspecialchars($img_nr++),
                                        'weapon'=>htmlspecialchars(MODToWeaponName($data['MOD'])),
                                        'kills'=>htmlspecialchars(!empty($data['Kills'])? $data['Kills'] : 0),
                                        'deaths'=>htmlspecialchars(!empty($data['Deaths'])? $data['Deaths'] : 0),
                                        'teamkills'=>htmlspecialchars(!empty($data['TeamKills'])? $data['TeamKills'] : 0),
                                        'teamdeaths'=>htmlspecialchars(!empty($data['TeamDeaths'])? $data['TeamDeaths'] : 0),
                                        'mod_img'=>$img,
                                        ));
    $tpl->parseTemplate('weapon_stats', 'a');
    $row^=3;
  }
  // Show favorite victims
  $tpl->addVar('profile_page', 'max_favorite_victims', htmlspecialchars($max_favorite_victims));
  $row=1;
  foreach ($favorite_victims as $data) {
    $tpl->addVars('favorite_victims', array('display'=>true,
                                            'row'=>htmlspecialchars($row),
                                            'key'=>htmlspecialchars($data['VictimGUID_Key']),
                                            'name'=>coloredToHTML($data['VictimName']),
                                            'name_txt'=>htmlspecialchars($data['VictimNameTxt']),
                                            'kills'=>htmlspecialchars($data['Kills']),
                                            'deaths'=>htmlspecialchars($data['Deaths']),
                                            'efficiency'=>htmlspecialchars(number_format(round($data['Efficiency'], 2), 2, '.', '')),
                                            ));
    $tpl->parseTemplate('favorite_victims', 'a');
    $row^=3;
  }

  // Show worst enemies
  $tpl->addVar('profile_page', 'max_worst_enemies', htmlspecialchars($max_worst_enemies));
  $row=1;
  foreach ($worst_enemies as $data) {
    $tpl->addVars('worst_enemies', array('display'=>true,
                                         'row'=>htmlspecialchars($row),
                                         'key'=>htmlspecialchars($data['KillerGUID_Key']),
                                         'name'=>coloredToHTML($data['KillerName']),
                                         'name_txt'=>htmlspecialchars($data['KillerNameTxt']),
                                         'kills'=>htmlspecialchars($data['Kills']),
                                         'deaths'=>htmlspecialchars($data['Deaths']),
                                         'efficiency'=>htmlspecialchars(number_format(round($data['Efficiency'], 2), 2, '.', '')),
                                         ));
    $tpl->parseTemplate('worst_enemies', 'a');
    $row^=3;
  }

  // Show recent games
  $row=1;
  foreach ($recent_games['ListedResults'] as $data) {
    $img=PCPIN_DIR_OFFSET.'/image/maps/'.$data['MapName'].'.gif';
    if (!file_exists($img)) {
      $img=PCPIN_DIR_OFFSET.'/image/maps/UNKNOWNMAP.gif';
    }
    $tmp=explode('_', $data['MapName']);
    foreach ($tmp as $key=>$tmp_val) {
      $tmp[$key]=ucfirst($tmp_val);
    }
    $data['MapNameStr']=implode(' ', $tmp);
    $tpl->addVars('recent_games', array('display'=>true,
                                        'row'=>htmlspecialchars($row),
                                        'nr'=>htmlspecialchars($data['GameNr']),
                                        'map'=>htmlspecialchars($data['MapNameStr']),
                                        'map_img'=>$img,
                                        ));
    $tpl->parseTemplate('recent_games', 'a');
    $row^=3;
  }

}

?>