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

  ################## PAGE INITIALIZATION #########################
  $lgid=$_SESSION['lgid'];
  $lgpath=$_SESSION['lgpath'];
  $date=new DateTime($_SESSION['lgdate']);
  $lgyear=$_SESSION['lgyear'];

  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'];
	  
  ##### 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 - Pitching Starters";
  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 #####
  echo gen_pitstart($team_id);

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

  exit;

  
##############################################################################################
# gen_pitstart - Pitching Starters Chart
##############################################################################################
function gen_pitstart($tid="")
 {
   ##### Exit if no team_id #####
   if ($tid=="") {exit;}
   include($_SESSION['adminpath']."/dbopen.php");

   ##### Check for tables #####
   $query="SHOW TABLES LIKE 'team_history%';";
   $result=mysqli_query($db,$query);
   if (mysqli_num_rows($result)<5) {return "Please load the team_history SQL tables first";}

   ##### Get basic parameters #####
   $date=new DateTime($_SESSION['lgdate']);
   $year=$_SESSION['lgyear'];
   $lgpath=$_SESSION['lgpath'];
   $lgid=$_GET['lgid'];
   if ($lgid=="") {$lgid=$_SESSION['lgid'];}
   if ($lgid=="") {$lgid=100;}
   $text="";

   ##### Get Pitchers #####
   $query="SELECT year,pcp.player_id,first_name,last_name,g,gs,w,l,s,(ip*3+ipf)/3 as ip,er FROM players_career_pitching_stats as pcp,players as p WHERE pcp.player_id=p.player_id AND pcp.team_id=$tid AND split_id=1 ORDER BY year,gs DESC,ip DESC;";
   $result=mysqli_query($db,$query);
   while ($row=mysqli_fetch_array($result))
    {
      $yr=$row['year'];
      $pid=$row['player_id'];
      $fi=$row['first_name'];
      $fi=$fi[0];
      $name=$fi.". ".$row['last_name'];
      $g=$row['g'];
      $gs=$row['gs'];
      $w=$row['w'];
      $l=$row['l'];
      $s=$row['s'];
      $ip=$row['ip'];
      $er=$row['er'];

      if ($ip==0) {$era=0;}
       else {$era=(9*$er)/$ip;}
      $era=sprintf("%.2f",$era);

      $years[$yr]['found']=1;

      $players[$pid]['name']=$name;
      $players[$pid][$yr]['w']=$w;
      $players[$pid][$yr]['l']=$l;
      $players[$pid][$yr]['sv']=$s;
      $players[$pid][$yr]['era']=$era;
      $players[$pid][$yr]['g']=$g;

      $prevSV=$cl[$yr]['maxSV'];
      if (($prevSV<$s)&&($s>0))
       {
         $cl[$yr]['maxSV']=$s;
	 $cl[$yr]['pid']=$pid;
       }

      if ($gs>0) {$sp[$yr][$pid]=$gs;}
      $rp[$yr][$pid]=$g;
    }

   ##### Get Team Record #####
   $query="SELECT thr.year,g,w,l,pos,gb FROM team_history_record as thr,team_history as th WHERE thr.team_id=th.team_id AND thr.year=th.year AND thr.team_id=$tid UNION SELECT '$year' as year,g,w,l,pos,gb FROM team_record as tr,teams as t WHERE tr.team_id=t.team_id AND tr.team_id=$tid ORDER BY year;";
   $result=mysqli_query($db,$query);
   while ($row=mysqli_fetch_array($result))
    {
      $yr=$row['year'];
      $g=$row['g'];
      if (($yr==0)||($g==0)) {continue;}
      $l=$row['l'];
      $w=$row['w'];
      $pos=$row['pos'];
      $gb=$row['gb'];

      if ($g==0) {$wpct=0;} else {$wpct=$w/$g;}
      $wpct=sprintf("%.3f",$wpct);
      if ($wpct<1) {$wpct=strstr($wpct,".");}

      $Tyr+=1;
      $Tg+=$g;
      $Tw+=$w;
      $Tl+=$l;
      $Tpos+=$pos;

      $years[$yr]['g']=$g;
      $years[$yr]['w']=$w;
      $years[$yr]['l']=$l;
      $years[$yr]['wpct']=$wpct;
      $years[$yr]['pos']=$pos;
    }

   ##### Display Results #####
   $text.="<div class='textbox'>\n";
   $text.=" <table cellpadding=0 cellspacing=0 border=0 width='935px'>\n";
   $text.="  <tr class='title'><td style='padding:2px;'>Pitching Staff By Role</td></tr>\n";
   $text.="  <tr><td>\n";
   $text.="   <table cellpadding=2 cellspacing=0 border=0 class='sortable' width='100%'>\n";
   $text.="    <thead><tr class='headline'><td class='hsc2_l'>Year</td><td class='hsc2'>W</td><td class='hsc2'>L</td><td class='hsc2'>WPct</td><td class='hsc2' style='border-right:1px solid black;'>Fin</td><td class='hsc2' colspan=5 style='border-right:1px solid black;text-align:center;'>Starting Pitchers</td><td class='hsc2' style='border-right:1px solid black;text-align:center;'>Closer</td><td class='hsc2' colspan=3 style='border-right:1px solid black;text-align:center;'>Bullpen</td>";
   $text.="</tr></thead>\n";
   $rowCnt=0;
   for ($i=1;$i<=9;$i++) {$slotCnt[$i]=-1;}
   foreach ($years as $yr => $val)
    {
      $cls='s'.($rowCnt%2+1);
      $text.="    <tr class='$cls'><td class='".$cls."_l'><a href='./team_summary.php?team_id=$tid&year=$yr'>$yr</a></td>";
      $text.="<td>".$years[$yr]['w']."</td>";
      $text.="<td>".$years[$yr]['l']."</td>";
      $text.="<td>".$years[$yr]['wpct']."</td>";
      $finish=$years[$yr]['pos'];
      if ($finish=="") {$text.="<td style='border-right:1px solid black;'>&nbsp;</td>";}
      else {$text.="<td style='border-right:1px solid black;'>".ordinal_suffix($finish,1)."</td>";}
      ##Starters
      if (isset($sp[$yr])) {arsort($sp[$yr]);}
      $spCnt=0;
      unset($slot);
      unset($pslot);
      if (isset($sp[$yr])) 
       {
         foreach ($sp[$yr] as $pid => $val)
          {
            $spCnt++;
            if ($spCnt>5) {unset($sp[$yr][$pid]);}  #only first 5
	     else
	     {
	       $slot[$spCnt]=$pid;
	       $pslot[$pid]=$spCnt;
	     }
          }
      }
      for ($j=1;$j<=5;$j++)
       {
         for ($i=1;$i<=5;$i++)
          {
            $pid=$slot[$i];
	    $tmpSLOT=$lastSlot[$pid];
	    if (($i!=$tmpSLOT)&&(isset($lastSlot[$pid]))&&($tmpSLOT<6))
	     {
               $tmpPID=$slot[$tmpSLOT];
	       $slot[$tmpSLOT]=$pid;
	       $pslot[$pid]=$tmpSLOT;
	       $slot[$i]=$tmpPID;
   	       $pslot[$tmpPID]=$i;
  	     }
          }
       }
      for ($i=1;$i<=5;$i++)
       {
	 if ($i==5) {$style=" style='border-right:1px solid black;'";} else {$style="";}
         if (isset($slot[$i])) 
          {
            $pid=$slot[$i];
            if ($lastSlot[$pid]!=$i) {$slotCnt[$i]=$slotCnt[$i]+1;}
            $pcls=" class='s".(($slotCnt[$i])%2+1)."_l'";
	    $text.="<td$pcls$style><a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a><br/>".$players[$pid][$yr]['w']."-".$players[$pid][$yr]['l'].", ".$players[$pid][$yr]['era']."</td>";
	    $spyears[$pid]=$spyears[$pid]+1;
	  }
	  else
	  {
	    $slotCnt[$i]=$slotCnt[$i]+1;
	    $pcls=" class='s".(($slotCnt[$i])%2+1)."_l'";
	    $text.="<td$pcls$style>&nbsp;</td>";
 	  }
       }
      unset($lastSlot);
      for ($i=1;$i<=5;$i++) {$pid=$slot[$i];$lastSlot[$pid]=$i;}

      ##Closer
      $pid=$cl[$yr]['pid'];
      if ($pid!="")
       {
	 if ($cllastSlot[$pid]!=6) {$slotCnt[6]=$slotCnt[6]+1;}
	 $pcls=" class='s".(($slotCnt[6])%2+1)."_l'";
	 $text.="<td$pcls style='border-right:1px solid black;'><a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a><br/>".$players[$pid][$yr]['sv']." SV, ".$players[$pid][$yr]['era']."</td>";
	 $clyears[$pid]=$clyears[$pid]+1;
       }
       else
       {
         $slotCnt[$i]=$slotCnt[$i]+1;
         $pcls=" class='s".(($slotCnt[$i])%2+1)."_l'";
	 $text.="<td$pcls style='border-right:1px solid black;'>&nbsp;</td>";
       }
      unset($cllastSlot);
      if ($pid!="") {$cllastSlot[$pid]=6;}

      ##Bullpen
      if (isset($sp[$yr])) {arsort($rp[$yr]);}
      $rpCnt=6;
      unset($slot);
      unset($pslot);
      if (isset($rp[$yr])) 
       {
         foreach ($rp[$yr] as $pid => $val)
          {
            if (($cl[$yr]['pid']==$pid)||(isset($sp[$yr][$pid]))) {continue;}
            $rpCnt++;
            if ($rpCnt>9) {unset($rp[$yr][$pid]);}  #only first 3
	     else
	     {
	       $slot[$rpCnt]=$pid;
	       $pslot[$pid]=$rpCnt;
	     }
	  }
       }
      for ($j=7;$j<=9;$j++)
       {
         for ($i=7;$i<=9;$i++)
          {
            $pid=$slot[$i];
	    $tmpSLOT=$rplastSlot[$pid];
	    if (($i!=$tmpSLOT)&&(isset($rplastSlot[$pid]))&&($tmpSLOT>6))
	     {
               $tmpPID=$slot[$tmpSLOT];
	       $slot[$tmpSLOT]=$pid;
	       $pslot[$pid]=$tmpSLOT;
	       $slot[$i]=$tmpPID;
   	       $pslot[$tmpPID]=$i;
  	     }
          }
       }
      for ($i=7;$i<=9;$i++)
       {
         if (isset($slot[$i])) 
          {
            $pid=$slot[$i];
            if ($rplastSlot[$pid]!=$i) {$slotCnt[$i]=$slotCnt[$i]+1;}
            $pcls=" class='s".(($slotCnt[$i])%2+1)."_l'";
	    $text.="<td$pcls><a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a><br/>".$players[$pid][$yr]['g']." G, ".$players[$pid][$yr]['era']."</td>";
	    $rpyears[$pid]=$rpyears[$pid]+1;
	  }
	  else
	  {
	    $slotCnt[$i]=$slotCnt[$i]+1;
	    $pcls=" class='s".(($slotCnt[$i])%2+1)."_l'";
	    $text.="<td$pcls>&nbsp;</td>";
 	  }
       }
      unset($rplastSlot);
      for ($i=7;$i<=9;$i++) {$pid=$slot[$i];$rplastSlot[$pid]=$i;}
      $text.="</tr>\n";

      $rowCnt++;
    }
   ##Footer
   $text.="    <tfoot>\n";
   $text.="     <tr class='headline'>";
   $text.="<td class='hsc2_l' colspan=5 style='border-right:1px solid black;'>".count($years)." years</td>";
   if (count($spyears)==1) {$text.="<td class='hsc2' coslpan=5 style='border-right:1px solid black;text-align:center;'>".count($spyears)." pitcher</td>";} else {$text.="<td class='hsc2' colspan=5 style='border-right:1px solid black;text-align:center;'>".count($spyears)." pitchers</td>";}
   if (count($clyears)==1) {$text.="<td class='hsc2' style='border-right:1px solid black;text-align:center;'>".count($clyears)." pitcher</td>";} else {$text.="<td class='hsc2' style='border-right:1px solid black;text-align:center;'>".count($clyears)." pitchers</td>";}
   if (count($rpyears)==1) {$text.="<td class='hsc2' colspan=3 style='text-align:center;>".count($rpyears)." pitcher</td>";} else {$text.="<td class='hsc2' colspan=3 style='text-align:center;'>".count($rpyears)." pitchers</td>";}
   $text.="</tr>\n";
   $text.="     <tr class='slb' valign='top'>";
   $text.="<td class='hsc2_l' colspan=5 style='border-right:1px solid black;'>Most Common</td>";
   arsort($spyears);
   $flg=0;
   foreach ($spyears as $pid => $cnt)
   {
      if ($flg>=5) {break;}
      $text.="<td class='hsc2' style='";
      if ($flg==4) {$text.="border-right:1px solid black;";}
      $text.="text-align:center;'><a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a>($cnt)</td>";
      $flg+=1;
      $lastSPcnt=$cnt;
      $spShown[$pid]=1;
    }
   arsort($clyears);
   $text.="<td class='hsc2' rowspan=2 style='border-right:1px solid black;text-align:center;'>";
   $flg=0;$prevCnt=-1;
   foreach ($clyears as $pid => $cnt)
    {
      if ($flg==1) {$text.="<br/>";}
      if ($prevCnt==$cnt) {$text.="<a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a>";}
       elseif ($prevCnt==-1) {$text.="<a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a>($cnt)";}
       else {break;}
      $flg=1;
      $prevCnt=$cnt;
    }
   $text.="</td>";
   arsort($rpyears);
   $flg=0;
   foreach ($rpyears as $pid => $cnt)
   {
      if ($flg>=3) {break;}
      $text.="<td class='hsc2' style='text-align:center;'><a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a>($cnt)</td>";
      $flg+=1;
      $lastRPcnt=$cnt;
      $rpShown[$pid]=1;
    }
   $text.="</tr>\n";
   $text.="     <tr class='slb' valign='top'>";
   $text.="<td class='hsc2_l' colspan=5 style='border-right:1px solid black;'>&nbsp;</td>";
   $flg=0;
   $text.="<td class='hsc2' colspan=5 style='border-right:1px solid black;text-align:center;'>";
   foreach ($spyears as $pid => $cnt)
    {
      if (($flg>=1)&&($lastSPcnt==$cnt)&&(!isset($spShown[$pid])))
       {
         if ($flg>1) {$text.=", ";}
         $text.="<a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a>($cnt)";
         $flg++;
       }
      if (($lastSPcnt==$cnt)&&($flg<1)) {$flg=1;}
    }
   if ($flg<=1) {$text.="&nbsp;";}
   $text.="</td>";
   $flg=0;
   $text.="<td class='hsc2' colspan=3 style='text-align:center;'>";
   foreach ($rpyears as $pid => $cnt)
    {
      if (($flg>=1)&&($lastRPcnt==$cnt)&&(!isset($rpShown[$pid])))
       {
         if ($flg>1) {$text.=", ";}
         $text.="<a href='./player.php?player_id=$pid'>".$players[$pid]['name']."</a>($cnt)";
         $flg++;
       }
      if (($lastRPcnt==$cnt)&&($flg<1)) {$flg=1;}
    }
   if ($flg<=1) {$text.="&nbsp;";}
   $text.="</td>";
   $text.="</tr>\n";
   $text.="    </tfoot>\n";

   $text.="   </table>\n";
   $text.="  </td></tr>\n";
   $text.=" </table>\n";
   $text.="</div>   <!-- END of Pitching Depth -->\n";

   mysqli_close($db);

   return $text;
 }

?>
