<?php
  include("html_functions.php");

  ################## PAGE INITIALIZATION #########################
  $lgid=$_SESSION['lgid'];
  $lgpath=$_SESSION['lgpath'];
  $date=new DateTime($_SESSION['lgdate']);
  $lgyear=$date->format("Y");

  if (($_SESSION['user_team_id']>0)&&(!isset($_GET['team_id'])))
  {
	  if ($_SESSION['user_league_id']==$lgid) {$team_id=$_SESSION['user_team_id'];}
	  else
	  {
		  include($_SESSION['adminpath']."/dbopen.php");
		  $query="SELECT team_id FROM teams WHERE parent_team_id=".$_SESSION['user_team_id']." AND league_id=$lgid";
		  $result=mysqli_query($db,$query);
		  if (mysqli_num_rows($result))
		  {
			  $row=mysqli_fetch_array($result);
			  $team_id=$row['team_id'];
		  }
		  mysqli_close($db);
	  }
  }
  elseif (isset($_GET['team_id'])) {$team_id=$_GET['team_id'];}
  if ($team_id=="") {$team_id=-1;}
  $tyear=$_GET['year'];
  $limit=$_GET['limit'];
  if ($limit=="") {$limit=25;}
	  
  ##### Get Team Names #####
  include($_SESSION['adminpath']."/dbopen.php");
  $query="SELECT team_id,name,nickname FROM teams WHERE league_id=$lgid";
  if ($team_id>0) {$query.=" AND team_id=$team_id";}
  $query.=" AND allstar_team=0 ORDER BY name,nickname LIMIT 1;";
  $result=mysqli_query($db,$query);
  while ($row=mysqli_fetch_array($result))
  {
	  $team_id=$row['team_id'];
	  $tname=$row['name']." ".$row['nickname'];
  }
  mysqli_close($db);
  
  ##### Get Title #####  
  $title=$tname." History - $tyear Player Tenure";
  page_head($title,$_SESSION['lgpath'],"","","./jquery/excanvas.js|./jquery/jquery.min.js|./jquery/jquery.jqplot.min.js|./jquery/plugins/jqplot.categoryAxisRenderer.min.js|./jquery/plugins/jqplot.pointLabels.min.js|./jquery/plugins/jqplot.barRenderer.min.js|./jquery/plugins/jqplot.highlighter.min.js|./jquery/plugins/jqplot.cursor.min.js");
  echo " <div id='topbar'>\n";
  main_titlebar($lgid,$_SESSION['lgpath'],$title,$team_id);
  nav_toolbar("history","History");
  nav_toolbar("teams","Teams","","",$team_id,$tyear);

  ##### Show Page Content #####
  echo " </div>   <!-- END topbar DIV -->\n";

  echo " <div id='contentpane'>\n";

  ##### Check for file #####
  if ($tyear>0) {echo gen_yearTen($team_id,$tyear);}
  else
  {
	  include($_SESSION['adminpath']."/dbopen.php");

	  ## Display Longest Tenured Players
  	  echo "<div class='textbox' style='width:100%;'>   <!-- open tenure listing -->\n";
	  echo " <table border=0 cellpadding=4 cellspacing=0 width='100%' style='margin-left:auto;margin-right:auto;'>   <!-- open tenure listing -->\n";
	  echo "  <tr class='title2'><td colspan=8>$limit Longest Tenured Players</td></tr>\n";
	  echo "  <tr class='headline'><td class='hsc2'>Pos</td><td class='hsc2_l'>Player</td><td class='hsc2'>From</td><td class='hsc2'>To</td><td class='hsc2'>Years</td><td class='hsc2'>G</td><td class='hsc2'>PA/IP</td><td class='hsc2'>WAR</td></tr>\n";

	  $query="SELECT first_name,last_name,position,role,x.* FROM players as p,(SELECT player_id,MIN(year) as minYr,MAX(year) as maxYr,COUNT(DISTINCT year) as yrs,SUM(g) as g,SUM(pa) as pt,SUM(war) as war FROM players_career_batting_stats WHERE league_id=$lgid AND split_id=1 AND team_id=$team_id GROUP BY player_id UNION SELECT player_id,MIN(year) as minYr,MAX(year) as maxYr,COUNT(DISTINCT year) as yrs,SUM(g) as g,SUM(ip)+SUM(ipf)/3 as pt,SUM(war) as war FROM players_career_pitching_stats WHERE league_id=$lgid AND split_id=1 AND team_id=$team_id GROUP BY player_id) as x WHERE p.player_id=x.player_id ORDER BY yrs DESC,g DESC,pt DESC LIMIT $limit";
	  if ($_GET['showq']==1) {echo "$query<br/>\n";}
	  $result=mysqli_query($db,$query);
	  if (mysqli_num_rows($result))
	  {
		  $rowCnt=0;
		  while ($row=mysqli_fetch_array($result))
		  {
			  $pid=$row['player_id'];
			  $pos=$row['position'];
			  if ($pos==1) {$pos=$row['role'];}

			  $cls='s'.($rowCnt%2+1);

			  echo "  <tr class='$cls'>";
			  echo "<td>".get_pos($pos,1)."</td>";
			  echo "<td class='".$cls."_l'><a href='./player.php?player_id=$pid'>".$row['first_name']." ".$row['last_name']."</td>";
			  echo "<td>".$row['minYr']."</td>";
			  echo "<td>".$row['maxYr']."</td>";
			  echo "<td>".$row['yrs']."</td>";
			  echo "<td>".$row['g']."</td>";
			  if ($pos>10) {echo "<td>".stat_format('ip',$row['pt'])."</td>";}
			  else {echo "<td>".stat_format('pa',$row['pt'],0)."</td>";}
              echo "<td>".stat_format('war',$row['war'])."</td>";
			  echo "<tr>\n";

			  $rowCnt++;
		  }
	  }
	  
  	  echo " </table>   <!-- close tenure listing -->\n";
	  echo "</div>   <!-- close tenure listing -->\n";

	  mysqli_close($db);
  }

  ################## END OF PAGE #########################
  echo " </div>   <!-- END contentpane DIV -->\n";
  page_foot($_SESSION['lgpath']);

  exit;

  
##############################################################################################
# gen_yearTen - Year Player Log
##############################################################################################
function gen_yearTen($tid="",$year="")
 {
   ##### Exit if no team_id #####
   if (($tid=="")||($year=="")) {exit;}
   include($_SESSION['adminpath']."/dbopen.php");

   ##### Get basic parameters #####
   $date=new DateTime($_SESSION['lgdate']);
   $thisYear=$date->format("Y");
   $lgpath=$_SESSION['lgpath'];
   $lgid=$_GET['lgid'];
   if ($lgid=="") {$lgid=$_SESSION['lgid'];}
   if ($lgid=="") {$lgid=100;}
   $text="";

   ##### Get Player List #####
   $query="SELECT player_id FROM (SELECT player_id FROM players_career_batting_stats WHERE team_id=$tid AND year=$year UNION SELECT player_id FROM players_career_pitching_stats WHERE team_id=$tid AND year=$year) as t ORDER BY player_id;";
   $result=mysqli_query($db,$query);
   if (mysqli_num_rows($result))
    {
      $pList="";
      while ($row=mysqli_fetch_array($result)) {$pList.=",".$row['player_id'];}
      $pList=trim($pList,",");

      ## Get Basic Player Info
      $query="SELECT player_id,first_name,last_name,bats,throws,date_of_birth FROM players WHERE player_id IN ($pList);";
      $result=mysqli_query($db,$query);
      while ($row=mysqli_fetch_array($result))
       {
         $pid=$row['player_id'];
	 $players[$pid]['name']=$row['first_name']." ".$row['last_name'];
	 $players[$pid]['sortname']=$row['last_name'].", ".$row['first_name'];
	 $players[$pid]['dob']=$row['date_of_birth'];
	 $players[$pid]['b']=get_hand($row['bats']);
	 $players[$pid]['t']=get_hand($row['throws']);
	 $players[$pid]['minYr']=99999;
	 $players[$pid]['maxYr']=0;
       }

      ## Get Years Played
      $query="SELECT player_id,year,team_id,SUM(ip)+SUM(ipf)/3 as ip,MIN(stint) as stint FROM players_career_pitching_stats WHERE league_id=$lgid AND split_id=1 AND player_id IN ($pList) GROUP BY player_id,team_id,year ORDER BY player_id,year,stint,team_id;";
      $result=mysqli_query($db,$query);
      while ($row=mysqli_fetch_array($result))
       {
         $pid=$row['player_id'];
         $yr=$row['year'];
         $team_id=$row['team_id'];
         $players[$pid][$yr]['teams']=$players[$pid][$yr]['teams']+1;
         if ($team_id==$tid) {$players[$pid][$yr]['for']=1;} else {$players[$pid][$yr]['for']=max(0,$players[$pid][$yr]['for']);}
         if (($yr==$year)&&($team_id=$tid)) {$pitchSort[$pid]=$row['ip'];}
         if ($yr<$players[$pid]['minYr']) {$players[$pid]['minYr']=$yr;}
         if ($yr>$players[$pid]['maxYr']) {$players[$pid]['maxYr']=$yr;}
       }
      $query="SELECT player_id,year,team_id,SUM(g) as g,MIN(stint) as stint FROM players_career_batting_stats WHERE league_id=$lgid AND split_id=1 AND player_id IN ($pList) GROUP BY player_id,team_id,year ORDER BY player_id,year,stint,team_id;";
      $result=mysqli_query($db,$query);
      while ($row=mysqli_fetch_array($result))
       {
         $pid=$row['player_id'];
         $yr=$row['year'];
         $team_id=$row['team_id'];
         if (!isset($pitchSort[$pid])) {$players[$pid][$yr]['teams']=$players[$pid][$yr]['teams']+1;}
         if ($team_id==$tid) {$players[$pid][$yr]['for']=1;} else {$players[$pid][$yr]['for']=max(0,$players[$pid][$yr]['for']);}
         if (($yr==$year)&&($team_id=$tid)&&(!isset($pitchSort[$pid]))) {$batSort[$pid]=$row['g'];}
         if ($yr<$players[$pid]['minYr']) {$players[$pid]['minYr']=$yr;}
         if ($yr>$players[$pid]['maxYr']) {$players[$pid]['maxYr']=$yr;}
       }

      ## Sort Players
      arsort($pitchSort);
      arsort($batSort);

      ## Get Year Range
      $minTmYr=99999;
      $maxTmYr=0;
      foreach ($players as $pid => $val)
       {
         $minYr=$players[$pid]['minYr'];
	 $maxYr=$players[$pid]['maxYr'];
	 if ($minYr<$minTmYr) {$minTmYr=$minYr;}
	 if ($maxYr>$maxTmYr) {$maxTmYr=$maxYr;}
       }
      $yrRange=$maxTmYr-$minTmYr+1;
      while ($yrRange>17)
       {
         if (($year-$minTmYr)>($maxTmYr-$year)) {$minTmYr+=1;} else {$maxTmYr-=1;}
	 $yrRange=$maxTmYr-$minTmYr+1;
         $rngAdjust=1;
       }

      ## Get Team Colors
      $priColor="#006184";
      $secColor="#1188b5";
      $othColor="#a76708";

      ## Display Players
      $text.=" <div class='tablebox'>\n";
      $text.="  <table cellpadding=2 cellspacing=0 border=0 width='915px'>\n";
      $text.="   <tr class='title2'><td colspan=".(2+2*$yrRange).">Batter Tenure</td><tr>\n";
      $text.="   <tr class='headline'><td class='hsc2_l'>Player</td><td class='hsc2' style='padding-right:10px;'>$year G</td>";
      for ($i=$minTmYr;$i<=$maxTmYr;$i++) {$text.="<td class='hsc2' colspan=2 style='text-align:center;'>$i</td>";}
      $text.="</tr>\n";
      $cnt=0;
      foreach ($batSort as $pid => $g)
       {
         $cls='s'.($cnt%2+1);
         $text.="   <tr class='$cls'>";
	 $text.="<td class='".$cls."_l' sorttable_customkey=\"".$players[$pid]['sortname']."\"><a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a></td>";
	 $text.="<td style='padding-right:10px;'>$g</td>";
         $minYr=$players[$pid]['minYr'];
	 $maxYr=$players[$pid]['maxYr'];
	 ## Open Row
	 if ($minYr!=$minTmYr)
	  {
            for ($i=$minTmYr;$i<$minYr;$i++) {$text.="<td colspan=2>&nbsp;</td>";}
	  }
	 ## Player years
	 for ($i=max($minYr,$minTmYr);$i<=min($maxYr,$maxTmYr);$i++)
	  {
	    if (!isset($players[$pid][$i]['teams']))
	     {
	       $text.="<td style='border:1px solid white;' colspan=2>&nbsp;</td>";
	       continue;
	     }
	    $text.="<td style='background-color:";
	    if ($players[$pid][$i]['for']==0)
	     {
	       $text.="$othColor;border:1px solid white;";
	       if (($i==$minTmYr)&&($minYr<$minTmYr)) {$text.="text-align:left;";}
	       if (($i==$maxTmYr)&&($maxYr>$maxTmYr)) {$text.="text-align:right;";}
	       $text.="' colspan=2>";
	       if (($i==$minTmYr)&&($minYr<$minTmYr)) {$text.="<img src='./images/ext-l-$cls.png'>";}
	        elseif (($i==$maxTmYr)&&($maxYr>$maxTmYr)) {$text.="<img src='./images/ext-r-$cls.png'>";}
	        else {$text.="&nbsp;";}
	       $text.="</td>";
	     }
	     else
	     {
	       if ($players[$pid][$i]['teams']>1)
	        {
              if (((isset($players[$pid][$i-1]['teams']))&&($players[$pid][$i-1]['for']==1))||((isset($players[$pid][$i+1]['teams']))&&($players[$pid][$i+1]['for']==0)))
               {
                 if ($i==$year) {$text.="$secColor";} else {$text.="$priColor";}
                 $text.=";border-left:1px solid white;border-top:1px solid white;border-bottom:1px solid white;";
                 if (($i==$minTmYr)&&($minYr<$minTmYr)) {$text.="text-align:left;'><img src='./images/ext-l-$cls.png'>";} else {$text.="'>&nbsp;";}
                 $text.="</td><td style='background-color:$othColor;border-right:1px solid white;border-top:1px solid white;border-bottom:1px solid white;";
                 if (($i==$maxTmYr)&&($maxYr>$maxTmYr)) {$text.="text-align:right;'><img src='./images/ext-r-$cls.png'>";} else {$text.="'>&nbsp;";}
                 $text.="</td>";
               }
               else
               {
                 $text.="$othColor;border-left:1px solid white;border-top:1px solid white;border-bottom:1px solid white;";
                 if (($i==$minTmYr)&&($minYr<$minTmYr)) {$text.="text-align:left;'><img src='./images/ext-l-$cls.png'>";} else {$text.="'>&nbsp;";}
                 $text.="</td><td style='background-color:";
                     if ($i==$year) {$text.="$secColor";} else {$text.="$priColor";}
                 $text.=";border-right:1px solid white;border-top:1px solid white;border-bottom:1px solid white;";
                 if (($i==$maxTmYr)&&($maxYr>$maxTmYr)) {$text.="text-align:right;'><img src='./images/ext-r-$cls.png'>";} else {$text.="'>&nbsp;";}
                 $text.="</td>";
               }
            }
	        else
	        {
              if ($i==$year) {$text.="$secColor";} else {$text.="$priColor";}
              $text.=";border:1px solid white;";
              if (($i==$minTmYr)&&($minYr<$minTmYr)) {$text.="text-align:left;";}
              if (($i==$maxTmYr)&&($maxYr>$maxTmYr)) {$text.="text-align:right;";}
              $text.="' colspan=2>";
              if (($i==$minTmYr)&&($minYr<$minTmYr)) {$text.="<img src='./images/ext-l-$cls.png'>";}
               elseif (($i==$maxTmYr)&&($maxYr>$maxTmYr)) {$text.="<img src='./images/ext-r-$cls.png'>";}
               else {$text.="&nbsp;";}
              $text.="</td>";
            }
	     }
	  }
	 ## Close Row
	 if ($maxYr<$maxTmYr)
	  {
	    $text.="<td colspan=".(2*($maxTmYr-$maxYr)).">&nbsp;</td>";
	  }
	 $text.="</tr>\n";
	 $cnt++;
       }
      $text.="  </table>\n";
      $text.=" </div>\n";

      $text.=" <div class='tablebox'>\n";
      $text.="  <table cellpadding=2 cellspacing=0 border=0 width='915px'>\n";
      $text.="   <tr class='title2'><td colspan=".(3+2*$yrRange).">Pitcher Tenure</td><tr>\n";
      $text.="   <tr class='headline'><td class='hsc2_l'>Player</td><td class='hsc2' style='padding-right:10px;'>$year IP</td>";
      for ($i=$minTmYr;$i<=$maxTmYr;$i++) {$text.="<td class='hsc2' colspan=2 style='text-align:center;'>$i</td>";}
      $text.="</tr>\n";
      $cnt=0;
      foreach ($pitchSort as $pid => $ip)
       {
         $cls='s'.($cnt%2+1);
         $text.="   <tr class='$cls'>";
	 $text.="<td class='".$cls."_l' sorttable_customkey=\"".$players[$pid]['sortname']."\"><a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a></td>";
	 $text.="<td style='padding-right:10px;'>".sprintf("%.1f",$ip)."</td>";
         $minYr=$players[$pid]['minYr'];
	 $maxYr=$players[$pid]['maxYr'];
	 ## Open Row
	 if ($minYr>$minTmYr)
	  {
            $text.="<td colspan=".(2*($minYr-$minTmYr)).">&nbsp;</td>";
	  }
	 ## Player years
	 for ($i=max($minYr,$minTmYr);$i<=min($maxYr,$maxTmYr);$i++)
	  {
	    if (!isset($players[$pid][$i]['teams']))
	     {
	       $text.="<td style='border:1px solid white;' colspan=2>&nbsp;</td>";
	       continue;
	     }
	    $text.="<td style='background-color:";
	    if ($players[$pid][$i]['for']==0)
	     {
	       $text.="$othColor;border:1px solid white;";
	       if (($i==$minTmYr)&&($minYr<$minTmYr)) {$text.="text-align:left;";}
	       if (($i==$maxTmYr)&&($maxYr>$maxTmYr)) {$text.="text-align:right;";}
	       $text.="' colspan=2>";
	       if (($i==$minTmYr)&&($minYr<$minTmYr)) {$text.="<img src='./images/ext-l-$cls.png'>";}
	        elseif (($i==$maxTmYr)&&($maxYr>$maxTmYr)) {$text.="<img src='./images/ext-r-$cls.png'>";}
	        else {$text.="&nbsp;";}
	       $text.="</td>";
	     }
	     else
	     {
	       if ($players[$pid][$i]['teams']>1)
	        {
		  if (((isset($players[$pid][$i-1]['teams']))&&($players[$pid][$i-1]['for']==1))||((isset($players[$pid][$i+1]['teams']))&&($players[$pid][$i+1]['for']==0)))
		   {
		     if ($i==$year) {$text.="$secColor";} else {$text.="$priColor";}
		     $text.=";border-left:1px solid white;border-top:1px solid white;border-bottom:1px solid white;";
		     if (($i==$minTmYr)&&($minYr<$minTmYr)) {$text.="text-align:left;'><img src='./images/ext-l-$cls.png'>";} else {$text.="'>&nbsp;";}
		     $text.="</td><td style='background-color:$othColor;border-right:1px solid white;border-top:1px solid white;border-bottom:1px solid white;";
		     if (($i==$maxTmYr)&&($maxYr>$maxTmYr)) {$text.="text-align:right;'><img src='./images/ext-r-$cls.png'>";} else {$text.="'>&nbsp;";}
		     $text.="</td>";
		   }
		   else
		   {
		     $text.="$othColor;border-left:1px solid white;border-top:1px solid white;border-bottom:1px solid white;";
		     if (($i==$minTmYr)&&($minYr<$minTmYr)) {$text.="text-align:left;'><img src='./images/ext-l-$cls.png'>";} else {$text.="'>&nbsp;";}
		     $text.="</td><td style='background-color:";
	             if ($i==$year) {$text.="$secColor";} else {$text.="$priColor";}
		     $text.=";border-right:1px solid white;border-top:1px solid white;border-bottom:1px solid white;";
		     if (($i==$maxTmYr)&&($maxYr>$maxTmYr)) {$text.="text-align:right;'><img src='./images/ext-r-$cls.png'>";} else {$text.="'>&nbsp;";}
		     $text.="</td>";
		   }
		}
	        else
	        {
   		  if ($i==$year) {$text.="$secColor";} else {$text.="$priColor";}
		  $text.=";border:1px solid white;";
		  if (($i==$minTmYr)&&($minYr<$minTmYr)) {$text.="text-align:left;";}
		  if (($i==$maxTmYr)&&($maxYr>$maxTmYr)) {$text.="text-align:right;";}
		  $text.="' colspan=2>";
		  if (($i==$minTmYr)&&($minYr<$minTmYr)) {$text.="<img src='./images/ext-l-$cls.png'>";}
		   elseif (($i==$maxTmYr)&&($maxYr>$maxTmYr)) {$text.="<img src='./images/ext-r-$cls.png'>";}
		   else {$text.="&nbsp;";}
		  $text.="</td>";
		}
	     }
	  }
         ## Close row
	 if ($maxYr<$maxTmYr)
	  {
	    $text.="<td colspan=".(2*($maxTmYr-$maxYr)).">&nbsp;</td>";
	  }
	 $text.="</tr>\n";
	 $cnt++;
       }
      $text.="  </table>\n";
      $text.=" </div>\n";

      ## Display Legend
      $text.=" <div class='tablebox'>\n";
      $text.="  <table cellpadding=2 cellspacing=2 border=0 width='915px'>\n";
      $text.="   <tr><td colspan=6><b>Legend</b></td><tr>\n";
      $text.="   <tr><td style='background-color:$secColor'>&nbsp;</td><td style='background-color:$priColor'>&nbsp;</td><td> - Played for team</td><td style='background-color:$othColor'>&nbsp;</td><td> - Played for another team</td><td style='border:1px solid black;'>&nbsp;</td><td> - Did not play in league</td><tr>\n";
      $text.="   <tr><td colspan=6>NOTE: Split seasons are not proportional to playing time or necessarily in order.</td><tr>\n";
      if ($rngAdjust==1) {$text.="   <tr><td colspan=6>Some player careers extend beyond the year range displayed.</td><tr>\n";}
      $text.="  </table>\n";
      $text.=" </div>\n";

    }
   
   mysqli_close($db);

   return $text;
 }

?>
