<?php

  include("html_functions.php");



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

  $lgid=$_SESSION['lgid'];

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

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

  $hmid=$_SESSION['user_id'];

  

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

  $title='Draft Order Import';



  page_head($title,$_SESSION['lgpath']);

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

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



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

  {

	  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 #########################

  $target = "./uploads/"; 

  $target = $target . "draft_order_$lgid.csv" ; 

  $ok=1; 

 

  //This is our size condition 

  if ($uploaded_size > 350000) 

  { 

	  echo "Your file is too large.<br/>\n"; 

	  $ok=0; 

  } 

 

  //This is our limit file type condition 

  $validTypes=Array("text/csv","text/comma-separated-values","application/vnd.ms-excel","text/plain","application/octet-stream");

  $uploaded_type=$_FILES['uploaded']['type'];

  $e=explode(".",$_FILES['uploaded']['name']);

  $lastIdx=count($e)-1;

  $ext=strtolower($e[$lastIdx]);

  if ((!in_array($uploaded_type,$validTypes))||($ext!="csv"))

  { 

	  echo "Only *.csv files are permitted, but you have uploaded a file of type \"".$uploaded_type."\" with a *.$ext extension.<br/> Please note that you may receive this error message if you have the file open while uploading.<br/>\n"; 

	  $ok=0; 

  } 

 

  //Here we check that $ok was not set to 0 by an error 

  if ($ok==0) 

  { 

	  Echo "Sorry your file was not uploaded<br/>\n"; 

  } 

  

  //If everything is ok we try to upload it 

  else 

  { 

	  if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) 

	  { 

		  // Set file to read only (with write for owner)

		  chmod($target, 0644);

		  

		  echo "The file ". basename($_FILES['uploadedfile']['name']). " has been uploaded and renamed draft_order_$lgid.csv<br/>\n"; 



		  // Read file and import to database

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



		  //open the csv file for reading

		  $handle = fopen($target, 'r');



		  $cnt=1;

		  $query="";

		  while (($data = fgetcsv($handle, 1000, ',')) !== FALSE)

		  {



			  // extract data

			  $rnd=mysqli_real_escape_string($db,$data[0]);

			  $supp=mysqli_real_escape_string($db,$data[1]);

			  $pick=mysqli_real_escape_string($db,$data[2]);

			  $tid=mysqli_real_escape_string($db,$data[4]);

			  $pid=mysqli_real_escape_string($db,$data[5]);



			  if ((is_numeric($rnd))&&(is_numeric($supp))&&(is_numeric($pick))&&(is_numeric($tid))&&(is_numeric($pid)))

			  {

				  if ($supp==1) {$sRnds[$rnd]=1;}

				  $rnds[$rnd]['fnd']=1;

				  $rnds[$rnd]['picks']=$rnds[$rnd]['picks']+1;



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

				  $query.=" VALUES ($lgid,$rnd,$supp,$pick,$tid,";

				  if ($pid==0) {$query.="NULL";} else {$query.=$pid;}

				  $query.=");";



				  $cnt++;

			  }

		  } 

		  fclose($handle);



		  if ($query!="")

		  {

			  // Clear table

			  $clearQuery="DELETE FROM amateur_draft WHERE league_id=$lgid";

			  mysqli_query($db,$clearQuery);



			  // Run queries

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

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

			  {

				  mysqli_query($db,$impQuery);

			  }



			  echo "Imported ".($cnt-1)." picks to your draft<br/> - NOTE: this import does not verify that your imported team ID's and player ID's are correct for the league.<br/>\n";



			  // Update admin settings

			  $scope=$lgid;

			  $module='Draft';



			  // Set supplemental rounds field

			  $rndList="";

			  if (isset($sRnds))

			  {

				  foreach ($sRnds as $rnd => $val)

				  {

					  $sRndList=$sRndList.";$rnd";

				  }

				  $sRndList=trim($sRndList,";");

			  }

			  $query="INSERT INTO ootp_sql_admin (scope,module,setting,value) VALUES ($scope,'$module','suppRounds','$sRndList') ON DUPLICATE KEY UPDATE value='$sRndList'";

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

			  mysqli_query($db,$query);



			  // Set draft round length field

			  $query="SELECT round,supplemental,COUNT(*) as picks FROM `amateur_draft` WHERE league_id=$lgid GROUP BY round,supplemental HAVING COUNT(*)!=(SELECT COUNT(DISTINCT team_id) FROM teams WHERE league_id=$lgid AND allstar_team=0) ORDER BY round,supplemental";

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

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

			  $pickList="";

			  if (mysqli_num_rows($result))

			  {

				  while ($row=mysqli_fetch_array($result))

				  {

					  $rnd=$row['round'];

					  $supp=$row['supplemental'];

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

					  $picks=$row['picks'];

					  $pickList.=";$rnd,$picks";

				  }

				  $pickList=trim($pickList,";");

			  }

			  $query="INSERT INTO ootp_sql_admin (scope,module,setting,value) VALUES ($scope,'$module','rndLength','$pickList') ON DUPLICATE KEY UPDATE value='$pickList'";

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

			  mysqli_query($db,$query);



			  $query="INSERT INTO ootp_sql_admin (scope,module,setting,value) VALUES ($scope,'$module','nRounds','".count($rnds)."') ON DUPLICATE KEY UPDATE value='".count($rnds)."'";

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

			  mysqli_query($db,$query);

		  }

		  else

		  {

			  echo "Invalid file contents or no players found to import.<br/>\n";

		  }



		  // Remove file from server

		  unlink($target);

		  echo "Your draft pool file has been deleted from the server<br/>\n";



		  mysqli_close($db);



	  } 

	  else 

	  { 

		  echo "Sorry, there was a problem uploading your file.<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']);









?>

