<?php

  include("html_functions.php");



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

  $lgid=$_SESSION['lgid'];

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

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

  $hmid=$_SESSION['user_id'];

  

  ## Get Filter Settings

  $listView=$_GET['listView'];

  $who     =$_GET['who'];

  $view    =$_GET['view'];

  $statLg  =$_GET['statLg'];

  $statView=$_GET['statView'];

  $minPT   =$_GET['minPT'];

  $sort1   =$_GET['sort1'];

  $sort2   =$_GET['sort2'];

  $sort3   =$_GET['sort3'];



  if ($listView=="") {$listView='All';     }

  if ($who=="")      {$who     ="batters"; }

  if ($view=="")

  {

	  if ((!isset($settings['Talents']))||($settings['Talents']=='Hidden')) {$view='stats';}

	  else {$view='talent';}

  }

  if ($statLg=="")   {$statLg  ='All';     }

  if ($statView=="") {$statView='career';  }



  //Sort defaults

  switch ($who)

  {

  case 'pitchers':

  case 11:

  case 12:

  case 13:

	  switch ($view)

	  {

	  case 'overall':

	  case 'talent':

		  $sortList=Array("pitching_ratings_talent_stuff","pitching_ratings_talent_control","pitching_ratings_talent_movement","pitching_ratings_misc_velocity","pitching_ratings_misc_stamina","last_name,first_name","age","lvl","porder");

		  $ratArray=Array("pitching_ratings_talent_stuff","pitching_ratings_talent_control","pitching_ratings_talent_movement","pitching_ratings_misc_velocity","pitching_ratings_misc_stamina","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","pitching_ratings_misc_ground_fly");

		  break;

	  case 'stats':

		  $sortList=Array('pk','era','whip','w','l','s','cg','sho','pg','gs','ip','ha','pr','er','hra','pbb','oavg','babip',"last_name,first_name","age","lvl","porder");

		  $statArray=Array('w','l','s','cg','sho','era','g','gs','ip','ha','r','er','hra','bb','k','whip','oavg','babip');

		  break;

	  }

	  break;

  default:

	  switch ($view)

	  {

	  case 'overall':

	  case 'talent':

		  $sortList=Array('batting_ratings_talent_contact','batting_ratings_talent_power','batting_ratings_talent_eye','batting_ratings_talent_gap','batting_ratings_talent_strikeouts','running_ratings_speed','running_ratings_stealing','running_ratings_baserunning',"last_name,first_name","age","lvl","porder");

		  $ratArray=Array('batting_ratings_talent_contact','batting_ratings_talent_gap','batting_ratings_talent_power','batting_ratings_talent_eye','batting_ratings_talent_strikeouts');

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

		  $fldArray=Array('fielding_rating_pos2','fielding_rating_pos3','fielding_rating_pos4','fielding_rating_pos5','fielding_rating_pos6','fielding_rating_pos7','fielding_rating_pos8','fielding_rating_pos9','fielding_ratings_catcher_arm','fielding_ratings_infield_arm','fielding_ratings_outfield_arm');

		  break;

	  case 'stats':

		  $sortList=Array('h','hr','bb','g','ab','r','d','t','rbi','k','sb','cs','avg','obp','slg','ops','wOBA',"last_name,first_name","age","lvl","porder");

		  $statArray=Array('g','ab','r','h','d','t','hr','rbi','bb','k','sb','cs','avg','obp','slg','ops','wOBA');

		  $fldArray=Array('fielding_rating_pos2','fielding_rating_pos3','fielding_rating_pos4','fielding_rating_pos5','fielding_rating_pos6','fielding_rating_pos7','fielding_rating_pos8','fielding_rating_pos9','fielding_ratings_catcher_arm','fielding_ratings_infield_arm','fielding_ratings_outfield_arm');

		  break;

	  }

	  break;

  }

  if (!in_array($sort1,$sortList)) {$sort1=$sortList[0];}

  if (!in_array($sort2,$sortList)) {$sort2=$sortList[1];}

  if (!in_array($sort3,$sortList)) {$sort3=$sortList[2];}



  # Adjust sorts if needed

  if ($view=="overall")

  {

	  $sort1=str_replace("_talent_","_overall_",$sort1);

	  $sort2=str_replace("_talent_","_overall_",$sort2);

	  $sort3=str_replace("_talent_","_overall_",$sort3);

  }

  switch ($sort1)

  {

  case 'pk': $sort1="k"; break;

  case 'pg': $sort1="g"; break;

  case 'pr': $sort1="r"; break;

  case 'pbb': $sort1="bb"; break;

  }

  switch ($sort2)

  {

  case 'pk': $sort2="k"; break;

  case 'pg': $sort2="g"; break;

  case 'pr': $sort2="r"; break;

  case 'pbb': $sort2="bb"; break;

  }

  switch ($sort3)

  {

  case 'pk': $sort3="k"; break;

  case 'pg': $sort3="g"; break;

  case 'pr': $sort3="r"; break;

  case 'pbb': $sort3="bb"; break;

  }



  ################## 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','auto','auto_list','autoRnd','draftSubscribe')";

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

  if (mysqli_num_rows($result))

  {

	  while ($row=mysqli_fetch_array($result))

	  {

		  $setting=$row['setting'];

		  $settings[$setting]=$row['value'];

	  }

  }



  ## Generate Query

  $query="";

  # Get Fielding Ratings

  switch ($who)

  {

  case 'pitchers':

  case 11:

  case 12:

  case 13:

	  break;

  default:

	  $query.="SELECT x.*";

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

	  {

		  # Get scale

		  $ratScale=get_scale($ratLbl);

		  $scale=$settings[$ratScale];

	

		  # Add to query

		  $query.=",";

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

		  $query.=" as $ratLbl";

	  }

	  $query.=" FROM players_fielding";

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

	  $query.=" as pf,(";

	  break;

  }

  # Get Primary Stats/Ratings

  $query.="SELECT px.player_id,first_name,last_name,position,role,date_of_birth,age,porder,slot";

  if (isset($statArray)) {foreach ($statArray as $key => $statLbl) {$query.=",$statLbl";}}

  if (isset($ratArray)) {foreach ($ratArray as $key => $statLbl) {$query.=",$statLbl";}}

  if (isset($runArray)) {foreach ($runArray as $key => $statLbl) {$query.=",$statLbl";}}

  $query.=" FROM (";

  switch ($view)

  {

  case 'stats':

	  $query.="SELECT player_id";

	  foreach ($statArray as $key => $statLbl) {$query.=",".stat_query($statLbl)." as $statLbl";}

	  $query.=" FROM ";

	  switch ($who)

	  {

	  case 'pitchers':

	  case 11:

	  case 12:

	  case 13:

		  $query.="players_career_pitching_stats";

		  break;

	  default:

		  $query.="players_career_batting_stats";

		  break;

	  }

	  $query.=" WHERE split_id=1";

	  if (is_numeric($statLg)) {$query.=" AND level_id=$statLg";} else {$query.=" AND level_id IN (10,11)";}

	  switch ($statView)

	  {

	  case 'thisyr':

		  $query.=" AND year=$lgyear";

		  break;

	  case 'lastyr':

		  $query.=" AND year=".($lgyear-1);

		  break;

	  }

	  $query.=" GROUP BY player_id";

	  if ((is_numeric($minPT))&&($minPT>0))

	  {

		  switch ($who)

		  {

		  case 'pitchers':

		  case 11:

		  case 12:

		  case 13:

			  $query.="HAVING ".stat_query("ip").">$minPT";

			  break;

		  default:

			  $query.="HAVING ".stat_query("pa").">$minPT";

			  break;

		  }

	  }

	  break;

  default:

	  $query.="SELECT player_id";

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

	  {

		  if ($view=='overall')

		  {

			  $ratLbl=str_replace("_pitches_talent_","_pitches_",$ratLbl);

			  $ratLbl=str_replace("_talent_","_overall_",$ratLbl);

		  }



		  # Get scale

		  $ratScale=get_scale($ratLbl);

		  $scale=$settings[$ratScale];

	

		  # Add to query

		  $query.=",";

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

		  $query.=" as $ratLbl";

	  }

	  if ((isset($runArray))&&($settings['scoutsOn']==1))

	  {

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

		  {

			  # Get scale

			  $ratScale=get_scale($ratLbl);

			  $scale=$settings[$ratScale];

	

			  # Add to query

			  $query.=",";

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

			  $query.=" as $ratLbl";

		  }

	  }

	  $query.=" FROM ";

	  switch ($who)

	  {

	  case 'pitchers':

	  case 11:

	  case 12:

	  case 13:

		  $query.="players_pitching";

		  break;

	  default:

		  $query.="players_batting";

		  break;

	  }

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

	  break;



  }

  $query.=") as ps RIGHT JOIN (";

  # Get Player Info

  $query.="SELECT first_name,last_name,position,role,date_of_birth,age";

  if ((isset($runArray))&&($settings['scoutsOn']!=1))

  {

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

	  {

		  # Get scale

		  $ratScale=get_scale($ratLbl);

		  $scale=$settings[$ratScale];

	

		  # Add to query

		  $query.=",";

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

		  $query.=" as $ratLbl";

	  }

  }

  $query.=",pp.* FROM players as p,(";

  # Get Player Pool

  switch ($listView)

  {

  case 'All':

	  $query.="SELECT dp2.* FROM (SELECT dp1.player_id,if(porder IS NULL,999999,porder) as porder,slot FROM (SELECT dp.player_id,slot 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 IN ($hmid,-999,NULL) ORDER BY porder) as dp2 GROUP BY player_id

";

	  break;

  case 'List':

	  $query.="SELECT dp1.player_id,if(porder IS NULL,999999,porder) as porder,slot FROM (SELECT dp.player_id,dp.league_id,porder,slot 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";

	  break;

  case 'NonList':

	  $query.="SELECT dp1.player_id,999999 as porder,slot FROM (SELECT dp.player_id,dp.league_id,porder,slot FROM ootp_sql_draft_pool as dp LEFT JOIN (SELECT player_id,league_id,porder FROM ootp_sql_draft_list WHERE human_manager_id=$hmid AND league_id=$lgid) as dl ON dp.player_id=dl.player_id WHERE dp.league_id=$lgid) 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 AND porder IS NULL";

	  break;

  }

  $query.=") as pp";

  # Combine with players

  $query.=" WHERE p.player_id=pp.player_id";

  if ($who=='pitchers') {$query.=" AND position=1";}

  elseif ($who>10) {$query.=" AND role=$who";}

  else {$query.=" AND position!=1";}

  $query.=") as px";

  # Combine with stats

  $query.=" ON ps.player_id=px.player_id";

  # Combine with fielding ratings

  switch ($who)

  {

  case 'pitchers':

  case 11:

  case 12:

  case 13:

	  break;

  default:

	  $query.=") as x WHERE pf.player_id=x.player_id";

	  if ((is_numeric($who))&&($who<10)) {$query.=" AND fielding_rating_pos$who>0";}

	  break;

  }



  # Apply Sorts

  $query.=" ORDER BY ";

  if ($sort1=="last_name,first_name") {$query.=$sort1;}

  else {$query.="$sort1 ".stat_sort($sort1,"",$rev);}

  if ($sort2=="last_name,first_name") {$query.=", ".$sort2;}

  else {$query.=", $sort2 ".stat_sort($sort2,"",$rev);}

  if ($sort3=="last_name,first_name") {$query.=", ".$sort3;}

  else {$query.=", $sort3 ".stat_sort($sort3,"",$rev);}

  if (($sort1!="last_name,first_name")&&($sort2!="last_name,first_name")&&($sort3!="last_name,first_name")) {$query.=",last_name,first_name";}



  ## Run Query	  

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

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

  if (mysqli_num_rows($result))

  {

	  $cnt=0;

	  $line[$cnt]=Array("//Format: Player ID", "List", "First Name", "Last Name", "Slot Demand", "Date of Birth", "Age", "Position", "Role");

	  switch ($view)

	  {

	  case 'stats':

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

		  {

			  array_push($line[$cnt],stat_text($val,2));

		  }

		  break;

	  default:

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

		  {

			  array_push($line[$cnt],stat_text($val,2));

		  }

		  switch ($who)

		  {

		  case 'pitchers':

		  case 11:

		  case 12:

		  case 13:

			  break;

		  default:

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

			  {

				  array_push($line[$cnt],stat_text($val,2));

			  }

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

			  {

				  array_push($line[$cnt],stat_text($val,2));

			  }

			  break;

		  }

		  break;

	  }



	  $cnt++;



	  while ($row=mysqli_fetch_array($result))

	  {

		  $pid=$row['player_id'];

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



		  $porder=$row['porder'];

		  if ($porder==999999) {$porder="";}

		  $fname=$row['first_name'];

		  $lname=$row['last_name'];

		  $slot=$row['slot'];

		  $dob=$row['date_of_birth'];

		  $age=$row['age'];

		  $pos=get_pos($row['position'],1);

		  $role=get_pos($row['role'],1);



		  $line[$cnt]=Array($pid,$porder,"$fname","$lname","$slot","$dob",$age,$pos,$role);



		  switch ($view)

		  {

		  case 'stats':

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

			  {

				  array_push($line[$cnt],stat_format($val,$row[$val]));

			  }

			  break;

		  default:

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

			  {

				  if ($view=='overall')

				  {

					  $val=str_replace("_pitches_talent_","_pitches_",$val);

					  $val=str_replace("_talent_","_overall_",$val);

				  }

				  array_push($line[$cnt],stat_format($val,$row[$val]));

			  }

			  switch ($who)

			  {

			  case 'pitchers':

			  case 11:

			  case 12:

			  case 13:

				  break;

			  default:

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

				  {

					  array_push($line[$cnt],stat_format($val,$row[$val]));

				  }

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

				  {

					  array_push($line[$cnt],stat_format($val,$row[$val]));

				  }

				  break;

			  }

			  break;

		  }

		  

		  $cnt++;

	  }



	  header("Content-type: text/csv");

	  header("Content-Disposition: attachment; filename=draft_listing_".$who."_".$view.".csv");

	  header("Pragma: no-cache");

	  header("Expires: 0");

	  outputCSV($line); 

  }

  else

  {

	  echo "Draft has not been configured";

  }



?>

