<?php

  include("html_functions.php");



  ################## PAGE INITIALIZATION #########################

  $lgid=$_SESSION['lgid'];

  

  $lgpath=$_SESSION['lgpath'];

  $adminpath=$_SESSION['adminpath'];

  $htmlpath=$_SESSION['htmlpath'];

  $date=new DateTime($_SESSION['lgdate']);

  $lgyear=$_SESSION['lgyear'];



  $module="All-Star";



  include($_SESSION['adminpath']."/dbopen.php");



  # Check if awards vote table exists

  $query="SHOW TABLES LIKE 'awards_vote';";

  $result=mysqli_query($db,$query);

  if (!mysqli_num_rows($result))

  {

	  ##### Initialize Table #####

	  $query="CREATE TABLE IF NOT EXISTS awards_vote (player_id INT, league_id INT, sub_league_id INT, year SMALLINT, human_manager_id INT, award_id SMALLINT, position SMALLINT, vote INT DEFAULT 0, PRIMARY KEY (player_id, league_id, sub_league_id, year, human_manager_id, award_id));";

	  $result=mysqli_query($db,$query);

  }

  # Check Admin Table

  $module='All-Star';

  $query="SHOW TABLES LIKE 'ootp_sql_admin';";

  $result=mysqli_query($db,$query);

  if (mysqli_num_rows($result)) 

  {

	  # Get Settings

	  $query="SELECT setting,value FROM ootp_sql_admin WHERE scope IN ('ALL',$lgid) AND (module='$module' OR setting='showAllUsers')";

	  if ($_GET['showq']==1) {echo "$query<br/>\n";}

	  $result=mysqli_query($db,$query);

	  if (mysqli_num_rows($result))

	  {

		  while ($row=mysqli_fetch_array($result))

		  {

			  $field=$row['setting'];

		 	  $val=$row['value'];

			  $val=stripslashes($val);

		 	  switch ($field)

			  {

	  		  case 'asVotingOn' : $asVotingOn=$val;  break;

	  		  case 'asModEnable': $asModEnable=$val; break;

			  case 'asResults'  : $asResults=$val;   break;

	  		  case 'minPA'      : $minPA=$val;       break;

			  case 'minFIP'     : $minFIP=$val;      break;

	  		  case 'qOnTotFIP'  : $qOnTotFIP=$val;   break;

			  case 'splitOF'    : $splitOF=$val;     break;

      			  case 'DHconfig'   : $DHconfig=$val;    break;

			  case 'minGS'      : $minGS=$val;       break;

	  		  case 'minIPs'     : $minIPs=$val;      break;

			  case 'minIPr'     : $minIPr=$val;      break;

	  		  case 'minSV'      : $minSV=$val;       break;

			  case 'maxGSpct'   : $maxGSpct=$val;    break;

	  		  case 'showAllUsers': $showAllUsers=$val; break;

			  }

		  }

	  }

  }

  if ($splitOF=="") {$splitOF=0;}

  if (($DHconfig!=1)&&($DHconfig!=2)) {$DHconfig=0;}

  if ($minPA=="") {$minPA=3.1;}

  if ($minFIP=="") {$minFIP=4.5;}	

  if ($minIPs=="") {$minIPs=1.0;}

  if ($minIPr=="") {$minIPr=0.4;}

  if ($minGS=="") {$minGS=0.5;}

  if ($maxGSpct=="") {$maxGSpct=0.5;}

  

  #Configure position array

  if ($splitOF==1) {$posArray=Array(2,3,4,5,6,7,8,9);}

  else  {$posArray=Array(2,3,4,5,6,20);}

  if ($DHconfig<2) {array_push($posArray,10);}

  array_push($posArray,11);

  array_push($posArray,21);



  mysqli_close($db);



  ################## PAGE INITIALIZATION #########################

  $title='All-Star Voting Admin';



  page_head($title,$_SESSION['lgpath']);

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

  main_titlebar($_SESSION['lgid'],$_SESSION['lgpath'],$title);



  if ($_SESSION['user_is_commish']!=1)

  {

	  nav_toolbar("allstar","All-Star Voting");

	  echo " </div>   <!-- END topbar DIV -->\n";

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

	  echo "You must be a commisioner to access this page";

	

	  ################## END OF PAGE #########################

	  echo " </div>   <!-- END contentpane DIV -->\n";

	  page_foot($_SESSION['lgpath']);

	  exit;

  }

  else

  {

	  nav_toolbar('admin','Admin Pages');

	  nav_toolbar("allstar","All-Star Voting");

	  echo " </div>   <!-- END topbar DIV -->\n";

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

  }



  ################## START OF PAGE CONTENT #########################

  echo " <table cellpadding=0 cellspacing=0 border=0 width='910px'><tr><td valign='top'>\n";

  echo "  <div class='textbox'>\n";



  echo "   <FORM ACTION=\"save_settings.php\" METHOD=\"post\">\n";

  echo "    <input type='hidden' name='module' value='All-Star'>\n";

  if ($_GET['debug']==1) {echo "    <input type='hidden' name='debug' value='1'>\n";}

  echo "    <table cellpadding=2 cellspacing=0>";

  echo "     <TR class='title'><TD colspan=5>All-Star Voting Settings</TD></TR>\n";



  echo "     <TR><TD>Enable Voting:</TD><TD align='left' colspan=4><INPUT type=\"checkbox\" name=\"asVotingOn\" value=1";

  if ($asVotingOn==1) {echo " checked";}

  echo "></TD></TR>\n";

  echo "     <TR><TD>Allow Users To Change Their Vote:</TD><TD align='left' colspan=4><INPUT type=\"checkbox\" name=\"asModEnable\" value=1";

  if ($asModEnable==1) {echo " checked";}

  echo "></TD></TR>\n";

  echo "     <TR><TD>Show Results To All (else, only after voting):</TD><TD align='left'><INPUT type=\"checkbox\" name=\"asResults\" value=1";

  if ($asResults==1) {echo " checked";}

  echo "></TD></TR>\n";

  echo "     <TR class='headline'><TD class='hsc2_l' colspan=2>Batter Settings (per Team Game)</TD></TR>\n";

  echo "     <TR><TD>Minimum Plate Appearances:</TD><TD align='left'><INPUT type=\"text\" size=20 name=\"minPA\" value=\"".$minPA."\"></TD></TR>\n";

  echo "     <TR><TD>Minimum Fielding Innings for Position Qualification:</TD><TD align='left'><INPUT type=\"text\" name=\"minFIP\" value=\"".$minFIP."\"></TD></TR>\n";

  echo "     <TR><TD>Qualify based on total fielding innings:<br />(else, must have qualifying innings at position)</TD><TD align='left'><INPUT 

  	  type=\"checkbox\" name=\"qOnTotFIP\" value=1";

  if ($qOnTotFIP==1) {echo " checked";}

	  echo "></TD></TR>\n";

  echo "     <TR><TD>Split Outfielders by Position:</TD><TD align='left'><INPUT type=\"checkbox\" name=\"splitOF\" value=1";

  if ($splitOF==1) {echo " checked";}

  echo "></TD></TR>\n";

  echo "     <TR><TD>Designated Hitter Voting:</TD>\n";

  echo "      <TD align='left'>\n";

  echo "       <select name='DHconfig'>\n";

  echo "        <option value=0";

  if ($DHconfig==0) {echo " selected";}

  echo ">Follow League Settings</option>\n";

  #echo "        <option value=1";

  #if ($DHconfig==1) {echo " selected";}

  #echo ">All Leagues</option>\n";

  echo "        <option value=2";

  if ($DHconfig==2) {echo " selected";}

  echo ">No DH Voting</option>\n";

  echo "       </select>\n";

  echo "      </TD></TR>\n";

  echo "     <TR class='headline'><TD class='hsc2_l' colspan=2>Pitcher Settings (per Team Game)</TD></TR>\n";

  echo "     <TR><TD>Minimum Innings Pitched for Starters:</TD><TD align='left'><INPUT type=\"text\" name=\"minIPs\" value=\"".$minIPs."\"></TD></TR>\n";

  echo "     <TR><TD>Minimum Innings Pitched for Relievers:</TD><TD align='left'><INPUT type=\"text\" name=\"minIPr\" value=\"".$minIPr."\"></TD></TR>\n";

  echo "     <TR class='headline'><TD class='hsc2_l' colspan=2>Pitcher Settings (games started ratios (g/gs))</TD></TR>\n";

  echo "     <TR><TD>Minimum Games Started Ratio for Starters:</TD><TD align='left'><INPUT type=\"text\" name=\"minGS\" value=\"".$minGS."\"></TD></TR>\n";

  echo "     <TR><TD>Maximum Games Started Ratio for Relievers:</TD><TD align='left'><INPUT type=\"text\" name=\"maxGSpct\" value=\"".$maxGSpct."\"></TD></TR>\n";

  echo "     <TR class='headline'><TD class='hsc2_l' colspan=2>Additional Pitcher Settings</TD></TR>\n";

  echo "     <TR><TD>Include All Pitchers With At Least X Saves Per Team Game:</TD><TD align='left'><INPUT type=\"text\" name=\"minSV\" value=\"".$minSV."\"></TD></TR>\n";

  

  echo "     <TR><TD colspan=5><INPUT type=\"submit\" value=\"Save\"></TD></TR>\n";

  echo "   </FORM>\n";

  echo "     <TR><TD></TD><TD colspan=4>\n";

  echo "      <form method='get' action='./asSubmit.php'>\n";

  echo "       <input type='hidden' name='clear_votes' value=1 />\n";

  echo "       <input type='hidden' name='lgid' value='$lgid' />\n";

  echo "       <input type='hidden' name='year' value=$lgyear />\n";

  echo "       <INPUT type='submit' value=\"Clear This Year's Votes\">\n";

  echo "      </form>\n";

  echo "     </TD></TR>\n";

  echo "     <TR><TD></TD><TD colspan=4>\n";

  echo "      <form method='get' action='./asSubmit.php'>\n";

  echo "       <input type='hidden' name='clear_votes' value=1 />\n";

  echo "       <input type='hidden' name='lgid' value='$lgid' />\n";

  echo "       <INPUT type='submit' value=\"Clear All Votes\">\n";

  echo "      </form>\n";

  echo "     </TD></TR>\n";

  echo "    </table>";

  echo "  </div>\n";



  ## Display Users

  include($_SESSION['adminpath']."/dbopen.php");

  ## Get Subleagues

  $query="SELECT sub_league_id,name,designated_hitter as dh FROM sub_leagues WHERE league_id=$lgid ORDER BY sub_league_id;";

  $result=mysqli_query($db,$query);

  $prevSL=0;

  $SLcnt=0;

  while ($row=mysqli_fetch_array($result))

  {

	  $sub_league_id=$row['sub_league_id'];

	  $subleagues[$sub_league_id]['name']=$row['name'];

	  $subleagues[$sub_league_id]['origDH']=$row['dh'];

	  switch ($DHconfig)

	  {

	  case 1: $subleagues[$sub_league_id]['dh']=1; break;

	  case 2: $subleagues[$sub_league_id]['dh']=0; break;

	  default: $subleagues[$sub_league_id]['dh']=$row['dh']; break;

	  }

	  $SLcnt++;

  }



  ## Get leagues

  $query="SELECT l.league_id,name FROM leagues as l,human_managers as hm WHERE l.league_id=hm.league_id";

  $result=mysqli_query($db,$query);

  if (mysqli_num_rows($result)>0)

  {

	  while ($row=mysqli_fetch_array($result))

	  {

		  $uLeagueID=$row['league_id'];

		  $leagues[$uLeagueID]['name']=$row['name'];

	  }

  }

  

  ## Display Summary of Users

  $query="SELECT human_manager_id,position,sub_league_id FROM awards_vote WHERE league_id=$lgid AND year=$lgyear AND award_id=9 GROUP BY human_manager_id,position,sub_league_id";

  $result=mysqli_query($db,$query);

  if (mysqli_num_rows($result)>0)

  {

	  while ($row=mysqli_fetch_array($result))

      	  {

		  $hmid=$row['human_manager_id'];

  		  $pos=$row['position'];

		  $slid=$row['sub_league_id'];

	    	  $votes[$hmid][$pos][$slid]=1;

		  if (!isset($votes[$hmid]['total'])) {$votes[$hmid]['total']=1;} else {$votes[$hmid]['total']++;}

      	  }

  }

  $expVotes=$SLcnt*count($posArray);

  if ($DHconfig==0)

  {

	  foreach ($subleagues as $slid => $val)

	  {

		  if ($subleagues[$slid]['dh']==0) {$expVotes--;}

	  }

  }

  

  $query="SELECT hm.human_manager_id,t.name,t.nickname,first_name,last_name,hm.league_id FROM human_managers AS hm,teams AS t WHERE hm.team_id=t.team_id UNION SELECT human_manager_id,IF(is_commish=1,'Commissioner','No team') as name,'' as nickname,first_name,last_name,9999-is_commish as league_id FROM human_managers WHERE team_id=0 ORDER BY league_id,last_name,first_name;";

  $result=mysqli_query($db,$query);

  $cnt=0;

  if (mysqli_num_rows($result))

  {

	  while ($row=mysqli_fetch_array($result))

	  {

	    	  if (($showAllUsers!=1)&&($row['name']=='No team')) {continue;}

		  $hmid=$row['human_manager_id'];

		  $managers[$hmid]['name']=$row['first_name']." ".$row['last_name']." (".$row['name']." ".$row['nickname'].")";

		  $managers[$hmid]['lgid']=$row['league_id'];

	  }

  }

  

  echo " </tr>";



  ## Display User Detail

  echo " <tr><td>\n";

  echo "  <div class='textbox'>\n";

  echo "    <table cellpadding=2 cellspacing=0 border=0 width='935px'>\n";

  echo "     <tr class='title'><td colspan=".(2+$SLcnt*count($posArray)).">Voting Detail</td></tr>\n";

  echo "     <tr class='headline'><td class='hsc2_l' colspan=2>&nbsp;</td>";

  foreach ($subleagues as $slid => $val)

  {

	  echo "<td class='hsc2' colspan='";

	  if ($DHconfig==0)

	  {

		  echo (count($posArray)+($subleagues[$slid]['dh']-1));

	  }

	  else {echo count($posArray);}

	  echo "' style='text-align:center;border-left:1px dotted #999999;'>".$subleagues[$slid]['name']."</td>";

  }

  if ($settings[$lgid]['Awards'][-1]['gmEnable']==1) {echo "<td class='hsc2' style='text-align:center;border-left:1px dotted #999999;'>All</td>";}

  echo "</tr>\n";

  echo "     <tr class='headline'><td class='hsc2_l'>User</td><td class='hsc2_l'>Status</td>";

  foreach ($subleagues as $slid => $val)

  {

	  foreach ($posArray as $key => $pos)

	  {

		  if (($pos==10)&&($subleagues[$slid]['dh']==0)) {continue;}

		  echo "<td class='hsc2' style='text-align:center;";

		  if ($pos==2) {echo "border-left:1px dotted #999999;";}

		  echo "' title='".get_pos($pos)."'>".get_pos($pos,1)."</td>";

	  }

  }

  if ($settings[$lgid]['Awards'][-1]['gmEnable']==1) {echo "<td class='hsc2' style='text-align:center;border-left:1px dotted #999999;' title='General Manager of the Year'>GM</td>";}

  echo "</tr>\n";

  $mCnt=0;

  $oldHMLeagueID=-1;

  foreach ($managers as $hmid => $val)

  {

	  $hmLeagueID=$managers[$hmid]['lgid'];



	  if ($hmLeagueID!=$oldHMLeagueID)

	  {

		  $mCnt=0;

		  echo "     <tr class='headline'><td class='hsc2_l' colspan=".(2+$SLcnt*count($posArray)).">";

		  if ($hmLeagueID==9998) {echo "Unaffiliated Commissioners";}

		  elseif ($hmLeagueID==9999) {echo "Unaffiliated Users";}

		  else {echo $leagues[$hmLeagueID]['name'];}

		  echo "</td></tr>\n";

	  }



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

	  echo "     <tr class='$cls'>";

	  $voted="Not voted";

	  if ($votes[$hmid]['total']==$expVotes) {$voted="Yes";}

	  elseif ($votes[$hmid]['total']>0) {$voted="Partial";}

	  if ($voted!="Yes") {echo "<td class='".$cls."_l'><font color='red'>".$managers[$hmid]['name']."</font></td>";}

	  else {echo "<td class='".$cls."_l'>".$managers[$hmid]['name']."</td>";}

  	  if ($voted=="Not voted")

	  {

		  echo "<td class='".$cls."_l'><font weight='bold' color='red'>$voted</font></td>";

	  }

	  else

	  {

		  echo "<td class='".$cls."_l'><a href='./allstar.php?page=results&human_manager_id=$hmid'>$voted</a> (<a title='Clear entire ballot' href='./asSubmit.php?lgid=$lgid&year=$lgyear&clear_votes=1&human_manager_id=$hmid'>X</a>)</td>";

	  }

	  foreach ($subleagues as $slid => $val)

	  {

		  foreach ($posArray as $key => $pos)

		  {

			  if (($pos==10)&&($subleagues[$slid]['dh']==0)) {continue;}

			  echo "<td style='text-align:center;";

			  if ($pos==2) {echo "border-left:1px dotted #999999;";}

			  echo "'>";

			  if ($votes[$hmid][$pos][$slid]==1) {echo "<a title='Clear vote for ".get_pos($pos)."' href='./asSubmit.php?lgid=$lgid&year=$lgyear&clear_votes=1&human_manager_id=$hmid&pos=$pos'>X</a>";}

			  else {echo "<font weight='bold' color='red'>No</font>";}

			  echo "</td>";

		  }

	  }

	  echo "</tr>\n";

	  $mCnt++;

	  $oldHMLeagueID=$hmLeagueID;

  }

  echo "    </table>\n";

  echo "   </div>\n";

  echo " </td></tr>\n";



  echo "</table>\n";



  mysqli_close($db);



  ################## END OF PAGE #########################

  echo " </div>   <!-- END contentpane DIV -->\n";

  page_foot($_SESSION['lgpath']);





?>

