<?php

  include("html_functions.php");



  // Initialize Variables

  $lgid=$_SESSION['lgid'];

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

  $lgyear=$date->format("Y");



  $fromPg=$_GET['from'];

  $create=$_GET['create'];

  $schedule=$_GET['schedule'];

  $debug=max($_GET['debug'],$_GET['showq']);



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



  // Get Draft Settings

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

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

  if (mysqli_num_rows($result)) 

  {

	  # Get Settings

	  $query="SELECT * FROM ootp_sql_admin WHERE scope=$lgid AND module='Draft' AND setting NOT IN ('feeder','emailList','replyList')";

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

	  if (mysqli_num_rows($result))

	  {

		  while ($row=mysqli_fetch_array($result))

		  {

			  $scope=$row['scope'];

			  $module=$row['module'];

			  $setting=$row['setting'];

			  $identifier=$row['identifier'];

			  $value=$row['value'];



			  $settings[$setting]=$value;

		  }

	  }

  }



  if ($debug==1) {echo "Settings<br/>\n";print_r($settings);echo "<br/>\n";}



  // Recreate the draft order

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

  {

	  if ($debug==1) {echo "Creating draft order...<br/>\n";}



	  $updText="";



	  $nRounds=$settings['nRounds'];

	  $suppRounds=$settings['suppRounds'];

	  $rndLength=$settings['rndLength'];

	  $draftOrder=$settings['draftOrder'];

	  $draftPattern=$settings['draftPattern'];



	  # Check for past history

	  $query="SELECT team_id FROM team_history_record WHERE league_id=$lgid LIMIT 1";

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

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

	  if (mysqli_num_rows($thResult))

	  {

		  # Get Teams In Draft Order

		  if ($draftOrder==0)

		  {

			  $query="SELECT t.team_id,t.sub_league_id,pct FROM teams as t LEFT JOIN team_history_record as thr ON t.team_id=thr.team_id WHERE t.league_id=$lgid AND allstar_team=0 AND year=".($lgyear-1)." ORDER BY pct";

		  }

		  else

		  {

			  $query="SELECT team_id,pct,CASE WHEN @sub_league_id!=sub_league_id THEN @rownum:=0 ELSE @rownum:=@rownum+1 END AS rank,@sub_league_id:=sub_league_id FROM (SELECT @rownum:=0,t.team_id,@sub_league_id:=t.sub_league_id as sub_league_id,pct FROM teams as t LEFT JOIN team_history_record as thr ON t.team_id=thr.team_id WHERE t.league_id=$lgid AND allstar_team=0 AND year=".($lgyear-1)." ORDER BY t.sub_league_id,pct) as x ORDER BY rank,sub_league_id";

			  if ($draftOrder==2) {$query.=" DESC";}

		  }

	  }

	  else

	  {

		  # Get Teams In Draft Order

		  if ($draftOrder==0)

		  {

			  $query="SELECT team_id,sub_league_id FROM teams WHERE league_id=$lgid AND allstar_team=0 ORDER BY name,nickname";

		  }

		  else

		  {

			  $query="SELECT team_id,CASE WHEN @sub_league_id!=sub_league_id THEN @rownum:=0 ELSE @rownum:=@rownum+1 END AS rank,@sub_league_id:=sub_league_id FROM (SELECT @rownum:=0,team_id,@sub_league_id:=sub_league_id as sub_league_id FROM teams WHERE league_id=$lgid AND allstar_team=0 ORDER BY sub_league_id,name,nickname) as x ORDER BY rank,sub_league_id";

			  if ($draftOrder==2) {$query.=" DESC";}

		  }

	  }

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

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

	  $nTeams=0;

	  while ($row=mysqli_fetch_array($result))

	  {

		  $tid=$row['team_id'];

		  $slid=$row['sub_league_id'];

		  $teams[$nTeams]=$tid;

		  $nTeams++;

	  }



	  # Get Round Length

	  if ($rndLength!="")

  	  {

		  $e=explode(";",$rndLength);

  		  foreach ($e as $key => $val)

		  {

  			  $f=explode(",",$val);

			  $rnd=$f[0];

  			  if (!isset($f[1])) {$f[1]=0;}

			  $rndLen[$rnd]=$f[1];

		  }

		  if ($debug==1) {echo "Round Lengths<br/>\n";print_r($rndLen);echo "<br/>\n";}

	  }



	  # Get Supplemental Rounds

	  if ($suppRounds!="")

	  {

		  $e=explode(";",$suppRounds);

		  foreach ($e as $key => $val)

		  {

			  $suppRnd[$val]=$val;

		  }

		  if ($debug==1) {echo "Supplemental Rounds<br/>\n";print_r($suppRnd);echo "<br/>\n";}

	  }



	  # Clear Draft

	  $updText.="DELETE FROM amateur_draft WHERE league_id=$lgid;\n";



	  # Create Standard Rounds

	  $pickOvr=0;

	  for ($rnd=1;$rnd<=$nRounds;$rnd++)

	  {

		  $pick=0;

		  if (($draftPattern=='Linear')||(($draftPattern=='Serpentine')&&(($rnd%2)==1)))

		  {

			  ksort($teams);

		  }

		  else

		  {

			  krsort($teams);

		  }



		  if (!isset($rndLen[$rnd])) {$rndLen[$rnd]=$nTeams;}



		  while ($pick<$rndLen[$rnd])

		  {

			  foreach ($teams as $key => $tid)

			  {

				  $pick++;

	

				  if ($pick>$rndLen[$rnd]) {continue;}  //Stop at defined end of round



				  $updText.="INSERT INTO amateur_draft (league_id, round, supplemental, pick_round, team_id)";

				  $updText.=" VALUES ($lgid, $rnd, 0, $pick, $tid)\n";

			  }

		  }



		  // Process Supplemental Round

		  if (isset($suppRnd[$rnd]))

		  {

			  $pick=0;

			  $rndLbl='S'.$rnd;

	

			  if (!isset($rndLen[$rndLbl])) {$rndLen[$rndLbl]=$nTeams;}



			  while ($pick<$rndLen[$rndLbl])

			  {

				  foreach ($teams as $key => $tid)

				  {

					  $pick++;

	

					  if ($pick>$rndLen[$rndLbl]) {continue;}  //Stop at defined end of round

	

	

					  $updText.="INSERT INTO amateur_draft (league_id, round, supplemental, pick_round, team_id)";

					  $updText.=" VALUES ($lgid, $rnd, 1, $pick, $tid)\n";

				  }

			  }

		  } // End supplemental rounds loop



	  } // End rounds loop



	  // Process SQL statements

	  if ($updText!="")

	  {

		  $e=explode("\n",$updText);

		  foreach ($e as $key => $query)

		  {

			  if ($query=="") {continue;}

			  else

			  {

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

				  mysqli_query($db,$query);

			  }

		  }

	  }



  } // Endif create draft 









  // Reschedule the draft picks

  if ($schedule==1)

  {

	  if ($debug==1) {echo "Scheduling draft picks...<br/>\n";}

	  $updText="";



	  // Get Draft Picks

	  $query="SELECT round,supplemental,pick_round FROM amateur_draft WHERE league_id=$lgid AND player_id IS NULL ORDER BY round,supplemental,pick_round";

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

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

	  if (mysqli_num_rows($result))

	  {

		  // Get Draft Start Time

		  $dStartDt=$settings['dStartDt'];

		  $dStartTm=$settings['dStartTm'];

		  $timePick1=$settings['timePick1'];

		  $timePick2=$settings['timePick2'];

		  $rndSwitch=$settings['rndSwitch'];

		  $timeStart=$settings['timeStart'];

		  $timeStop=$settings['timeStop'];

		  $pauseWkEnd=$settings['pauseWkEnd'];



		  if (($timeStart=="")||($timeStart<0)) {$timeStart=0;}
		  if (($timePick1=="")||($timePick1<0)) {$timePick1=0;}
		  if (($timePick2=="")||($timePick2<0)) {$timePick2=0;}



		  $now=time();

		  $dStartInst=strtotime($dStartDt." ".$dStartTm);

		  if ($dStartInst<$now) {$dStartInst=$now;}



		  // Reschedule unselected players

		  $pickCnt=1;

		  while ($row=mysqli_fetch_array($result))

		  {

			  $rnd=$row['round'];

			  $supp=$row['supplemental'];

			  $pick=$row['pick_round'];



			  if ($rnd<=$rndSwitch) {$pickInterval=$timePick1;} else {$pickInterval=$timePick2;}



			  if ($pickCnt==1) //First pick

			  {

				  $pickInst=$dStartInst+(60*$pickInterval);

			  }

			  else //Next pick

			  {

				  // Determine unadjusted next pick time

				  $nextInst=$pickInst+(60*$pickInterval);



				  // Determine stop time on date of pick

				  $curDate=strftime("%Y-%m-%d",$pickInst);

				  if ($timeStop==2400)

				  {

					  $lastInst=strtotime($curDate." ".($timeStop-41))+60;

				  }

				  elseif ($timeStop!="")

				  {

					  $lastInst=strtotime($curDate." ".$timeStop);

				  }



				  // Adjust if after stop time

				  if ($nextInst>$lastInst)

				  {

					  ## Determine next day's start time

					  // Get next day

					  $nextDate=strtotime($curDate." + 1 day");

					  $dow=date("w",$nextDate);



					  // Adjust for weekend if needed

					  if (($pauseWkEnd==1)&&($dow==6))

					  {

						  $nextDate=strtotime($curDate." + 3 days");

					  }



					  // Get time expired before last instance

					  $expTime=$lastInst-$pickInst;

					  $remTime=(60*$pickInterval)-$expTime;



					  $nextInst=strtotime(strftime("%Y-%m-%d",$nextDate)." $timeStart + $remTime seconds");



		    			  if (($_GET['showq']==1)||($debug==1)) {echo " - $rnd::$supp::$pick::$nextDate::$dow::$expTime::$remTime::$nextInst<br/>\n";}

				  }



				  // Determine start time on date of pick

				  $curDate=strftime("%Y-%m-%d",$nextInst);

				  $firstInst=strtotime($curDate." ".$timeStart);



				  if (($_GET['showq']==1)||($debug==1)) {echo " -> $rnd::$supp::$pick :: Next:$nextInst::".strftime("%Y-%m-%d %H:%M:%S",$nextInst)." :: Last:$lastInst::".strftime("%Y-%m-%d %H:%M:%S",$lastInst)." :: First:$firstInst::".strftime("%Y-%m-%d %H:%M:%S",$firstInst)."<br/>\n";}



				  // Adjust if before start time

				  if ($nextInst<=$firstInst)

				  {

					  // Adjust for weekend if needed

					  $dow=date("w",strtotime($curDate));

					  if ($pauseWkEnd==1)

					  {

						  switch ($dow)

						  {

						  case 0:

							  $nextDate=strtotime($curDate." + 1 day");

							  $nextInst=strtotime(strftime("%Y-%m-%d",$nextDate)." ".$timeStart);

							  break;

						  case 6:

							  $nextDate=strtotime($curDate." + 2 days");

							  $nextInst=strtotime(strftime("%Y-%m-%d",$nextDate)." ".$timeStart);

							  break;

						  default:

							  $nextInst=$firstInst;

							  break;

						  }



					  }

					  else

					  {

						  $nextInst=$firstInst;

					  }



		    			  if (($_GET['showq']==1)||($debug==1)) {echo " + $rnd::$supp::$pick::$curDate::$dow::$nextInst<br/>\n";}

				  }



				  $pickInst=$nextInst;

			  }



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



  			  if (($_GET['showq']==1)||($debug==1)) {echo "$rnd::$supp::$pick::$pickInst::$pickDue<br/>\n";}



			  $updText.="UPDATE amateur_draft SET pick_time='$pickDue' WHERE league_id=$lgid AND round=$rnd AND supplemental=$supp AND pick_round=$pick;\n";



			  $pickCnt++;

		  }

	  }



	  // Process SQL statements

	  if ($updText!="")

	  {

		  $e=explode("\n",$updText);

		  foreach ($e as $key => $query)

		  {

			  if ($query=="") {continue;}

			  else

			  {

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

				  mysqli_query($db,$query);

			  }

		  }

	  }

  }



  mysqli_close($db);



  if ($debug==1) {exit;}



  if ($fromPg=="")

  {

	  header('Location: '.$_SERVER['HTTP_REFERER']);

  }

  else

  {

	  header('Location: '.$fromPg);

  }



?>

