<?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'];

  if (($tyear==0)||($tyear=="")) {header("Location: ./team_hist.php?team_id=$team_id");}

	  
  ##### 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 Schedule";
  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_schedule($team_id,$tyear);

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

  exit;

##############################################################################################
# gen_year - Year Summary
##############################################################################################
function gen_schedule($tid="",$year="")
 {
     if (!is_numeric($year)) {return "Please select a valid year";}
     
   ##### Exit if no team_id #####
   if (($tid=="")||($year=="")) {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";}

     $query="SHOW TABLES LIKE 'z_games_".$year."';";
     $result=mysqli_query($db,$query);
     if (mysqli_num_rows($result)<1) {return "Game logs for $year are unavailable";}

   ##### Get basic parameters #####
   $date=new DateTime($_SESSION['lgdate']);
   $thisYear=$_SESSION['lgyear'];
   $lgpath=$_SESSION['lgpath'];
   if (isset($_GET['lgid'])) {$lgid=$_GET['lgid'];} else {$lgid="";}
   if ($lgid=="") {$lgid=$_SESSION['lgid'];}
   if ($lgid=="") {$lgid=100;}
   $text="";
	 
	 ##### Get League Abbr #####
	 $query="SELECT abbr FROM leagues WHERE league_id=$lgid;";
     if ($_GET['showq']==1) {$text.=$query."<br/>\n";}
	 $result=mysqli_query($db,$query);
	 $row=mysqli_fetch_array($result);
	 $lgAbbr=$row['abbr'];
	 
	 ##### Get Subleague #####
     $query="SELECT team_id,t.sub_league_id,sl.abbr FROM ";
	 if ($year==$thisYear) {$query.="teams";} else {$query.="team_history";}
	 $query.=" as t,sub_leagues as sl WHERE t.sub_league_id=sl.sub_league_id AND t.league_id=sl.league_id AND t.league_id=$lgid";
     $query.=" AND year=$year";
     if ($_GET['showq']==1) {$text.=$query."<br/>\n";}
	 $result=mysqli_query($db,$query);
	 while ($row=mysqli_fetch_array($result))
	 {
		 $team_id=$row['team_id'];
		 $slID=$row['sub_league_id'];
		 if ($team_id==$tid) {$slAbbr=$row['abbr'];$tmSLid=$slID;}
		 if (!isset($subleagues[$slID]['teamList'])) {$subleagues[$slID]['teamList']="$team_id";} else {$subleagues[$slID]['teamList']=$subleagues[$slID]['teamList'].",".$team_id;}
	 }
	 $teamList=trim($subleagues[$tmSLid]['teamList'],",");
     
     ##### Get Teams #####
     $query="SELECT team_id,sub_league_id,division_id,abbr,name,nickname FROM team_history WHERE year=$year AND league_id=$lgid";
     if ($_GET['showq']==1) {$text.=$query."<br/>\n";}
     $result=mysqli_query($db,$query);
     while ($row=mysqli_fetch_array($result))
     {
         $team_id=$row['team_id'];
         $slid=$row['sub_league_id'];
         $divid=$row['division_id'];
         $divid=$slid."_".$divid;
         $teams[$team_id]['slid']=$slid;
         $teams[$team_id]['divid']=$divid;
         $teams[$team_id]['name']=$row['name']." ".$row['nickname'];
         $teams[$team_id]['abbr']=$row['abbr'];
     }

     ## Initialize Team Wins
     $gtypes=Array(0,2,3);

     ## Get Pitchers
     $pquery="SELECT p.player_id,first_name,last_name FROM players as p,(";
     $pquery.="SELECT DISTINCT pitcher FROM (";
     $pquery.="SELECT DISTINCT winning_pitcher as pitcher FROM z_games_$year WHERE (home_team=$tid OR away_team=$tid)";
     $pquery.=" AND game_type=0";
     $pquery.=" UNION ";
     $pquery.="SELECT DISTINCT losing_pitcher as pitcher FROM z_games_$year WHERE (home_team=$tid OR away_team=$tid)";
     $pquery.=" AND game_type=0";
     $pquery.=" UNION ";
     $pquery.="SELECT DISTINCT save_pitcher as pitcher FROM z_games_$year WHERE (home_team=$tid OR away_team=$tid)";
     $pquery.=" AND game_type=0";
     $pquery.=") as t0";
     $pquery.=") as t1 WHERE p.player_id=t1.pitcher";
     if ($_GET['showq']==1) {$text.=$pquery."<br/>\n";}
     $presult=mysqli_query($db,$pquery);
     
     $pList="";
     while ($row=mysqli_fetch_array($presult))
     {
         $pid=$row['player_id'];
         $pname=$row['first_name']." ".$row['last_name'];
         $psort=$row['last_name'].", ".$row['first_name'];
         $players[$pid]['name']=$pname;
         $players[$pid]['sort']=$psort;
         
         foreach ($gtypes as $key => $gtype)
         {
             $players[$pid]['w'][$gtype]=0;
             $players[$pid]['l'][$gtype]=0;
             $players[$pid]['s'][$gtype]=0;
         }
         $pList.=",".$pid;
     }
     
   ##### Get All-Star Game Date #####
   $query="SELECT * FROM z_games_".$year." WHERE league_id=$lgid AND game_type=4";
   if ($_GET['showq']==1) {$text.=$query."<br/>\n";}
   $result=mysqli_query($db,$query);
   if (mysqli_num_rows($result)>0)
   {
       $row=mysqli_fetch_array($result);
       $asDate=new DateTime($row['date']);
   }

   ##### Get Games Played #####
   $query="SELECT * FROM z_games_".$year." WHERE league_id=$lgid AND (home_team=$tid OR away_team=$tid) ORDER BY date,time,game_id";
   if ($_GET['showq']==1) {$text.=$query."<br/>\n";}
   $result=mysqli_query($db,$query);

   ##### Display Results #####
   if (mysqli_num_rows($result)>0)
   {
       foreach ($gtypes as $val => $gtype)
       {
           $teams[$tid]['w'][$gtype]=0;
           $teams[$tid]['l'][$gtype]=0;
       }
       
       $text.=" <div class='textbox'>\n";
       $text.="  <table cellpadding=0 cellspacing=0 border=0><tr class='title2'><td>Game Logs</td></tr>\n";
       $text.="   <tr><td>\n";
       $text.="     <table cellpadding=2 cellspacing=0 border=0 class='sortable' style='width:935px;'>\n";
       $text.="      <thead><tr class='headline'>\n";
       $text.="       <td class='hsc2_l'>Date</td><td class='hsc2_l'>Opp</td><td class='hsc2_l'>Time</td><td class='hsc2_l'>Result</td><td class='hsc2'>&nbsp;</td><td class='hsc2_l'>W-L</td><td class='hsc2_l'>Type</td><td class='hsc2_l'>Win</td><td class='hsc2_l'>Loss</td><td class='hsc2_l'>Save</td><td class='hsc2'>Attendance</td>\n";
       $text.="    </tr></thead>\n";
       
       $cnt=0;
       $prevGtype="";
       $prevDate="";
       while ($row=mysqli_fetch_array($result))
       {
           $gid=$row['game_id'];
           $gtype=$row['game_type'];
           
           unset($gdate);
           $gdate=new DateTime($row['date']);
           $gtime=$row['time'];
           
           $gt1=substr($gtime,0,2);
           $gt2=substr($gtime,2,2);
           
           if ($gt1==0) {$gtime="12:$gt2 am";}
           elseif ($gt1==12) {$gtime="12:$gt2 pm";}
           elseif ($gt1>12) {$gtime=($gt1-12).":$gt2 pm";}
           else {$gtime="$gt1:$gt2 am";}
           $gtype=$row['game_type'];
           
           switch ($gtype)
           {
               case 0: $gtAbbr="REG"; break;
               case 2: $gtAbbr="ST"; break;
               case 3: $gtAbbr="PS"; break;
           }
           $hid=$row['home_team'];
           $aid=$row['away_team'];
           
           $aruns=$row['runs0'];
           $hruns=$row['runs1'];
           
           if ($hid==$tid)
           {
               $games[$gid]['home']=1;
               $oppAbbr=$teams[$aid]['abbr'];
               $opponent="<a href='./team_summary.php?league_id=$lgid&team_id=$aid&year=$year'>".$teams[$aid]['abbr']."</a>";
               
               if ($hruns>$aruns)
               {
                   $games[$gid]['result']='w';
                   $score="Win, $hruns-$aruns";
                   $teams[$hid]['w'][$gtype]=$teams[$hid]['w'][$gtype]+1;
               }
               else
               {
                   $games[$gid]['result']='l';
                   $score="Loss, $hruns-$aruns";
                   $teams[$hid]['l'][$gtype]=$teams[$hid]['l'][$gtype]+1;
               }
           }
           else
           {
               $games[$gid]['home']=0;
               $oppAbbr=$teams[$hid]['abbr'];
               $opponent="<a href='./team_summary.php?league_id=$lgid&team_id=$hid&year=$year'>@ ".$teams[$hid]['abbr']."</a>";
               
               if ($aruns>$hruns)
               {
                   $games[$gid]['result']='w';
                   $score="Win, $aruns-$hruns";
                   $teams[$aid]['w'][$gtype]=$teams[$aid]['w'][$gtype]+1;
               }
               else
               {
                   $games[$gid]['result']='l';
                   $score="Loss, $aruns-$hruns";
                   $teams[$aid]['l'][$gtype]=$teams[$aid]['l'][$gtype]+1;
               }
           }
           
           $inn=$row['innings'];
           $winP=$row['winning_pitcher'];
           if (!isset($players[$winP])) {$winP=-1;}
           else {$players[$winP]['w'][$gtype]=$players[$winP]['w'][$gtype]+1;}
           $lossP=$row['losing_pitcher'];
           if (!isset($players[$lossP])) {$lossP=-1;}
           else {$players[$lossP]['l'][$gtype]=$players[$lossP]['l'][$gtype]+1;}
           $svP=$row['save_pitcher'];
           if ($svP==0) {1;}
           elseif (!isset($players[$svP])) {$svP=-1;}
           else {$players[$svP]['s'][$gtype]=$players[$svP]['s'][$gtype]+1;}
           
           if (($hid!=$tid)&&($aid!=$tid)) {continue;}
           
           if (($prevGtype!="")&&($prevGtype!=$gtype)) {$style=" style='border-top:3px double black;'";}
           else
           {
               $style="";
               
               ## Check for off days
               if ($prevDate!="")
               {
                   $interval = $gdate->diff($prevDate);
                   $days_difference = $interval->days;
                   
                   for ($i=1;$i<$days_difference;$i++)
                   {
                       $cls='s'.($cnt%2+1);
                       $text.="      <tr class='$cls'><td colspan=7 class='hc'>";
                       if (isset($asDate))
                       {
                           $asInt = $gdate->diff($asDate);
                           $asDaysDiff = $asInt->days;
                           if ($i==($days_difference - $asDaysDiff))
                           {
                               $text.="- - - All-Star Game - - -";
                           }
                           else
                           {
                               $text.="--- Off Day ---";
                           }
                       }
                       else
                       {
                           $text.="--- Off Day ---";
                       }
                       $text.="</td><td colspan=4>&nbsp;</td></tr>";
                       $cnt++;
                   }
                       
               }
           }
           
           $cls='s'.($cnt%2+1);
           $text.="      <tr class='$cls'>";
           $text.="<td class='".$cls."_l'$style sorttable_customkey='".$gdate->format("Ymd")."'>".$gdate->format("m-d-Y")."</td>";
           
           $text.="<td class='".$cls."_l'$style sorttable_customkey='$oppAbbr'>$opponent</td>";
           
           $text.="<td class='".$cls."_l'$style>$gtime</td>";
           
           $text.="<td class='".$cls."_l'$style>$score</td>";
           
           $text.="<td class='".$cls."_l'$style>";
           if ($inn>9) {$text.=" $inn Inn";} else {$text.="&nbsp;";}
           $text.="</td>";
           
           $text.="<td class='".$cls."_l'$style>".$teams[$tid]['w'][$gtype]."-".$teams[$tid]['l'][$gtype]."</td>";
           
           $text.="<td class='".$cls."_l'$style>$gtAbbr</td>";
           
           if ($winP==-1) {$text.="<td class='".$cls."_l'$style' title='Minor leaguer since purged from database'>n/a</td>";}
           else
           {
               $text.="<td class='".$cls."_l'$style";
               $text.=" sorttable_customkey='".$players[$winP]['sort']."'><a href='./player.php?player_id=$winP'>".$players[$winP]['name']."</a>";
               $text.=" (".$players[$winP]['w'][$gtype]."-".$players[$winP]['l'][$gtype].")";
               $text.="</td>";
           }
           
           if ($lossP==-1) {$text.="<td class='".$cls."_l'$style' title='Minor leaguer since purged from database'>n/a</td>";}
           else
           {
               $text.="<td class='".$cls."_l'$style";
               $text.=" sorttable_customkey='".$players[$lossP]['sort']."'><a href='./player.php?player_id=$lossP'>".$players[$lossP]['name']."</a>";
               $text.=" (".$players[$lossP]['w'][$gtype]."-".$players[$lossP]['l'][$gtype].")";
               $text.="</td>";
           }
           
           $text.="<td class='".$cls."_l'$style";
           if ($svP==0) {$text.=">-";}
           elseif ($svP==-1) {$text.=" title='Minor leaguer since purged from database'>n/a";}
           else
           {
               $text.=" sorttable_customkey='".$players[$svP]['sort']."'><a href='./player.php?player_id=$svP'>".$players[$svP]['name']."</a>";
               $text.=" (".$players[$svP]['s'][$gtype].")";
           }
           $text.="</td>";
           
           $text.="<td$style>".number_format($row['attendance'],0,".",",")."</td>";
           $text.="</tr>\n";
           
           $prevGtype=$gtype;
           $prevDate=$gdate;
           $cnt++;
       }
       
       $text.="     </table>\n";
       $text.="   </td></tr>\n";
       $text.="  </table>\n";
       $text.=" </div>\n";
   }
     
     mysqli_close($db);
     return $text;
}

?>
