<?php

  include("html_functions.php");



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

  $lgid=$_SESSION['lgid'];

  $lgdate=$_SESSION['lgdate'];

  $date=new DateTime($lgdate);

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

  $hmid=-999;

  if (isset($_GET['hmid'])) {$hmid=$_GET['hmid'];}

  

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

  $title='Draft Auto List Generation';



  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("draft","Draft");

	  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("draft","Draft");

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

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

  }



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

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



  ##### Get Ratings Config

  $query="SELECT setting,value FROM ootp_sql_admin WHERE scope IN ('ALL',$lgid) AND module IN ('users','admin') AND identifier IN (-1,$hmid) AND setting IN ('Ratings','Talents','Others','scoutsOn','rawRatings')";

  $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['Ratings']=='Hidden') {$settings['Ratings']="1-5";}
  if ($settings['Talents']=='Hidden') {$settings['Talents']="1-5";}
  if ($settings['Others']=='Hidden') {$settings['Others']="1-5";}

  $scale=$settings['Talents'];

  if ($scale=='Raw')
  {
      // Lookup min and max ratings in the table to determine scale
      $query="SELECT ";
      $query.="LEAST(MIN(batting_ratings_talent_contact),MIN(batting_ratings_talent_power),MIN(batting_ratings_talent_eye)) as minRat,";
      $query.="GREATEST(MAX(batting_ratings_talent_contact),MAX(batting_ratings_talent_power),MAX(batting_ratings_talent_eye)) as maxRat";
      $query.=" FROM players_batting WHERE 1;";
      $result=mysqli_query($db,$query);
      if (mysqli_num_rows($result))
      {
          $row=mysqli_fetch_array($result);
          $scMin=$row['minRat'];
          $scMax=$row['maxRat'];
      }
  }
  else
  {
      $e=explode("-",$scale);
      $scMin=$e[0];
      $scMax=$e[1];
  }
  $scAvg=$scMin+($scMax-$scMin)/2;

  ##### Find Draft Eligible Players

  $runArray=Array('running_ratings_speed','running_ratings_stealing','running_ratings_baserunning');

  $query="SELECT p.player_id";

  $query.=" FROM players as p,ootp_sql_draft_pool as dp WHERE p.player_id=dp.player_id AND dp.league_id=$lgid;";

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

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

  if (!mysqli_num_rows($result))

  {

	  echo "No players found in draft pool.  Please generate or import the draft pool first.<br/><br/>Return to the <a href='./draftAdmin.php'>draft admin</a> page<br/>\n";

	

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

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

	  page_foot($_SESSION['lgpath']);

	  exit;

  }

  else

  {

	  while ($row=mysqli_fetch_array($result))

      	  {

		  $pid=$row['player_id'];

      	  }

  }



  ##### Get Scaled Batter Ratings

  $ratArray=Array('batting_ratings_overall_contact','batting_ratings_overall_gap','batting_ratings_overall_power','batting_ratings_overall_eye','batting_ratings_overall_strikeouts','batting_ratings_talent_contact','batting_ratings_talent_gap','batting_ratings_talent_power','batting_ratings_talent_eye','batting_ratings_talent_strikeouts');

  $query="SELECT p.player_id";

  foreach ($ratArray as $key => $ratLbl)

  {

	  # Get scale
      if ($settings['rawRatings']==1)
      {
          $ratScale=get_scale($ratLbl);
          $scale=$settings[$ratScale];
      }
      else {$scale='Raw';}

	  # Add to query
	  $query.=",";
	  $query.=ratings_query($ratLbl,$scale);
	  $query.=" as $ratLbl";

  }

  foreach ($runArray as $key => $ratLbl)

  {

      # Get scale
      if ($settings['rawRatings']==1)
      {
          $ratScale=get_scale($ratLbl);
          $scale=$settings[$ratScale];
      }
      else {$scale='Raw';}

      # Add to query

      $query.=",";

      $query.=ratings_query($ratLbl,$scale);

      $query.=" as $ratLbl";

  }

  $query.=" FROM players_batting";

  if ($settings['scoutsOn']==1) {$query.="_scouted";}

  $query.=" as p,ootp_sql_draft_pool as dp WHERE p.player_id=dp.player_id AND dp.league_id=$lgid;";

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

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

  while ($row=mysqli_fetch_array($result))

  {

	  $pid=$row['player_id'];

	  $value=0;



	  foreach ($ratArray as $key => $ratLbl)

	  {

		  $val=$row[$ratLbl];

		  switch ($ratLbl)

		  {

		  case 'batting_ratings_overall_contact':

			  $val=6*$val;

	       		  $value+=$val;

			  break;

		  case 'batting_ratings_overall_gap':

			  $val=2*$val;

	       		  $value+=$val;

			  break;

		  case 'batting_ratings_overall_power':

			  $val=4*$val;

	       		  $value+=$val;

			  break;

		  case 'batting_ratings_overall_eye':

			  $val=3*$val;

	       		  $value+=$val;

			  break;

		  case 'batting_ratings_overall_strikeouts':

			  $val=1*$val;

	       		  $value+=$val;

			  break;

		  case 'batting_ratings_talent_contact':

			  $val=30*$val;

	       		  $value+=$val;

			  break;

		  case 'batting_ratings_talent_gap':

			  $val=10*$val;

	       		  $value+=$val;

			  break;

		  case 'batting_ratings_talent_power':

			  $val=17*$val;

	       		  $value+=$val;

			  break;

		  case 'batting_ratings_talent_eye':

			  $val=15*$val;

	       		  $value+=$val;

			  break;

		  case 'batting_ratings_talent_strikeouts':

			  $val=5*$val;

	       		  $value+=$val;

			  break;

		  }

	  }



	  #Power

	  if ($scAvg<=(($row['batting_ratings_talent_contact']+$row['batting_ratings_talent_power'])/2)) {$value+=2;}

	  #On-Base

	  if ($scAvg<=(($row['batting_ratings_talent_contact']+$row['batting_ratings_talent_eye'])/2)) {$value+=2;}

	  #TTO

	  if ($scAvg<=(($row['batting_ratings_talent_power']+$row['batting_ratings_talent_eye'])/2)) {$value+=2;}

	  #TripleThreat

	  if ($scAvg<=(($row['batting_ratings_talent_contact']+$row['batting_ratings_talent_power']+$row['batting_ratings_talent_eye'])/3)) {$value+=4;}

	  #Contact Issues

	  if ($row['batting_ratings_talent_contact']>(1.5*$scAvg)) {$value+=10;}

	  if ($scAvg>$row['batting_ratings_talent_contact']) {$value-=10;}

	  if ((.5*$scAvg)>$row['batting_ratings_talent_contact']) {$value-=10;}



	  ## Process running ratings
      foreach ($runArray as $key => $ratLbl)
      {
          $val=$row[$ratLbl];
          $players[$pid][$ratLbl]=$val;
      }

	  foreach ($runArray as $key => $ratLbl)
	  {

		  $val=$players[$pid][$ratLbl];

		  switch ($ratLbl)
		  {
		  case 'running_ratings_speed':
			  $val=3*$val;
              $value+=$val;
			  break;

		  case 'running_ratings_stealing':
			  $val=3*$val;
              $value+=$val;
			  break;

		  case 'running_ratings_baserunning':
			  $val=1*$val;
              $value+=$val;
			  break;
          }

	  }



	  $value=$value/100;



	  $bvalues[$pid]=$value;

  }



  ##### Get Fielding Ratings

  $query="SELECT p.player_id,fielding_ratings_infield_arm,fielding_ratings_outfield_arm,fielding_ratings_catcher_arm,fielding_rating_pos2,fielding_rating_pos4,fielding_rating_pos5,fielding_rating_pos6,fielding_rating_pos8,fielding_rating_pos9 FROM players_fielding";

  if ($settings['scoutsOn']==1) {$query.="_scouted";}

  $query.=" as p,ootp_sql_draft_pool as dp WHERE p.player_id=dp.player_id AND dp.league_id=$lgid;";

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

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

  while ($row=mysqli_fetch_array($result))

  {

	  $pid=$row['player_id'];



	  $mod=0;

       	  $bcnt=0;

	  if ($row['fielding_rating_pos2']>1)

	  {

		  $mod+=.02;$bcnt+=1;

		  if ($row['fielding_ratings_catcher_arm']>100) {$mod+=.005;$bcnt+=1;}

	  }

	  if ($row['fielding_rating_pos4']>100) {$mod+=.01;$bcnt+=1;}

       	  if ($row['fielding_rating_pos5']>120) {$mod+=.008;$bcnt+=1;}

	  elseif (($row['fielding_rating_pos5']>60)&&($row['fielding_ratings_infield_arm']>100)) {$mod+=.005;$bcnt+=1;}

       	  if ($row['fielding_rating_pos6']>100) {$mod+=.017;$bcnt+=1;}

	  if ($row['fielding_rating_pos8']>100) {$mod+=.0075;$bcnt+=1;}

       	  if (($row['fielding_rating_pos9']>60)&&($row['fielding_ratings_outfield_arm']>100)) {$mod+=.005;$bcnt+=1;}

	  switch ($bcnt)

	  {

    	  case 0: 

	  case 1: $mod=$mod*1.00; break;

    	  case 2: $mod=$mod*.800; break;

	  case 3: $mod=$mod*.650; break;

    	  case 4: $mod=$mod*.600; break;

	  case 5: $mod=$mod*.575; break;

    	  case 6: 

	  case 7: 

    	  case 8: $mod=$mod*.550; break;

	  default: break;

      	  }

	  $bvalues[$pid]=$bvalues[$pid]*(1+$mod);

  }



  ##### Get Scaled Pitching Ratings

  $pitches=array("fastball","slider","curveball","screwball","forkball","changeup","sinker","splitter","knuckleball","cutter","circlechange","knucklecurve");

  $ratArray=Array("pitching_ratings_overall_stuff","pitching_ratings_overall_control","pitching_ratings_overall_movement","pitching_ratings_talent_stuff","pitching_ratings_talent_control","pitching_ratings_talent_movement","pitching_ratings_misc_velocity","pitching_ratings_misc_stamina");

  $query="SELECT p.player_id";

  foreach ($ratArray as $key => $ratLbl)

  {

	  switch ($ratLbl)

	  {

	  case 'pitching_ratings_misc_velocity':

	  case 'pitching_ratings_misc_stamina':

		  $query.=",$ratLbl";

		  break;

	  default:

		  # Get scale
          if ($settings['rawRatings']==1)
          {
              $ratScale=get_scale($ratLbl);
              $scale=$settings[$ratScale];
          }
          else {$scale='Raw';}

		  # Add to query

		  $query.=",";

		  $query.=ratings_query($ratLbl,$scale);

		  $query.=" as $ratLbl";

		  break;

	  }

  }

  foreach ($pitches as $key => $pitch)

  {

	  $query.=",pitching_ratings_pitches_$pitch";

       	  $query.=",pitching_ratings_pitches_talent_$pitch";

  }

  $query.=" FROM players_pitching";

  if ($settings['scoutsOn']==1) {$query.="_scouted";}

  $query.=" as p,ootp_sql_draft_pool as dp WHERE p.player_id=dp.player_id AND dp.league_id=$lgid;";

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

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

  while ($row=mysqli_fetch_array($result))

  {

	  $pid=$row['player_id'];

	  $value=0;



	  foreach ($ratArray as $key => $ratLbl)

	  {

		  $val=$row[$ratLbl];

		  switch ($ratLbl)

		  {

		  case 'pitching_ratings_overall_stuff':

		  case 'pitching_ratings_overall_control':

		  case 'pitching_ratings_overall_movement':

			  $val=3*$val;

	       		  $value+=$val;

			  break;

		  case 'pitching_ratings_talent_stuff':

		  case 'pitching_ratings_talent_control':

		  case 'pitching_ratings_talent_movement':

			  $val=20*$val;

	       		  $value+=$val;

			  break;

		  case 'pitching_ratings_misc_velocity':

			  $val=2*$val;

	       		  $value+=$val;

			  break;

		  case 'pitching_ratings_misc_stamina':

			  $val=1*$val;

	       		  $value+=$val;

			  break;

		  }

	  }



	  $value=$value/72;

       

	  $mod=1;

	  $pitchCnt=0;

       	  $qpc=0;

	  foreach ($pitches as $key => $pitch)

	  {

		  $field="pitching_ratings_pitches_".$pitch;

		  $pvalue=$row[$field];

	    	  if ($pvalue>180) {$mod+=0.001;}

		  if ($pvalue>160) {$mod+=0.001;}

	    	  if ($pvalue>130) {$mod+=0.001;}

		  if ($pvalue>100) {$mod+=0.001;}

	    	  if ($pvalue>0) {$mod+=0.001;}

		  $field="pitching_ratings_pitches_talent_".$pitch;

	    	  $pvalue=$row[$field];

		  if ($pvalue>180) {$mod+=0.02;}

	    	  if ($pvalue>160) {$mod+=0.02;}

		  if ($pvalue>130) {$mod+=0.02;$qpc+=1;}

	    	  if ($pvalue>100) {$mod+=0.02;}

		  if ($pvalue>0) {$mod+=0.02;$pitchCnt+=1;}

      	  }

	  if ($qpc>0) {$mod+=(($qpc-1)*0.05);}

	       

	  $value=$mod*$value;



	  $pvalues[$pid]=$value;

  }



  ##### Combine Batters and Pitchers

  ## Determine best case as batter or pitcher

  foreach ($bvalues as $pid => $val)

  {

	  if (isset($pvalues[$pid]))

      	  {

		  if ($pvalues[$pid]>$bvalues[$pid]) {unset($bvalues[$pid]);continue;} else {unset($pvalues[$pid]);}

      	  }

  }



  ## Calculate avg

  $bavg=average($bvalues);

  $pavg=average($pvalues);

  

  ## Calculate Deviation

  $bstd=deviation($bvalues);

  $pstd=deviation($pvalues);

  

  ## Compute z-Score

  foreach ($bvalues as $pid => $val) {$values[$pid]=($bvalues[$pid]-$bavg)/$bstd;}

  foreach ($pvalues as $pid => $val) {$values[$pid]=0.85*($pvalues[$pid]-$pavg)/$pstd;}

	  

  arsort($values);









  ##### Save as auto list

  $cnt=1;

  $query="";

  foreach ($values as $pid => $val)

  {

	  $query.="INSERT INTO ootp_sql_draft_list (human_manager_id,league_id,porder,player_id)";

	  $query.=" VALUES ($hmid,$lgid,$cnt,$pid);";

	  if ($_GET['showq']==1) {$query.="Value: $val B: ".(isset($bvalues[$pid])?$bvalues[$pid]:"-")." P: ".(isset($pvalues[$pid])?$pvalues[$pid]:"-").";";}



	  $cnt++;

  }



  if ($query!="")

  {

	  $clearQuery="DELETE FROM ootp_sql_draft_list WHERE league_id=$lgid AND human_manager_id=$hmid";
      if ($_GET['showq']==1) {echo "$clearQuery<br/>\n";}
	  mysqli_query($db,$clearQuery);



	  $q=explode(";",$query);

	  foreach ($q as $key => $impQuery)

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

          if ($impQuery[0]=="V") {continue;}
		  mysqli_query($db,$impQuery);

	  }



	  echo "Imported ".($cnt-1)." players to your auto draft list<br/> - NOTE: Player eligibility subject to accurate settings on draft admin page<br/>\n";

  }

  else

  {

	  echo "No draft eligible players found.<br/>\n";

  }



  echo "Return to the <a href='./draftAdmin.php'>draft admin</a> page<br/>\n";



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

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

  page_foot($_SESSION['lgpath']);



?>

