<?php

  include("html_functions.php");



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

  //$cmshOvr=1;         //Turn on to override the draft date restriction that prevents drafting after the league's draft date

  $lgid=$_SESSION['lgid'];

  $lgdate=$_SESSION['lgdate'];

  $lgpath=$_SESSION['lgpath'];

  

  $refresh=60;

  if (isset($_POST['refresh'])) {$refresh=$_POST['refresh'];$_SESSION['draft_refresh']=$refresh;}

  if (isset($_SESSION['draft_refresh'])) {$refresh=$_SESSION['draft_refresh'];}

  if ($refresh<5) {$refresh=60;}



  ##### Pre-Page Load Processing #####

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



  ## Check for teams on auto

  $query="SELECT SQL_NO_CACHE team_id,human_manager_id,identifier,setting,value FROM human_managers as hm LEFT JOIN (SELECT * FROM ootp_sql_admin WHERE scope=$lgid AND setting IN ('auto','autoRnd','auto_list')) as osa ON hm.human_manager_id=osa.identifier ORDER BY team_id,setting";

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

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

  if (mysqli_num_rows($result))

  {

	  while ($row=mysqli_fetch_array($result))

	  {

		  $tid=$row['team_id'];

		  $setting=$row['setting'];

		  $teams[$tid][$setting]=$row['value'];

		  $teams[$tid]['hmid']=$row['human_manager_id'];

	  }

  }



  ## Get Draft Date

  $query="SELECT draft_date,DATEDIFF(draft_date,'$lgdate') as diff FROM leagues WHERE league_id=$lgid;";

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

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

  $row=mysqli_fetch_array($result);

  $ddate=$row['draft_date'];

  $ddateDiff=$row['diff'];

  if (($ddateDiff<0)&&($cmshOvr!=1))

  {

	  $refresh="";

  }

  else

  {

	  ## Check if draft enabled and auto picks are on

	  $query="SELECT setting,value FROM ootp_sql_admin WHERE module='Draft' AND scope=$lgid AND setting IN ('draftOn','pauseAuto','autoDelay','timerEnable','autoOpen')";

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

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

	  if (mysqli_num_rows($result))

	  {

		  while ($row=mysqli_fetch_array($result))

		  {

			  $setting=$row['setting'];

			  $val=$row['value'];



			  switch ($setting)

			  {

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

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

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

			  case 'timerEnable': $timerOn=$val;   break;

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

			  }

		  }

	  }

	  if ($draftOn==0) {$timerOn=0;}

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



	  if ($_GET['showq']==1) {echo "Processing Check: draftOn=$draftOn, pauseAuto=$pauseAuto, timerOn=$timerOn<br/>\n";}

	

	  if (($draftOn==1)&&($pauseAuto!=1)&&($timerOn==1))  // Process overdue picks automatically

	  {

		  ## Get current pick info

		  $now=time();

		  $chkTime=strftime("%Y-%m-%d %H:%M:%S",$now);

		  $query="SELECT SQL_NO_CACHE t1.*,lastPick,TIMESTAMPDIFF(SECOND,lastPick,'$chkTime') as lastDiff FROM (SELECT round,supplemental,pick_round,team_id,pick_time,TIMESTAMPDIFF(SECOND,pick_time,'$chkTime') as nowDiff FROM amateur_draft WHERE league_id=$lgid AND player_id IS NULL ORDER BY round, supplemental, pick_round LIMIT 1) as t1,(SELECT MAX(pick_time) as lastPick FROM amateur_draft WHERE league_id=$lgid AND player_id IS NOT NULL) as t2";

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

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

		  if (mysqli_num_rows($result))

		  {

			  $row=mysqli_fetch_array($result);

			  $rnd=$row['round'];

			  $supp=$row['supplemental'];

			  $pick=$row['pick_round'];

			  $tid=$row['team_id'];



			  $makeAutoPick=0;

			  $makeListPick=0;

			  // Pick overdue

			  if ($row['nowDiff']>0) {$makeAutoPick=1;}

			  //Open team

			  elseif (!isset($teams[$tid]['hmid']))

			  {

				  if (($autoOpen==1)&&($row['lastDiff']>$autoDelay)) {$makeAutoPick=1;}

			  }

			  // Check team's auto status

			  elseif (($teams[$tid]['auto']==1)&&($row['lastDiff']>$autoDelay))

			  {

				  $autoRnd=$teams[$tid]['autoRnd'];

				  if (is_numeric($autoRnd))

				  {

					  if (($rnd>$autoRnd)||(($supp==1)&&($rnd==$autoRnd))) {$makeAutoPick=1;}

					  elseif ($teams[$tid]['auto_list']==1)

					  {

						  $makeListPick=1;

					  }

				  }

				  else

				  {

					  $autoRnd=substr($autoRnd,1,99);

					  if ($rnd>$autoRnd) {$makeAutoPick=1;}

					  elseif ($teams[$tid]['auto_list']==1) {$makeListPick=1;}

				  }

			  }

			  elseif (($teams[$tid]['auto_list']==1)&&($row['lastDiff']>$autoDelay)) {$makeListPick=1;}



			  // Check for undrafted players on list

			  if ($makeListPick==1)

			  {

				  $hmid=$teams[$tid]['hmid'];

				  $query="SELECT dp1.player_id,porder FROM (SELECT dp.player_id,dp.league_id,porder FROM ootp_sql_draft_pool as dp,ootp_sql_draft_list as dl WHERE dp.league_id=$lgid AND dp.player_id=dl.player_id AND human_manager_id=$hmid) as dp1 LEFT JOIN amateur_draft as ad ON dp1.player_id=ad.player_id WHERE dp1.league_id=$lgid AND ad.player_id IS NULL ORDER BY porder LIMIT 1";

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

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

				  if (mysqli_num_rows($result))

				  {

					  $row=mysqli_fetch_array($result);

					  $player_id=$row['player_id'];



					  header("Location: ./draftProcess.php?mode=auto_list_pick&team_id=$tid&rnd=$rnd&supp=$supp&pick=$pick&player_id=$player_id".($_GET['debug']==1?"&showq=1":""));

					  exit;

				  }

			  }

			  // Make Auto Pick

			  elseif ($makeAutoPick==1)

			  {

				  header("Location: ./draftProcess.php?team_id=$tid&rnd=$rnd&supp=$supp&pick=$pick".($_GET['debug']==1?"&showq=1":""));

				  exit;

			  }

		  }

	  }

  }





  mysqli_close($db);

	

  # Title Bar

  $title='Draft Board';



  page_head($title,$_SESSION['lgpath'],$refresh,"","./draft.js|./jquery/jquery.min.js");

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

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

  nav_toolbar("draft","Draft");

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



  echo " <script type='text/javascript'>\n";

  echo "  var rows,x;\n";

  echo " </script>\n";



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



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

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



  ## Get Draft Order

  $query="SELECT name,nickname,logo_file_name,x.* FROM teams as t,(SELECT round,supplemental,pick_round,team_id,player_id,pick_time FROM `amateur_draft` WHERE league_id=$lgid) as x WHERE t.team_id=x.team_id ORDER BY round,supplemental,pick_round";

  if ($_GET['showq']==1) {echo $query;}

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

  if (mysqli_num_rows($result)>0)

  {

	  ##### Display Refresh Option

	  if ($refresh>0)

	  {

		  $curPick=$curPick-5;

		  echo "<div style='float:right;border:0;'>\n";

		  echo "  <form action='./draftBoard.php";

		  if ($curPick>=20) {echo "#$curPick";}

		  echo "' method='post'>\n";

		  echo "   <table><tr><td>Refresh every</td><td><input type='textbox' name='refresh' size=3 maxlength=4 value='$refresh' /></td><td>seconds</td><td><input type='submit' value='Go' /></td></tr></table>\n";

		  echo "  </form>\n";

		  echo " </div>\n";

	  }



	  ##### Display Draft

	  $povr=0;

	  while ($row=mysqli_fetch_array($result))

	  {

		  $povr++;



		  $tid=$row['team_id'];

		  $picks[$povr]['rnd']=$row['round'];

		  $picks[$povr]['supplemental']=$row['supplemental'];

		  $picks[$povr]['pick']=$row['pick_round'];

		  $picks[$povr]['pick_time']=$row['pick_time'];



		  $picks[$povr]['tid']=$tid;

		  $picks[$povr]['pid']=$row['player_id'];



		  $teams[$tid]['name']=$row['name']." ".$row['nickname'];

		  $teams[$tid]['logo_file']=$row['logo_file_name'];

	  }

	

	  ## Get Drafted Players

	  $query="SELECT p.player_id,first_name,last_name,if(position=1,role,position) as position FROM players as p,amateur_draft as ad WHERE p.player_id=ad.player_id AND ad.league_id=$lgid;";

	  if ($_GET['showq']==1) {echo $query;}

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

	  if (mysqli_num_rows($result)>0)

	  {

		  while ($row=mysqli_fetch_array($result))

		  {

			  $pid=$row['player_id'];



			  $players[$pid]['name']=$row['first_name']." ".$row['last_name'];

			  $players[$pid]['pos']=$row['position'];

		  }

	  }



	  ## Display Draft

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

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



	  $nCols=7+$timerOn+$_SESSION['user_is_commish'];



	  echo "   <tr class='title2'><td colspan=$nCols";

	  if ($timerOn==1) {echo ">Draft Results<br/>Current server time is ".date("Y-m-d H:i T",time());}

	  else {echo " class='largeText'>Draft Results";}

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



	  $prvRnd=-1;

	  $rowCnt=0;

	  $povr=0;

	  foreach ($picks as $povr => $val)

	  {

		  $rnd  =$picks[$povr]['rnd'];

		  $supp =$picks[$povr]['supplemental'];

		  $pick =$picks[$povr]['pick'];

		  $ptime=$picks[$povr]['pick_time'];



		  $tid  =$picks[$povr]['tid'];

		  $pid  =$picks[$povr]['pid'];



		  if ($supp==1) {$rndLbl='S'.$rnd;} else {$rndLbl=$rnd;}



		  if ($rndLbl!=$prvRnd)

		  {

			  $rowCnt=0;

			  echo "  <tr class='title'>";

			  echo "<td colspan=".($nCols-1).">";

			  if ($supp==1) {echo "Supplemental to ";}

			  echo "Round $rnd";

			  echo "</td>";

			  echo "<td style='text-align:right;'><a onclick=\"rows=$('[name=rnd".$rnd."_".$supp."]');for(x=0;x<rows.length;x++){rows[x].style.display='inline';}\">Show</a>/<a onclick=\"rows=$('[name=rnd".$rnd."_".$supp."]');for(x=0;x<rows.length;x++){rows[x].style.display='none';}\">Hide</a></td>\n";

			  echo "</tr>\n";



			  echo "  <tr class='headline' name='rnd".$rnd."_".$supp."'>";

			  echo "<td class='hsc2'>Round</td>";

			  echo "<td class='hsc2'>Pick</td>";

			  echo "<td class='hsc2'>Overall</td>";

			  echo "<td class='hsc2_l' colspan=2>Team</td>";

			  echo "<td class='hsc2'>Pos</td>";

			  echo "<td class='hsc2_l'>Player</td>";

			  if ($timerOn==1) {echo "<td class='hsc2'>Due/Taken At</td>";}

			  if ($_SESSION['user_is_commish']==1) {echo "<td class='hsc2'>Commish Actions</td>";}

			  echo "</tr>\n";

		  }



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

		  echo "  <tr class='$cls' name='rnd".$rnd."_".$supp."'>";

		  echo "<td name='$povr'>$rndLbl</td>";

		  echo "<td>$pick</td>";

		  echo "<td>$povr</td>";

		  echo "<td style='width:22px;'><img src=\"$lgpath/images/team_logos/".str_replace(".png","_25.png",$teams[$tid]['logo_file'])."\"></td>";

		  echo "<td class='".$cls."_l'><a href='".$_SESSION['lgpath']."/teams/team_$tid.html'>".$teams[$tid]['name']."</a>";

		  if (!($pid>0))

		  {

			  if (!isset($teams[$tid]['hmid']))

			  {

				  echo " <span style='color:#990000;'><sup>Open";

				  if ($autoOpen==1) 

				  {

					  echo " - Auto";

					  if (!isset($pickStatus)) {$pickStatus="auto";}

				  }

				  else

				  {

					  echo " - No auto";

					  if (!isset($pickStatus)) {$pickStatus="none";}

				  }

				  echo "</sup></span>";

			  }

			  elseif ($teams[$tid]['auto']==1)

			  {

				  $autoRnd=$teams[$tid]['autoRnd'];

				  if (is_numeric($autoRnd))

				  {

					  if (($rnd>$autoRnd)||(($supp==1)&&($rnd==$autoRnd)))

					  {

						  echo " <span style='color:#990000;'><sup>Auto</sup></span>";

						  if (!isset($pickStatus)) {$pickStatus="auto";}

					  }

					  elseif ($teams[$tid]['auto_list']==1)

					  {

						  echo " <span style='color:#009900;' title=\"Pick will be made automatically only if undrafted players are on the team's draft list\"><sup>List Pick</sup></span>";

						  if (!isset($pickStatus)) {$pickStatus="list";}

					  }

				  }

				  else

				  {

					  $autoRnd=substr($autoRnd,1,99);

					  if ($rnd>$autoRnd)

					  {

						  echo " <span style='color:#990000;'><sup>Auto</sup></span>";

						  if (!isset($pickStatus)) {$pickStatus="auto";}

					  }

					  elseif ($teams[$tid]['auto_list']==1)

					  {

						  echo " <span style='color:#009900;' title=\"Pick will be made automatically only if undrafted players are on the team's draft list\"><sup>List Pick</sup></span>";

						  if (!isset($pickStatus)) {$pickStatus="list";}

					  }

				  }

			  }

			  elseif ($teams[$tid]['auto_list']==1)

			  {

				  echo " <span style='color:#009900;' title=\"Pick will be made automatically only if undrafted players are on the team's draft list\"><sup>List Pick</sup></span>";

				  if (!isset($pickStatus)) {$pickStatus="list";}

			  }

			  elseif (!isset($pickStatus)) {$pickStatus="none";}

		  }

		  else

		  {

			  if (!isset($teams[$tid]['hmid'])) {echo " <span style='color:#990000;'><sup>Open</sup></span>";}

		  }

		  echo "</td>";

		  if ($pid>0)

		  {

			  echo "<td>".get_pos($players[$pid]['pos'],1)."</td>";

			  echo "<td class='".$cls."_l'><a href='".$_SESSION['lgpath']."/players/player_$pid.html'>".$players[$pid]['name']."</a></td>";

			  if ($timerOn==1) {echo "<td>$ptime</td>";}

			  if ($_SESSION['user_is_commish']==1) {echo "<td class='hsc2'><a href='./draftProcess.php?mode=clear&rnd=$rnd&supp=$supp&pick=$pick'>Clear</a> / <a href='./draftManual.php?rnd=$rnd&supp=$supp&pick=$pick'>Edit</a> / <a href='./draftProcess.php?mode=rollback&rnd=$rnd&supp=$supp&pick=$pick'>Rollback</a></td>";}

		  }

		  elseif ($pid<0)

		  {

			  echo "<td>&nbsp;</td>";

			  echo "<td class='".$cls."_l'>";

			  switch ($pid)

			  {

			  case -998: echo " - Passed - "; break;

			  case -999: echo " - Skipped - "; break;

			  }

			  echo "</td>";

			  if ($timerOn==1) {echo "<td>$ptime</td>";}

			  if ($_SESSION['user_is_commish']==1) {echo "<td class='hsc2'><a href='./draftProcess.php?mode=clear&rnd=$rnd&supp=$supp&pick=$pick'>Clear</a> / <a href='./draftManual.php?rnd=$rnd&supp=$supp&pick=$pick'>Edit</a> / <a href='./draftProcess.php?mode=rollback&rnd=$rnd&supp=$supp&pick=$pick'>Rollback</a></td>";}

		  }

		  else

		  {

			  echo "<td>&nbsp;</td>";

			  echo "<td class='".$cls."_l' style='font-style:italic;'>";

			  if (($draftOn==1)&&($tid==$_SESSION['user_team_id'])&&(!isset($curPick))) 

			  {

				  echo "<span style='color:red;font-weight:bold;'>YOU ARE ON THE CLOCK</span>";

				  $onTheClock=1;

			  }

			  echo "</td>";



			  if ($timerOn==1)

			  {

				  echo "<td>$ptime</td>";

				  if (!isset($cdTime)) {$cdTime=strtotime($ptime);}

			  }



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

			  {

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

				  echo "<a href='./draftProcess.php?mode=manualauto&team_id=$tid&rnd=$rnd&supp=$supp&pick=$pick";

				  if ($_GET['showq']==1) {echo "&showq=1";}

				  echo "'>Auto Pick</a> / <a href='./draftManual.php?rnd=$rnd&supp=$supp&pick=$pick'>Manual Pick</a>";

				  echo " / <a href='./draftProcess.php?mode=skip&team_id=$tid&rnd=$rnd&supp=$supp&pick=$pick&player_id=-999";

				  if ($_GET['showq']==1) {echo "&showq=1";}

				  echo "'>Skip Pick</a>";

				  echo "</td>";

			  }



			  if (!isset($curPick)) {$curPick=$povr-1;}

		  }

		  echo "</tr>\n";



		  $rowCnt++;

		  $prvRnd=$rndLbl;

	  }



	  echo " </table>\n";

	  echo "</div>\n";



  	  ##### Show sidebar

	  if ($timerOn==1)

  	  {

		  echo "<div style='border-top: 1px solid #000000; border-bottom: 1px solid #000000; border-left: 1px solid #000000; background:#FFFFFF; position:fixed; z-index:100; right:0px; top:10px; padding:3px;'>\n";

  		  if ($onTheClock==1) {echo " <span style='color:red;font-weight:bold;'>YOU ARE ON THE CLOCK</span><br/>\n";}

		  echo " <div id='countboxSidebar'></div>\n";

		  echo "</div>\n";

  	  }



	  if (isset($cdTime))

	  {

		  $query="SELECT MAX(pick_time) as lastPick FROM amateur_draft WHERE league_id=$lgid AND player_id IS NOT NULL";

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

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

		  if (mysqli_num_rows($result))

		  {

			  $row=mysqli_fetch_array($result);

			  $lastTime=strtotime($row['lastPick']);

		  }

		  else {$lastTime=0;}

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



		  $now=time();

		  echo "<script type='text/javascript'>\n";

		  if (!isset($pickStatus)) {$pickStatus='none';}

		  echo "  countDown($cdTime,$now,$lastTime,'countboxSidebar',$autoDelay,'$pickStatus',$pauseAuto);\n";

		  echo "</script>\n";

	  }



  }

  else

  {

	  echo "<div class='textbox' style='border:0px;'>Draft not scheduled</div>\n";

  }



  mysqli_close($db);



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

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

  page_foot($_SESSION['lgpath']);





?>

