<?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 - Positional 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_batstart($team_id);

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

  exit;


##### Page Generation Functions #####

##############################################################################################
# gen_batstart - Positional Starters Chart
##############################################################################################
function gen_batstart($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="";

   ##### Check DH Settings #####
   $query="SELECT sub_league_id,designated_hitter FROM sub_leagues WHERE league_id=$lgid;";
   $result=mysqli_query($db,$query);
   while ($row=mysqli_fetch_array($result))
    {
      $slid=$row['sub_league_id'];
      $subleagues[$slid]['dh']=$row['designated_hitter'];
    }
   ## Get Implementation Dates
   $query="SHOW TABLES LIKE 'ootp_sql_admin';";
   $result=mysqli_query($db,$query);
   if (mysqli_num_rows($result)) 
   {
	   # Get Settings
	   $query="SELECT identifier,value FROM ootp_sql_admin WHERE scope=$lgid AND setting='dhYear'";
	   $result=mysqli_query($db,$query);
 	   if (mysqli_num_rows($result))
	   {
 		   while ($row=mysqli_fetch_array($result))
		   {
			   $slid=$row['identifier'];
			   $val=$row['value'];

			   $subleagues[$slid]['yrchg']=$value;
 		   }
	   }
   }

   ##### Get Depth #####
   $query="SELECT year,pcf.player_id,first_name,last_name,pcf.position,(ip*3+ipf)/3 as ip,g FROM players_career_fielding_stats as pcf,players as p WHERE pcf.player_id=p.player_id AND pcf.team_id=$tid AND pcf.position NOT IN (1,10) ORDER BY year,position,ip DESC,g DESC;";
   $result=mysqli_query($db,$query);
   while ($row=mysqli_fetch_array($result))
    {
      $yr=$row['year'];
      $pid=$row['player_id'];
      $pos=$row['position'];
      $fi=$row['first_name'];
      $fi=$fi[0];
      $name=$fi.". ".$row['last_name'];
      $sortname=$row['last_name'].", ".$row['first_name'];
      $ip=$row['ip'];
      if ($pos==10) {$ip=$row['g'];}

      $players[$pid]['name']=$name;
      $playerSort[$pid]=$sortname;

      $prevIP=$years[$yr][$pos]['maxIP'];
      if ((!isset($years[$yr][$pos]['maxIP']))||($prevIP<$ip))
       {
         $years[$yr][$pos]['maxIP']=$ip;
	 $years[$yr][$pos]['pid']=$pid;
	 $years[$yr][$pos]['name']=$name;
	 $years[$yr][$pos]['sortname']=$sortname;
       }
    }

   ##### Get Team Record #####
   $query="SELECT thr.year,g,w,l,pos,gb,th.sub_league_id 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,t.sub_league_id 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'];
      $slid=$row['sub_league_id'];

      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;

      $dhBool=$subleagues[$slid]['dh'];
      if ((($dhBool==1)&&($yr>=$subleagues[$slid]['yrchg']))||(($dhBool!=1)&&($yr<$subleagues[$slid]['yrchg'])))
       {
         $years[$yr]['dh']=1;
	 $showDH=1;
       }
      if ($_GET['showq']==1) {$text.="$yr::$slid::$dhBool::".$subleagues[$slid]['yrchg']."<br/>\n";}
    }

   ##### Get DH's If Applicable #####
   if ($showDH==1)
    { 
      ## Get Players
      $query="SELECT * FROM (SELECT p.player_id,first_name,last_name,year,g,gf,IF(gf IS NULL,g,g-gf) as dhG FROM players as p,(SELECT t1.player_id,t1.year,g,gf FROM (SELECT player_id,year,SUM(g) as g FROM players_career_batting_stats WHERE league_id=$lgid AND team_id=$tid AND split_id=1 GROUP BY player_id,year) as t1 LEFT JOIN (SELECT player_id,year,SUM(g) as gf FROM players_career_fielding_stats WHERE league_id=$lgid AND team_id=$tid AND position!=10 GROUP BY player_id,year) as t2 ON t1.player_id=t2.player_id AND t1.year=t2.year) as x WHERE p.player_id=x.player_id) as x2 ORDER BY year,dhG DESC";
      $result=mysqli_query($db,$query);
      while ($row=mysqli_fetch_array($result))
       {
         $yr=$row['year'];
         if ($years[$yr]['dh']!=1) {continue;}
	 $pid=$row['player_id'];
	 $fi=$row['first_name'];
   	 $fi=$fi[0];
	 $name=$fi.". ".$row['last_name'];
   	 $sortname=$row['last_name'].", ".$row['first_name'];

	 $players[$pid]['name']=$name;
	 $playerSort[$pid]=$sortname;

	 $g=$row['dhG'];
	 $prevG=$years[$yr][10]['maxG'];
   	 if ((!isset($years[$yr][10]['maxG']))||($prevG<$g))
	  {
            $fnd=0;
	    for ($i=2;$i<=9;$i++)
	     {
	       if ($pid==$years[$yr][$i]['pid']) {$fnd=1;}
	     }
	    if ($fnd==1) {continue;}
  	    $years[$yr][10]['maxG']=$g;
	    $years[$yr][10]['maxRat']=$paRat;
	    $years[$yr][10]['pid']=$pid;
   	    $years[$yr][10]['name']=$name;
	    $years[$yr][10]['sortname']=$sortname;
	  }
       }
    }

   for ($i=2;$i<=10;$i++) {$prevPid[$i]=-1;$posCnt[$i]=-1;}

   ksort($years);

   ##### Display Results #####
   $text.="<div class='textbox'>\n";
   $text.=" <table cellpadding=0 cellspacing=0 border=0>\n";
   $text.="  <tr class='title'><td style='padding:2px;'>Most Frequently Used Players By Position</td></tr>\n";
   $text.="  <tr><td>\n";
   $text.="   <table cellpadding=2 cellspacing=0 border=0 class='sortable' width='935px'>\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_l'>C</td><td class='hsc2_l'>1B</td><td class='hsc2_l'>2B</td><td class='hsc2_l'>3B</td><td class='hsc2_l' style='border-right:1px solid black;'>SS</td><td class='hsc2_l'>LF</td><td class='hsc2_l'>CF</td><td class='hsc2_l'";
   if ($showDH==1) {$text.=" style='border-right:1px solid black;'";}
   $text.=">RF</td>";
   if ($showDH==1) {$text.="<td class='hsc2_l'>DH</td>";}
   $text.="</tr></thead>\n";
   $rowCnt=0;
   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>";}
      for ($i=2;$i<=(9+$showDH);$i++)
       {
         $pid=$years[$yr][$i]['pid'];
	 $name=$years[$yr][$i]['name'];
	 $sortname=$years[$yr][$i]['sortname'];
	 $prev=$prevPid[$i];
	 if ($pid!=$prev) {$posCnt[$i]++;}
	 $posCls='s'.($posCnt[$i]%2+1);
	 if ($name!="")
	  {
            switch ($i)
 	     {
	       case 2 : $c[$pid]=$c[$pid]+1; break;
	       case 3 : $fb[$pid]=$fb[$pid]+1; break;
	       case 4 : $sb[$pid]=$sb[$pid]+1; break;
	       case 5 : $tb[$pid]=$tb[$pid]+1; break;
	       case 6 : $ss[$pid]=$ss[$pid]+1; break;
	       case 7 : $lf[$pid]=$lf[$pid]+1; break;
	       case 8 : $cf[$pid]=$cf[$pid]+1; break;
	       case 9 : $rf[$pid]=$rf[$pid]+1; break;
	       case 10: $dh[$pid]=$dh[$pid]+1; break;
	     }
	  }
	 switch ($i)
	  {
	    case 6:
	       if ($name=="") {$text.="<td class='".$posCls."_l' style='border-right:1px solid black;'>&nbsp;</td>";}
	        else {$text.="<td class='".$posCls."_l' style='border-right:1px solid black;' sorttable_customkey=\"".$sortname."\"><a href='./player.php?player_id=$pid'>$name</a></td>";}
	       break;
            case 9:
                if ($showDH==1)
		 {
		   if ($name=="") {$text.="<td class='".$posCls."_l' style='border-right:1px solid black;'>&nbsp;</td>";}
		    else {$text.="<td class='".$posCls."_l' style='border-right:1px solid black;' sorttable_customkey=\"".$sortname."\"><a href='./player.php?player_id=$pid'>$name</a></td>";}
		 }
		 else
		 {
		   if ($name=="") {$text.="<td class='".$posCls."_l'>&nbsp;</td>";}
		    else {$text.="<td class='".$posCls."_l' sorttable_customkey=\"".$sortname."\"><a href='./player.php?player_id=$pid'>$name</a></td>";}
		 }
	       break;
   	    default:
	       if ($name=="") {$text.="<td class='".$posCls."_l'>&nbsp;</td>";}
	        else {$text.="<td class='".$posCls."_l' sorttable_customkey=\"".$sortname."\"><a href='./player.php?player_id=$pid'>$name</a></td>";}
	       break;
	  }

         if ($pid!="") {$prevPid[$i]=$pid;}
       }
      $text.="</tr>\n";
      $rowCnt++;
    }
   $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($c)==1) {$text.="<td class='hsc2'>".count($c)." player</td>";} else {$text.="<td class='hsc2'>".count($c)." players</td>";}
   if (count($fb)==1) {$text.="<td class='hsc2'>".count($fb)." player</td>";} else {$text.="<td class='hsc2'>".count($fb)." players</td>";}
   if (count($sb)==1) {$text.="<td class='hsc2'>".count($sb)." player</td>";} else {$text.="<td class='hsc2'>".count($sb)." players</td>";}
   if (count($tb)==1) {$text.="<td class='hsc2'>".count($tb)." player</td>";} else {$text.="<td class='hsc2'>".count($tb)." players</td>";}
   if (count($ss)==1) {$text.="<td class='hsc2' style='border-right:1px solid black;'>".count($ss)." player</td>";} else {$text.="<td class='hsc2' style='border-right:1px solid black;'>".count($ss)." players</td>";}
   if (count($lf)==1) {$text.="<td class='hsc2'>".count($lf)." player</td>";} else {$text.="<td class='hsc2'>".count($lf)." players</td>";}
   if (count($cf)==1) {$text.="<td class='hsc2'>".count($cf)." player</td>";} else {$text.="<td class='hsc2'>".count($cf)." players</td>";}
   if ($showDH==1)
    {
      if (count($rf)==1) {$text.="<td class='hsc2' style='border-right:1px solid black;'>".count($rf)." player</td>";} else {$text.="<td class='hsc2' style='border-right:1px solid black;'>".count($rf)." players</td>";}
      if (count($dh)==1) {$text.="<td class='hsc2'>".count($dh)." player</td>";} else {$text.="<td class='hsc2'>".count($dh)." players</td>";}
    }
    else
    {
      if (count($rf)==1) {$text.="<td class='hsc2'>".count($rf)." player</td>";} else {$text.="<td class='hsc2'>".count($rf)." players</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($c);
   $text.="<td class='hsc2'>";
   $flg=0;$prevCnt=-1;
   foreach ($c 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($fb);
   $text.="<td class='hsc2'>";
   $flg=0;$prevCnt=-1;
   foreach ($fb 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($sb);
   $text.="<td class='hsc2'>";
   $flg=0;$prevCnt=-1;
   foreach ($sb 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($tb);
   $text.="<td class='hsc2'>";
   $flg=0;$prevCnt=-1;
   foreach ($tb 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($ss);
   $text.="<td class='hsc2' style='border-right:1px solid black;'>";
   $flg=0;$prevCnt=-1;
   foreach ($ss 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($lf);
   $text.="<td class='hsc2'>";
   $flg=0;$prevCnt=-1;
   foreach ($lf 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($cf);
   $text.="<td class='hsc2'>";
   $flg=0;$prevCnt=-1;
   foreach ($cf 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($rf);
   $text.="<td class='hsc2'";
   if ($showDH==1) {$text.=" style='border-right:1px solid black;'";}
   $text.=">";
   $flg=0;$prevCnt=-1;
   foreach ($rf 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>";
   if ($showDH==1)
    {
      $text.="<td class='hsc2'>";
      if (isset($dh)) 
       {
         arsort($dh);
         $flg=0;$prevCnt=-1;
         foreach ($dh 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;
         }
       }
       else {$text.="&nbsp;";}
    }
   $text.="</td>";
   $text.="</tr>\n";   $text.="    </tfoot>\n";

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

   $text.="<div class='textbox' style='border:0;width:935px;'><b>Note:</b> DH is player with most games played while not appearing in the field nor filling another defensive position as the most frequently used player.</div>";

   mysqli_close($db);

   return $text;
 }

?>
