<?php
  session_start();
include_once("./html_functions.php");
include_once("./slack_integration.php");
include_once("./discord_integration.php");

  ################## PAGE INITIALIZATION #########################
  $lgid=$_SESSION['lgid'];
  $user=$_SESSION['user_id'];
  $cmsh=$_SESSION['user_is_commish'];
  $lgpath=$_SESSION['lgpath'];

  $rnd=$_GET['rnd'];
  $supp=$_GET['supp'];
  $pick=$_GET['pick'];
  $player_id=(isset($_GET['player_id'])?$_GET['player_id']:"");
  $team_id=$_GET['team_id'];

  $mode=(isset($_GET['mode'])?$_GET['mode']:NULL);
  
  $debug=(isset($_GET['debug'])?$_GET['debug']:0);
  if (!isset($_GET['showq'])) {$_GET['showq']=0;}
  if ($_GET['showq']==1) {$debug=1;}
  
  $adminpath=$_SESSION['adminpath'];

  include($adminpath."/dbopen.php");
  
  ## Gather DB info
  // Get Slack Settings
  $query="SELECT setting,identifier,value FROM ootp_sql_admin WHERE scope IN ('ALL',$lgid) AND (setting IN ('StatsLabPath','serverurl','HTMLPath','Ratings','Talents','Others','scoutsOn','rawRatings') OR setting LIKE '%slack%' OR setting LIKE '%discord%');";
  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'];
		  $identifier=$row['identifier'];
		  $val=$row['value'];

          switch ($setting)
          {
              case 'StatsLabPath' : $_SESSION['StatsLabPath']=$val; break;
              case 'ServerURL': $_SESSION['serverurl']=$val;break;
              case 'HTMLPath' : $_SESSION['HTMLPath']=$val; break;
              case 'rawRatings': $settings['rawRatings']=$val; break;
              default:
                $settings[$setting][$identifier]=$val;
          }

          $StatsLabPath=$_SESSION['StatsLabPath'];

          if (strtolower(substr($_SESSION['StatsLabPath'],0,4))!="http") {$StatsLabPath=$_SESSION['serverurl'].$_SESSION['StatsLabPath'];}
          $HTMLPath=$_SESSION['serverurl'].$_SESSION['HTMLPath'];
          
          $settings[$setting][$identifier]=$val;
	  }
  }
  if (!isset($settings['rawRatings'])) {$settings['rawRatings']=0;}


  // Get league abbreviation
  $query="SELECT abbr FROM leagues WHERE league_id=$lgid";
  if ($_GET['showq']==1) {echo "$query<br/>\n";}
  $result=mysqli_query($db,$query);
  if (mysqli_num_rows($result))
  {
	  $row=mysqli_fetch_array($result);
	  $lgAbbr=$row['abbr'];
  }

  // Get teams
  $query="SELECT team_id,name,nickname,abbr,background_color_id,text_color_id,logo_file_name FROM teams WHERE league_id=$lgid AND allstar_team=0";
  if ($_GET['showq']==1) {echo "$query<br/>\n";}
  $result=mysqli_query($db,$query);
  $nTeams=0;
  if (mysqli_num_rows($result))
  {
	  while ($row=mysqli_fetch_array($result))
	  {
		  $tid=$row['team_id'];
		  $teams[$tid]['name']=$row['name']." ".$row['nickname'];
          $teams[$tid]['abbr']=$row['abbr'];
          $teams[$tid]['background_color_id']=$row['background_color_id'];
          $teams[$tid]['text_color_id']=$row['text_color_id'];
          $teams[$tid]['logo_file_name']=$row['logo_file_name'];

		  $nTeams++;
	  }
  }

  ##### Process Draft Functions #####
  switch ($mode)
  {
  case 'clear':
	  $query="UPDATE amateur_draft SET player_id=NULL WHERE league_id=$lgid AND round=$rnd AND supplemental=$supp AND pick_round=$pick";
	  if ($_GET['showq']==1) {echo "$query<br/>\n";}
	  $result=mysqli_query($db,$query);

	  //Send to Slack
	  if ($settings['slackEnable'][-1]==1)
	  {
		$msg=$lgAbbr." draft pick ".($supp==1?"S":"").$rnd.".".$pick." - Pick cleared";
		send_slack($adminpath,$lgid,'draft',$msg,$debug);
	  }
          
      //Send to Discord
      if ($settings['discordEnable'][-1]==1)
      {
          $msg=$lgAbbr." draft pick ".($supp==1?"S":"").$rnd.".".$pick." - Pick cleared";
          $dataArray = Array (
                              "content" => $msg
                              );
          send_discord($adminpath,$lgid,'Draft',$dataArray,$debug);
      }

	  //Take team off auto
	  $query="SELECT human_manager_id FROM amateur_draft as ad,human_managers as hm WHERE ad.team_id=hm.team_id AND ad.league_id=$lgid AND round=$rnd AND supplemental=$supp AND pick_round=$pick";
	  if ($_GET['showq']==1) {echo "$query<br/>\n";}
	  $result=mysqli_query($db,$query);
	  if (mysqli_num_rows($result))
	  {
		  $row=mysqli_fetch_array($result);
		  $hmid=$row['human_manager_id'];
	
		  $query="UPDATE ootp_sql_admin SET value=0 WHERE scope=$lgid AND module='users' AND identifier=$hmid AND setting='auto'";
		  if ($_GET['showq']==1) {echo "$query<br/>\n";}
		  $result=mysqli_query($db,$query);

		  $query="UPDATE ootp_sql_admin SET value=0 WHERE scope=$lgid AND module='users' AND identifier=$hmid AND setting='auto_list'";
		  if ($_GET['showq']==1) {echo "$query<br/>\n";}
		  $result=mysqli_query($db,$query);
	  }

	  header('Location: ./draftSchedule.php?from='.$_SERVER['HTTP_REFERER'].'&create=0&schedule=1');
	  exit;
	  break;
  case 'rollback':
	  $query="UPDATE amateur_draft SET player_id=NULL WHERE league_id=$lgid AND (round=$rnd AND supplemental=$supp AND pick_round>=$pick) OR (round=$rnd AND supplemental>$supp) OR (round>$rnd)";
	  if ($_GET['showq']==1) {echo "$query<br/>\n";}
	  $result=mysqli_query($db,$query);

	  //Send to Slack
	  if ($settings['slackEnable'][-1]==1)
	  {
		$msg=$lgAbbr." draft rolled back to pick ".($supp==1?"S":"").$rnd.".".$pick;
		send_slack($adminpath,$lgid,'draft',$msg,$debug);
	  }

      //Send to Discord
      if ($settings['discordEnable'][-1]==1)
      {
          $msg=$lgAbbr." draft rolled back to pick ".($supp==1?"S":"").$rnd.".".$pick;
          $dataArray = Array (
                              "content" => $msg
                              );
          send_discord($adminpath,$lgid,'Draft',$dataArray,$debug);
      }

          //Take team off auto
	  $query="SELECT human_manager_id FROM amateur_draft as ad,human_managers as hm WHERE ad.team_id=hm.team_id AND ad.league_id=$lgid AND round=$rnd AND supplemental=$supp AND pick_round=$pick";
	  if ($_GET['showq']==1) {echo "$query<br/>\n";}
	  $result=mysqli_query($db,$query);
	  if (mysqli_num_rows($result))
	  {
		  $row=mysqli_fetch_array($result);
		  $hmid=$row['human_manager_id'];
	
		  $query="UPDATE ootp_sql_admin SET value=0 WHERE scope=$lgid AND module='users' AND identifier=$hmid AND setting='auto'";
		  if ($_GET['showq']==1) {echo "$query<br/>\n";}
		  $result=mysqli_query($db,$query);

		  $query="UPDATE ootp_sql_admin SET value=0 WHERE scope=$lgid AND module='users' AND identifier=$hmid AND setting='auto_list'";
		  if ($_GET['showq']==1) {echo "$query<br/>\n";}
		  $result=mysqli_query($db,$query);
	  }

	  header('Location: ./draftSchedule.php?from='.$_SERVER['HTTP_REFERER'].'&create=0&schedule=1');
	  exit;
	  break;
  case 'auto_on':
	  $hmid=$_GET['hmid'];
	  $query="INSERT INTO ootp_sql_admin (scope,module,identifier,setting,value) VALUES ($lgid,'users',$hmid,'auto',1) ON DUPLICATE KEY UPDATE value=1";
	  if ($_GET['showq']==1) {echo "$query<br/>\n";}
	  $result=mysqli_query($db,$query);
	  header('Location: ./draftAdmin.php');
	  exit;
	  break;
  case 'auto_on_all':
	  $hmid=$_GET['hmid'];
	  $hms=explode(",",$hmid);
	  foreach ($hms as $key => $hmid)
	  {
		  $query="INSERT INTO ootp_sql_admin (scope,module,identifier,setting,value) VALUES ($lgid,'users',$hmid,'auto',1) ON DUPLICATE KEY UPDATE value=1";
		  if ($_GET['showq']==1) {echo "$query<br/>\n";}
		  $result=mysqli_query($db,$query);
	  }
	  header('Location: ./draftAdmin.php');
	  exit;
	  break;
  case 'auto_off':
	  $hmid=$_GET['hmid'];
	  $query="UPDATE ootp_sql_admin SET value=0 WHERE scope=$lgid AND module='users' AND identifier=$hmid AND setting='auto'";
	  if ($_GET['showq']==1) {echo "$query<br/>\n";}
	  $result=mysqli_query($db,$query);
	  header('Location: ./draftAdmin.php');
	  exit;
	  break;
  case 'auto_off_all':
	  $hmid=$_GET['hmid'];
	  $hms=explode(",",$hmid);
	  foreach ($hms as $key => $hmid)
	  {
		  $query="UPDATE ootp_sql_admin SET value=0 WHERE scope=$lgid AND module='users' AND identifier=$hmid AND setting='auto'";
		  if ($_GET['showq']==1) {echo "$query<br/>\n";}
		  $result=mysqli_query($db,$query);
	  }
	  header('Location: ./draftAdmin.php');
	  exit;
	  break;
  case 'auto_list_on':
	  $hmid=$_GET['hmid'];
	  $query="INSERT INTO ootp_sql_admin (scope,module,identifier,setting,value) VALUES ($lgid,'users',$hmid,'auto_list',1) ON DUPLICATE KEY UPDATE value=1";
	  if ($_GET['showq']==1) {echo "$query<br/>\n";}
	  $result=mysqli_query($db,$query);
	  header('Location: ./draftAdmin.php');
	  exit;
	  break;
  case 'auto_list_on_all':
	  $hmid=$_GET['hmid'];
	  $hms=explode(",",$hmid);
	  foreach ($hms as $key => $hmid)
	  {
		  $query="INSERT INTO ootp_sql_admin (scope,module,identifier,setting,value) VALUES ($lgid,'users',$hmid,'auto_list',1) ON DUPLICATE KEY UPDATE value=1";
		  if ($_GET['showq']==1) {echo "$query<br/>\n";}
		  $result=mysqli_query($db,$query);
	  }
	  header('Location: ./draftAdmin.php');
	  exit;
	  break;
  case 'auto_list_off':
	  $hmid=$_GET['hmid'];
	  $query="UPDATE ootp_sql_admin SET value=0 WHERE scope=$lgid AND module='users' AND identifier=$hmid AND setting='auto_list'";
	  if ($_GET['showq']==1) {echo "$query<br/>\n";}
	  $result=mysqli_query($db,$query);
	  header('Location: ./draftAdmin.php');
	  exit;
	  break;
  case 'auto_list_off_all':
	  $hmid=$_GET['hmid'];
	  $hms=explode(",",$hmid);
	  foreach ($hms as $key => $hmid)
	  {
		  $query="UPDATE ootp_sql_admin SET value=0 WHERE scope=$lgid AND module='users' AND identifier=$hmid AND setting='auto_list'";
		  if ($_GET['showq']==1) {echo "$query<br/>\n";}
		  $result=mysqli_query($db,$query);
	  }
	  header('Location: ./draftAdmin.php');
	  exit;
	  break;
  }

  ################## Proceed with Draft Choice ##################
  ##### Get pick information
  $query="SELECT human_manager_id,x.* FROM (SELECT round,supplemental,pick_round,team_id FROM amateur_draft WHERE league_id=$lgid";
  if ($mode!="Edit") {$query.=" AND player_id IS NULL";}
  if ((is_numeric($rnd))&&($rnd>0)) {$query.=" AND round=$rnd";}
  if ((is_numeric($supp))&&($supp>0)) {$query.=" AND supplemental=$supp";}
  if ((is_numeric($pick))&&($pick>0)) {$query.=" AND pick_round=$pick";}
  $query.=" ORDER BY round, supplemental, pick_round LIMIT 1) as x LEFT JOIN human_managers as hm ON hm.team_id=x.team_id";
  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'];

	  $hmid=$row['human_manager_id'];
  }
  else
  {
	  echo "ERROR: No valid pick found for team $team_id<br/>$query\n";
	  exit;
  }

  ##### Get Draft Settings
  $query="SELECT setting,identifier,value FROM ootp_sql_admin WHERE scope=$lgid AND (module='Draft' OR setting IN ('auto','autoRnd','auto_list'))";
  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'];
		  $identifier=$row['identifier'];
		  $val=$row['value'];

		  $settings[$setting][$identifier]=$val;

		  switch ($setting)
		  {
			  case 'draftOn'    : $draftOn=$val;   break;
			  case 'pauseAuto'  : $pauseAuto=$val; break;
			  case 'autoDelay'  : $autoDelay=$val; break;
			  case 'timerEnable': $timerOn=$val; break;
		  }
	  }
  }
  if ($draftOn==0) {$timerOn=0;}
  if (($autoDelay<=0)||($autoDelay=="")) {$autoDelay=0;}

  // Loop over pick process
  $makeSelection=1;
  while ($makeSelection>=1)
  {
	  unset($pid);

	  ##### Determine Player to Draft
	  ## Manual Pick
	  if ((is_numeric($player_id))&&($player_id>0)) 
	  {
		  $pid=$player_id;
		  $autoPick=0;

		  # Validate that manual picks are done by GM's and commishes only!
		  if (($hmid!=$user)&&($cmsh!=1)&&($mode!='auto_list_pick'))
		  {
			  echo "ERROR: You do not manage team $team_id and are not logged in as a commissioner.<br/>\n";
			  exit;
		  }
	  }
	  ## Auto Pick
	  elseif (!is_numeric($player_id))
	  {
		  //Check team draft list
		  if ($hmid>0)
		  {
			  $query="SELECT dp2.* FROM (SELECT dp1.player_id,if(porder IS NULL,999999,porder) as porder FROM (SELECT dp.player_id FROM ootp_sql_draft_pool as dp LEFT JOIN amateur_draft as ad ON dp.player_id=ad.player_id WHERE dp.league_id=$lgid AND ad.player_id IS NULL) as dp1 LEFT JOIN ootp_sql_draft_list as dl ON dp1.player_id=dl.player_id WHERE human_manager_id=$hmid ORDER BY porder) as dp2 GROUP BY player_id 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);
				  $pid=$row['player_id'];
				  $autoPick=1;
			  }
		  }
		  
		  //Check autodraft list
		  if (!isset($pid)||(!is_numeric($pid)))
		  {
			  $query="SELECT dp2.* FROM (SELECT dp1.player_id,if(porder IS NULL,999999,porder) as porder FROM (SELECT dp.player_id FROM ootp_sql_draft_pool as dp LEFT JOIN amateur_draft as ad ON dp.player_id=ad.player_id WHERE dp.league_id=$lgid AND ad.player_id IS NULL) as dp1 LEFT JOIN ootp_sql_draft_list as dl ON dp1.player_id=dl.player_id WHERE human_manager_id=";
			  if ($makeSelection==2) {$query.="-1000";} else  {$query.="-999";}
			  $query.=" ORDER BY porder) as dp2 GROUP BY player_id 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);
				  $pid=$row['player_id'];
				  $autoPick=1;
			  }
			  else {echo "ERROR: No player found for auto pick!  Try regenerating the autodraft list.<br/>$query<br/>\n";exit;}
		  }
	  }
	  else {$pid=$player_id;}
	
	  ##### Draft Player
	  $now=time();
      $chkTime=date("%Y-%m-%d %H:%M:%S",$now);
      
	  $query="UPDATE amateur_draft SET player_id=$pid,pick_time='$chkTime' WHERE league_id=$lgid AND round=$rnd AND supplemental=$supp AND pick_round=$pick";
	  if ($_GET['showq']==1) {echo "$query<br/>\n";}
	  $result=mysqli_query($db,$query);
	  
	  ## Send Slack Message
	  if (($settings['slackEnable'][-1]==1)||($settings['discordEnable'][-1]==1))
	  {
		## Get team
		$query="SELECT team_id FROM amateur_draft WHERE league_id=$lgid AND round=$rnd AND supplemental=$supp AND pick_round=$pick";
		$result=mysqli_query($db,$query);
		if (mysqli_num_rows($result))
		{
			$row=mysqli_fetch_array($result);
			$tid=$row['team_id'];
		}
		## Get player info
		$query="SELECT first_name,last_name,position,role,age,bats,throws FROM players WHERE player_id=$pid";
		$result=mysqli_query($db,$query);
		if (mysqli_num_rows($result))
		{
			$row=mysqli_fetch_array($result);
			$pos=$row['position'];
            $role=$row['role'];
            $position=get_pos(($pos==1?$role:$pos),1);
            $name=$row['first_name']." ".$row['last_name'];
            $age=$row['age'];
            $bats=get_hand($row['bats']);
            $throws=get_hand($row['throws']);
		}
          
        if ($settings['slackEnable'][-1]==1)
        {
            $msg=$lgAbbr." Draft Pick ".($supp==1?"S":"").$rnd.".".$pick.": The <$lgpath/teams/team_$tid.html|".$teams[$tid]['name']."> select $position <$lgpath/players/player_$pid.html|$name>";
            send_slack($adminpath,$lgid,'draft',$msg,$debug);
        }

        if ($settings['discordEnable'][-1]==1)
        {

            if ($rnd>$settings['discordDraftEmbedRnd'][-1])
            {
                $msg="";
                if ($settings['discordTeamEmojis'][-1]==1)
                {
                    $msg.=":".str_replace(" ","_",strtolower($teams[$tid]['name'])).": ";
                }
                $msg .= $lgAbbr." Draft Pick ".($supp==1?"S":"").$rnd.".".$pick.": ";
                $msg .= "The [".$teams[$tid]['name']."]($lgpath/teams/team_$tid.html) select ";
                $msg .= $age." year old ";
                $msg .= $position." [".$name."]($lgpath/players/player_$pid.html)";

                $dataArray = Array (
                                    "content" => $msg
                                    );
            }
            else
            {
                // Compose Title
                $title ="$lgAbbr ";
                if ($supp==1) {$title.="Supplemental ";}
                $title.=ordinal_suffix($rnd)." Round Draft Pick";
                $title.=" - Pick #".$pick;
                
                // Compose Primary Message
                $msg="";
                if ($fTid>0)
                {
                    $msg.="From the [".$teams[$fTid]['name']."]($lgpath/teams/team_$fTid.html), t";

                }
                else {$msg.="T";}
                $msg .= "he [".$teams[$tid]['name']."]($lgpath/teams/team_$tid.html) select ";
                $msg .= $age." year old ";
                if ($pos==1)
                {
                    switch ($throws)
                    {
                        case 'L': $msg.="lefty "; break;
                        default: $msg.="righty "; break;
                    }
                }
                $msg .= $position." [".$name."]($lgpath/players/player_$pid.html)";

                // Find color for bar
                $tBright = color_brightness($teams[$tid]['text_color_id']);
                $bBright = color_brightness($teams[$tid]['background_color_id']);
                if ( ($tBright > $bBright) || ($bBright > 200) ) {
                    if ($tBright > 200) {$barColor=$teams[$tid]['background_color_id'];}
                    else {$barColor = $teams[$tid]['text_color_id'];}
                }
                else {
                    $barColor = $teams[$tid]['background_color_id'];
                }

                // Compose embed fields
                $fields=Array();
                // Get Player Stats & Ratings
                $showStats=0;
                $showRats=0;
                if ($pos==1)
                {
                    $statArray = Array("g","w","l","s","ip","k","era");
                    $statTable = "players_career_pitching_stats";
                    $ratArray  = Array("pitching_ratings_talent_stuff","pitching_ratings_talent_control","pitching_ratings_talent_movement","pitching_ratings_misc_velocity","pitching_ratings_misc_stamina");
                    $pitchArray = Array(
                                        "pitching_ratings_pitches_talent_fastball"
                                        ,"pitching_ratings_pitches_talent_slider"
                                        ,"pitching_ratings_pitches_talent_curveball"
                                        ,"pitching_ratings_pitches_talent_screwball"
                                        ,"pitching_ratings_pitches_talent_forkball"
                                        ,"pitching_ratings_pitches_talent_changeup"
                                        ,"pitching_ratings_pitches_talent_sinker"
                                        ,"pitching_ratings_pitches_talent_splitter"
                                        ,"pitching_ratings_pitches_talent_knuckleball"
                                        ,"pitching_ratings_pitches_talent_cutter"
                                        ,"pitching_ratings_pitches_talent_circlechange"
                                        ,"pitching_ratings_pitches_talent_knucklecurve"
                                        );
                    $ratTable  = "players_pitching";
                }
                else
                {
                    $statArray=Array("g","avg","hr","rbi","sb","ops");
                    $statTable = "players_career_batting_stats";
                    $ratArray  = Array("batting_ratings_talent_contact","batting_ratings_talent_power","batting_ratings_talent_eye");
                    $ratTable  = "players_batting";
                }
                $fTid=0;
                // Stats Query
                $query="SELECT pcs.player_id,pcs.team_id,pcs.year,pcs.league_id,lgt.league_level,pcs.stint";
                foreach ($statArray as $key => $statLbl) {$query.=",".stat_query($statLbl)." as $statLbl";}
                $query.=" FROM ".$statTable." as pcs,leagues as lgt";
                $query.=" WHERE pcs.league_id=lgt.league_id AND lgt.parent_league_id=$lgid AND lgt.league_level IN (10,11)";
                $query.=" AND pcs.player_id=$pid";
                $query.=" AND pcs.split_id=1";
                $query.=" GROUP BY player_id,year,league_id";
                $query.=" ORDER BY year DESC, stint DESC, league_level";
                $query.=" 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);
                    $fTid=$row['team_id'];
                    
                    $statEmbed=Array();
                    $statEmbed['name']=$row['year']." Statistics";
                    
                    $statEmbed['value']="";
                    $statCnt=0;
                    foreach ($statArray as $key => $statLbl)
                    {
                        $statVal=$row[$statLbl];
                        if ($statCnt>0) {$statEmbed['value'].=", ";}
                        $statEmbed['value'].=stat_format($statLbl,$statVal)." ".stat_text($statLbl,2);
                        $statCnt++;
                    }
                    $statEmbed['inline']="false";
                    
                    $fldCnt=count($fields);
                    $fields[$fldCnt]=$statEmbed;
                }
                // Ratings Query
                $ratEmbed=Array();
                $query="SELECT player_id";
                foreach ($ratArray as $key => $ratLbl)
                {
                    # Get scale
                    if ($settings['rawRatings']==1)
                    {
                        $ratScale=get_scale($ratLbl);
                        $scale=$settings[$ratScale][-1];
                    }
                    else {$scale='Raw';}

                    $query.=",".ratings_query($ratLbl,$scale)." as $ratLbl";
                }
                if ($pos==1)
                {
                    foreach ($pitchArray as $key => $ratLbl)
                    {
                        # Get scale
                        if ($settings['rawRatings']==1)
                        {
                            $ratScale=get_scale($ratLbl);
                            $scale=$settings[$ratScale][-1];
                        }
                        else {$scale='Raw';}

                        $query.=",".ratings_query($ratLbl,$scale)." as $ratLbl";
                    }
                }
                $query.=" FROM ".$ratTable;
                $query.=" WHERE player_id=$pid";
                if ($_GET['showq']==1) {echo "$query<br/>\n";}
                $result=mysqli_query($db,$query);
                if (mysqli_num_rows($result))
                {
                    $row=mysqli_fetch_array($result);
                    
                    foreach ($ratArray as $key => $ratLbl)
                    {
                        $ratEmbed=Array();
                        $ratEmbed['name']=str_replace(" (Pot)","",stat_text($ratLbl));
                        $ratEmbed['value']=stat_format($ratLbl,$row[$ratLbl]);
                        $ratEmbed['inline']="true";

                        $fldCnt=count($fields);
                        $fields[$fldCnt]=$ratEmbed;
                    }
                    // Get pitches
                    if ($pos==1)
                    {
                        $pCnt=0;
                        $pText="";
                        foreach ($pitchArray as $key => $ratLbl)
                        {
                            if (!is_numeric($row[$ratLbl])) {continue;}
                            if ($pCnt>0) {$pText.=", ";}
                            $pText.=stat_text($ratLbl,2);
                            $pCnt++;
                        }
                        $ratEmbed=Array();
                        $ratEmbed['name']="$pCnt Pitches";
                        $ratEmbed['value']=$pText;
                        $ratEmbed['inline']="true";

                        $fldCnt=count($fields);
                        $fields[$fldCnt]=$ratEmbed;
                    }
                }
                // Fielding Ratings
                if ($pos!=1)
                {
                    // Bats
                    $ratEmbed=Array();
                    $ratEmbed['name']="Bats";
                    $ratEmbed['value']=$bats;
                    $ratEmbed['inline']="true";
                    $fldCnt=count($fields);
                    $fields[$fldCnt]=$ratEmbed;
                    // Throws
                    $ratEmbed=Array();
                    $ratEmbed['name']="Throws";
                    $ratEmbed['value']=$throws;
                    $ratEmbed['inline']="true";
                    $fldCnt=count($fields);
                    $fields[$fldCnt]=$ratEmbed;

                    //Positions
                    $query="SELECT player_id";
                    for ($i=2;$i<=9;$i++)
                    {
                        $ratLbl="fielding_rating_pos".$i;
                        # Get scale
                        if ($settings['rawRatings']==1)
                        {
                            $ratScale=get_scale($ratLbl);
                            $scale=$settings[$ratScale][-1];
                        }
                        else {$scale='Raw';}

                        $query.=",".ratings_query($ratLbl,$scale)." as $ratLbl";
                    }
                    $query.=" FROM players_fielding WHERE player_id=$pid";
                    if ($_GET['showq']==1) {echo "$query<br/>\n";}
                    $result=mysqli_query($db,$query);
                    if (mysqli_num_rows($result))
                    {
                        $row=mysqli_fetch_array($result);

                        $pCnt=0;
                        $pText="";
                        for ($i=2;$i<=9;$i++)
                        {
                            $ratLbl="fielding_rating_pos".$i;

                            if (!is_numeric($row[$ratLbl])) {continue;}
                            if ($pCnt>0) {$pText.=", ";}
                            $pText.=stat_text($ratLbl,2);
                            $pCnt++;
                        }
                        $ratEmbed=Array();
                        $ratEmbed['name']="Positions";
                        $ratEmbed['value']=$pText;
                        $ratEmbed['inline']="true";

                        $fldCnt=count($fields);
                        $fields[$fldCnt]=$ratEmbed;
                    }
                }
                
                // Compose Embed
                $dataArray = Array (
                      "username"   => 'StatsLab',
                      "embeds" => Array(
                                        Array(
                                              "title" => $title,
                                              "type" => "rich",
                                              "color" => hexdec($barColor),
                                              "description" => $msg,
                                              "thumbnail" => [
                                                "url" => $HTMLPath."/images/team_logos/".$teams[$tid]['logo_file_name']
                                              ]
                                              ,
                                              "fields" => $fields
                                              )
                                       )
                );
            }

            send_discord($adminpath,$lgid,'Draft',$dataArray,$debug);
        }
      }
            
	  ##### Set team to auto if appropriate
	  if (($autoPick==1)&&($makeSelection==1)&&($mode!='manualauto')&&($settings['setAuto'][-1]==1))
	  {
		  $query="INSERT INTO ootp_sql_admin (scope,module,identifier,setting,value) VALUES ($lgid,'users',$hmid,'auto',1) ON DUPLICATE KEY UPDATE value=1";
		  if ($_GET['showq']==1) {echo "$query<br/>\n";}
		  mysqli_query($db,$query);
		  if ($settings['autoRnd'][$hmid]>=$rnd)
		  {
			  $query="INSERT INTO ootp_sql_admin (scope,module,identifier,setting,value) VALUES ($lgid,'users',$hmid,'autoRnd',".($rnd+$supp-1).") ON DUPLICATE KEY UPDATE value=".($rnd+$supp-1);
			  mysqli_query($db,$query);
		  }
	  	  ## Inform Slack
		  if ($settings['slackEnable'][-1]==1)
		  {
			  $msg="The ".$teams[$tid]['name']." have been set to auto draft";
			  send_slack($adminpath,$lgid,'draft',$msg,$debug);
		  }

          //Send to Discord
          if ($settings['discordEnable'][-1]==1)
          {
              $msg="The ".$teams[$tid]['name']." have been set to auto draft";
              $dataArray = Array (
                                  "content" => $msg
                                  );
              send_discord($adminpath,$lgid,'Draft',$dataArray,$debug);
          }
	  }
	
	  ##### Determine If Next Pick Should Be Made
	  $makeSelection=-1;  // Draft complete/no email flag
	  ## Get next pick and team
	  $query="SELECT human_manager_id,x.* FROM (SELECT round,supplemental,pick_round,team_id,pick_time,TIMESTAMPDIFF(SECOND,pick_time,'$chkTime') as time_difference FROM amateur_draft WHERE league_id=$lgid AND player_id IS NULL ORDER BY round, supplemental, pick_round LIMIT 1) as x LEFT JOIN human_managers as hm ON hm.team_id=x.team_id";
	  if ($_GET['showq']==1) {echo "$query<br/>\n";}
	  $result=mysqli_query($db,$query);
	  if (mysqli_num_rows($result))
	  {
		  $row=mysqli_fetch_array($result);
		  $hmid=$row['human_manager_id'];
		  $rnd=$row['round'];
		  $supp=$row['supplemental'];
		  $pick=$row['pick_round'];
		  $tid=$row['team_id'];
		  $tdiff=$row['time_difference'];
	
		  $makeSelection=0;  // Next pick found
	  }


	  ## Determine if pick should happen now or later
	  if ($_GET['showq']==1) {echo "Processing next pick: hmid=$hmid (".(is_null($hmid)?"NULL":$hmid)."), autoOpen=".$settings['autoOpen'][-1].", autoList=".$settings['auto_list'][$hmid].", autoDelay=$autoDelay<br/>\n";}
	
	  if ((is_null($hmid))&&(($settings['autoOpen'][-1]==0)||($autoDelay>0))) {$makeSelection=-1;}
	  elseif (($autoDelay<=0)&&($makeSelection!=-1))
	  {
		  ## Check team auto settings
		  if ($settings['auto_list'][$hmid]==1) {$makeSelection=2;}
		  elseif ($settings['auto'][$hmid]==1)
		  {
			  $autoRnd=$settings['autoRnd'][$hmid];
			  if (is_numeric($autoRnd))
			  {
				  if (($rnd>$autoRnd)||(($supp==1)&&($rnd==$autoRnd))) {$makeSelection=1;}
			  }
			  else
			  {
				  $autoRnd=substr($autoRnd,1,99);
				  if ($rnd>$autoRnd) {$makeSelection=1;}
			  }
		  }
	  }
	  elseif ($autoDelay<=600) {$makeSelection=-1;}  // Auto delay less than 10 minutes

	  unset($player_id);
	  unset($mode);
  }  // End pick process loop

  ##### Reschedule picks if needed
  if ($settings['flexTimer'][-1]==1)
  {
	  header('Location: ./draftSchedule.php?from=draftBoard.php&create=0&schedule=1');
  }

  ##### Email GM's
  // Decide if email is appropriate
  if ($makeSelection==0)
  {
	  // Get email settings
	  $query="SELECT setting,value FROM ootp_sql_admin WHERE ((scope=$lgid AND module='Draft' AND setting IN ('emailList','replyList')) OR setting IN ('ServerURL','StatsLabPath'))";
  	  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'];
			  $settings[$setting]=$row['value'];
		  }

		  if ($settings['emailList']!='None')
		  {
			  // Get user emails
			  $query="SELECT first_name,last_name,is_commish,setting,identifier,value FROM ootp_sql_admin as osa,human_managers as hm WHERE osa.identifier=hm.human_manager_id AND module='users' AND setting IN ('email','draftSubscribe') AND (is_commish=1 OR league_id=$lgid)";
			  if ($_GET['showq']==1) {echo "$query<br/>\n";}
			  $result=mysqli_query($db,$query);
			  if (mysqli_num_rows($result))
			  {
				  while ($row=mysqli_fetch_array($result))
				  {
					  $mgrID=$row['identifier'];
					  $mgrList[$mgrID]['name']=$row['first_name']." ".$row['last_name'];
					  $mgrList[$mgrID]['cmsh']=$row['is_commish'];

					  $setting=$row['setting'];
					  $mgrList[$mgrID][$setting]=$row['value'];
				  }

				  ## Get to/from lists
				  $toList="";
				  $replyList="";
				  $badList="";
				  foreach ($mgrList as $mgrID => $val)
				  {
					  if (!filter_var($mgrList[$mgrID]['email'], FILTER_VALIDATE_EMAIL))
					  {
						  $badList.=$mgrID." :: ".$mgrList[$mgrID]['name']." <".$mgrList[$mgrID]['email']."><br/>\n";
						  continue;
					  }
					  
					  // Include commishes in both
					  if ($mgrList[$mgrID]['cmsh']==1)
					  {
						  $toList.=", ".$mgrList[$mgrID]['name']." <".$mgrList[$mgrID]['email'].">";
						  $replyList.=", ".$mgrList[$mgrID]['name']." <".$mgrList[$mgrID]['email'].">";
					  }
					  else
					  {
						  // Add to email list
						  if (
							  ($settings['emailList']=='All')
							  || (($settings['emailList']=='Subscribed')&&($mgrList[$mgrID]['draftSubscribe']==1))
							  || ($hmid==$mgrID)   // Active Pick
						  ) {$toList.=", ".$mgrList[$mgrID]['name']." <".$mgrList[$mgrID]['email'].">";}

						  // Add to from list
						  if (
							  ($settings['replyList']=='All')
							  || (($settings['replyList']=='Subscribed')&&($mgrList[$mgrID]['draftSubscribe']==1))
						  ) {$replyList.=", ".$mgrList[$mgrID]['name']." <".$mgrList[$mgrID]['email'].">";}
					  }
				  }
				  $toList=trim($toList,",");
				  $replyList=trim($replyList,",");

				  ## Get From Address
				  unset($fromList);
				  $query="SELECT value FROM ootp_sql_admin WHERE setting='emailFrom'";
				  if ($_GET['showq']==1) {echo "$query<br/>\n";}
				  $result=mysqli_query($db,$query);
				  if (mysqli_num_rows($result))
				  {
					  $row=mysqli_fetch_array($result);
					  $fromList=$row['value'];
				  }
				  if (!isset($fromList)||($fromList==""))
				  {
					  $fromList=$replyList;
				  }

				  if (($toList=="")||($replyList==""))
				  {
					  echo "Unable to find any valid email address for emailing<br/>\n";
					  echo $badList;
					  exit;
				  }

				  ## Compose email
				  $header  = "From: ".$fromList."\r\n";
				  $header .= "Reply-To: ".$replyList." \r\n";
				  $header .= "MIME-Version: 1.0\r\n";
				  $header .= "Content-type: text/html; charset=iso-8859-1\r\n";

				  $subject="StatsLab Draft Update";
				  $subject=$teams[$tid]['abbr']." up in $lgAbbr draft - ".$subject;
				  
				  // Get upcoming picks
				  $query="SELECT round,supplemental,pick_round,team_id,pick_time FROM amateur_draft WHERE league_id=$lgid AND player_id IS NULL ORDER BY round,supplemental,pick_round LIMIT $nTeams;";
				  if ($_GET['showq']==1) {echo "$query<br/>\n";}
				  $result=mysqli_query($db,$query);
				  if (mysqli_num_rows($result))
				  {
					  $message="Upcoming Draft Picks:<br/>\n";
					  $prevRnd=0;
					  while ($row=mysqli_fetch_array($result))
					  {
						  $team_id=$row['team_id'];

						  if ($prevRnd!=($row['round']+($row['supplmental']/10))) {$message.="<br/>\n";}

						  if ($row['supplemental']==1) {$message.="S";}
						  $message.=$row['round'].".".$row['pick_round']." - ";
						  if ($row['pick_time']!="") {$message.=$row['pick_time']." - ";}
						  $message.="<a href='".$_SESSION['lgpath']."/teams/team_$team_id.html''>".$teams[$team_id]['name']."</a>";
						  $message.="<br/>\n";

						  $prevRnd=$row['round']+($row['supplmental']/10);
					  }
				  }
				  else
				  {
					  $message="No picks remaining.<br/>\n";
				  }

				  $message.="<br/><a href='".$settings['ServerURL'].$settings['StatsLabPath']."/draftBoard.php'>Go to StatsLab</a>";

				  ## Send email
				  mail($toList,$subject,$message,$header);
			  }
		  }
	  }
  }

  
  mysqli_close($db);

  if ($settings['flexTimer'][-1]!=1)
  {
	  header('Location: ./draftBoard.php');
  }
?>
