<?php

  include("html_functions.php");



  ################## CONFIGURATION CHECKS #########################

  if (!isset($_SESSION['adminpath']))

  {

	  echo "StatsLab Configuration Error:<br/>\n";

	  echo " Please edit config.txt to contain the full server path to your SQL folder<br/>\n";

	  echo " e.g. ".htmlspecialchars("ADMINPATH|/home/username/domain.com/public_html/sql/leaguename")."<br/>\n";

	  exit;

  }

  if (!file_exists($_SESSION['adminpath']."/dbopen.php"))

  {

	  echo "StatsLab Configuration Error:<br/>\n";

	  echo " Unable to find dbopen.php file for connection to MySQL database<br/>\n";

	  echo " Configured path is: ".htmlspecialchars($_SESSION['adminpath'])."<br/>\n";

	  echo " - If this path is incorrect, please correct it in config.txt<br/>\n";

	  echo " - If the path is correct, please verify that dbopen.php exists in that folder<br/>\n";

	  echo " - If the file exists in that folder, please verify folder and file permissions<br/>\n";

	  exit;

  }



  ################## DATABASE INITIALIZATION #########################

  # Check DB Connection

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

  if (mysqli_error($db))

  {

	  echo "StatsLab Configuration Error:<br/>\n";

	  echo " Unable to connect to the MySQL database<br/>\n";

	  echo " Configured path is: ".htmlspecialchars($_SESSION['adminpath'])."<br/>\n";

	  echo " dbopen.php file was found at this path<br/>\n";

	  echo " Problem is most likely one of the following:<br/>\n";

	  echo " - The host name is incorrect<br/>\n";

	  echo " - The SQL username is incorrect<br/>\n";

	  echo " - The SQL user password is incorrect<br/>\n";

	  echo " - The database name is incorrect or does not exist<br/>\n";

	  echo " - The SQL user does not have appropriate priviledges for the database specified<br/>\n";

	  exit;

  }



  # Check Admin Table

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

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

  if (!mysqli_num_rows($result)) 

  {

	  # Create Admin Table

	  $query="CREATE TABLE IF NOT EXISTS ootp_sql_admin (scope VARCHAR(20) DEFAULT 'ALL', module VARCHAR(20), setting VARCHAR(60), identifier VARCHAR(100) DEFAULT -1, value VARCHAR(255), PRIMARY KEY (scope, module, setting, identifier))";

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



	  echo "<br/>\n";

	  echo "StatsLab database is not configured, please run an initial database load.<br/>\n";

	  echo "<a href='./db_update.php'>Load Database Files</a><br/>\n";

	  exit;

  }

  else

  {

	  # Get Settings

	  $query="SELECT * FROM ootp_sql_admin WHERE scope='ALL'";

	  $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[$scope][$module][$identifier][$setting]=$value;

		  }

	  }

  }

  # Get Current Date

  $query="SELECT leagues.current_date FROM leagues LIMIT 1";

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

  $row=mysqli_fetch_array($result);

  $lgdate=$row['current_date'];



  # Check User Table

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

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

  if (!mysqli_num_rows($result)) 

  {

	  echo "StatsLab Configuration Status: INSECURE<br/>\n";

	  echo " No user table defined.  Please load the human_managers table and change the commish password.<br/>\n";

  }

  else

  {

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

	  {

		  $query="SELECT human_manager_id FROM human_managers WHERE (human_manager_id=".$_SESSION['user_id'];

		  if (isset($_SESSION['user_was_commish'])) {$query.=" OR human_manager_id=".$_SESSION['user_was_commish'];}

		  $query.=") AND is_commish=1";

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

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

		  if (!mysqli_num_rows($result))

		  {

			  $query="SELECT value FROM ootp_sql_admin WHERE module='users' AND setting='commish' AND (identifier=".$_SESSION['user_id'];

			  if (isset($_SESSION['user_was_commish'])) {$query.=" OR identifier=".$_SESSION['user_was_commish'];}

			  $query.=")";

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

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

			  if (!mysqli_num_rows($result))

			  {

				  echo "You must be a commissioner to access this page.<br/> Click <a href='./login.php'>here</a> to login.<br/>\n";

				  exit;

			  }

		  }

	  }

	  else

	  {

		  echo "You must be a commissioner to access this page.<br/> Click <a href='./login.php'>here</a> to login.<br/>\n";

		  exit;

	  }

  }



  mysqli_close($db);





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

  $title='Admin';



  page_head($title,$_SESSION['lgpath'],'','','./admin.js');

  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');

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

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

  }



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

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



  ##SQL Load Errors

  if (isset($_SESSION['loaderr']))

  {

	  echo "    <p class='error'>\n";

       	  echo "     ".$_SESSION['loaderr']."\n";

	  echo "    </p>";

       	  unset($_SESSION['loaderr']);

  }



  ##### Administrative Button Functions #####

  echo "   <div class='textbox' style='float:right;clear:right;width:420px;'>\n";

  echo "    <table border=0 cellpadding=2 cellspacing=0 style='width:100%'>\n";

  echo "     <tr class='title'><td colspan=2>Administrative Functions</td></tr>\n";

  echo "     <tr class='headline'><td class='hsc2_l' colspan=2>Load Functions</td></tr>\n";

  $scriptArray=Array('loadrun'=>'db_update.php');

  $funcArray  =Array('loadrun'=>'Load SQL Files');

  $rowCnt=0;

  foreach ($funcArray as $key => $lbl)

  {

	  $cls='s'.($rowCnt%2+1);

	  echo "     <tr class='$cls'>\n";

	  echo "      <td style='text-align:center;'>";

	  if ($lgdate!=$settings['ALL']['admin'][-1][$key]) 

	  {

		  echo "* Out of date - ";

		  if ($settings['ALL']['admin'][-1][$key]!="") {echo "Last Run: ".$settings['ALL']['admin'][-1][$key];}

		  else {echo "Not Run";}

		  echo " *";

	  }

	  elseif ($_SESSION[$key]==1) {unset($_SESSION[$key]);echo "* Run *";}

	  else {echo "* Up to date *";}

	  echo "</td>\n";

	  echo "      <td>\n";

	  echo "      <FORM ACTION=\"".$scriptArray[$key]."\" METHOD=\"post\">\n";

	  if ($_GET['debug']==1) {echo "       <input type='hidden' name='debug' value='1'>\n";}

	  echo "       <input type='submit' value='$lbl' />\n";

	  echo "      </FORM>\n";

	  echo "     </td></tr>\n";

	  $rowCnt++;

  }

  echo "     <tr class='headline'><td class='hsc2_l' colspan=2>Post-Load Functions</td></tr>\n";

  $scriptArray=Array('sctrun'=>'scout_players.php','devrun'=>'run_development.php','pfrun'=>'parkFactors.php'       ,'slupdrun'=>'statslab_update.php');

  $funcArray  =Array('sctrun'=>'Scout Players'    ,'devrun'=>'Update Development'        ,'pfrun'=>'Calculate Park Factors','slupdrun'=>'Send Update');

  $rowCnt=0;

  foreach ($funcArray as $key => $lbl)

  {

	  if (($settings['ALL']['admin'][-1]['scoutsOn']!=1)&&($key=='sctrun')) {continue;}

	  if (($settings['ALL']['admin'][-1]['devEnable']!=1)&&($key=='devrun')) {continue;}

		  

	  $cls='s'.($rowCnt%2+1);

	  echo "     <tr class='$cls'>\n";

	  echo "      <td style='text-align:center;'>";

	  if ($key=='slupdrun') 

	  {

		  echo "\n";

		  echo "      <FORM ACTION=\"".$scriptArray[$key]."\" METHOD=\"post\">\n";

		  echo "       <table>\n";

		  echo "        <tr>\n";

		  echo "         <td><input type='checkbox' value=1 name='sendToAll'></td>\n";

		  echo "         <td>Send to all (<i>else, only subscribed</i>)</td>\n";

		  echo "        </tr>\n";

		  echo "       </table>\n";

		  echo "      ";

	  }

	  elseif ($lgdate!=$settings['ALL']['admin'][-1][$key]) 

	  {

		  echo "* Out of date - ";

		  if ($settings['ALL']['admin'][-1][$key]!="") {echo "Last Run: ".$settings['ALL']['admin'][-1][$key];}

		  else {echo "Not Run";}

		  echo " *";

	  }

	  elseif ($_SESSION[$key]==1) {unset($_SESSION[$key]);echo "* Run *";}

	  else {echo "* Up to date *";}

	  echo "</td>\n";

	  echo "      <td>\n";

	  if ($key!='slupdrun') {echo "      <FORM ACTION=\"".$scriptArray[$key]."\" METHOD=\"post\">\n";}

	  if ($_GET['debug']==1) {echo "       <input type='hidden' name='debug' value='1'>\n";}

	  echo "       <input type='submit' value='$lbl' />\n";

	  echo "      </FORM>\n";

	  echo "     </td></tr>\n";

	  $rowCnt++;

  }

  echo "    </table>\n";

  echo "   </div>\n";



  ##### Admin Settings #####

  echo "   <div class='textbox' style='float:left;clear:left;width:500px;'>\n";

  echo "   <form action=\"save_settings.php\" method=\"post\">\n";

  echo "    <input type='hidden' name='module' value='admin'>\n";

  if ($_GET['debug']==1) {echo "    <input type='hidden' name='debug' value='1'>\n";}

  echo "    <table cellpadding=2 cellspacing=0 width='100%'>";

  echo "     <tr class='title'><td colspan=2>General Settings</td></tr>\n";



  # Server Settings

  echo "     <TR class='headline'><TD colspan=2>Server Settings</TD></TR>\n";

  //echo "     <TR><TD>HTML Root:</TD><TD align='left'><INPUT type=\"text\" size=40 name=\"HTMLRoot\" value=\"".$settings['ALL']['admin'][-1]['HTMLRoot']."\"></TD></TR>\n";

  echo "     <TR><TD>HTML Path:</TD><TD align='left'><INPUT type=\"text\" size=40 name=\"HTMLPath\" value=\"".($settings['ALL']['admin'][-1]['HTMLPath']==""?"/reports/news/html":$settings['ALL']['admin'][-1]['HTMLPath'])."\"></TD></TR>\n";

  echo "     <TR><TD>Server URL:</TD><TD align='left'><INPUT type=\"text\" size=40 name=\"ServerURL\" value=\"".($settings['ALL']['admin'][-1]['ServerURL']==""?"http://www.league-site.com":$settings['ALL']['admin'][-1]['ServerURL'])."\"></TD></TR>\n";

  $e=explode('/admin.php',$_SERVER['SCRIPT_URI']);

  echo "     <TR><TD>StatsLab Path:</TD><TD align='left'><INPUT type=\"text\" size=40 name=\"StatsLabPath\" value=\"".($settings['ALL']['admin'][-1]['StatsLabPath']==""?$e[0]:$settings['ALL']['admin'][-1]['StatsLabPath'])."\"></TD></TR>\n";

  $phpver=phpversion();

  $phpver=$phpver[0];

  if ($phpver>4)

  {

	  echo "     <TR><TD>Time Zone For Time Display:</TD><TD>";

	  echo "<SELECT name='timezone'>";

       	  echo "<OPTION name='not_selected'>Use Server Setting</OPTION>";

	  $tzones=array('14'=>'Pacific/Kiritimati','12'=>'Pacific/Auckland','11'=>'Pacific/Noumea','10'=>'Australia/Sydney','9'=>'Asia/Tokyo','8'=>'Asia/Shanghai','7'=>'Asia/Bangkok','6'=>'Asia/Bishkek','5.5'=>'Asia/Calcutta','5'=>'Asia/Tashkent','4.5'=>'Asia/Kabul','4'=>'Asia/Dubai','3'=>'Europe/Moscow','2'=>'Europe/Athens','1'=>'Europe/Amsterdam','0'=>'Europe/London','-3'=>'America/Sao_Paolo','-4'=>'America/Halifax','-5'=>'America/New_York','-6'=>'America/Chicago','-7'=>'America/Denver','-8'=>'America/Los_Angeles','-9'=>'America/Anchorage','-10'=>'Pacific/Honolulu','-11'=>'Pacific/Apia');

	  $zoneSetting=$settings['ALL']['admin'][-1]['timezone'];

       	  foreach ($tzones as $key => $name)

	  {

	    	  echo "<OPTION value='$name'";

		  if ($name==$zoneSetting) {echo " selected";}

	    	  echo ">$name (UTC";

		  if ($key>=0) {echo "+";}

	    	  echo "$key)</OPTION>";

	  }

       	  echo "</SELECT>";

	  echo "</TD></TR>\n";

  }

  echo "     <TR><TD>Require Login For Access:</TD><TD align='left'><INPUT type=\"checkbox\" name=\"requireLogin\" value=1";

  if ($settings['ALL']['admin'][-1]['requireLogin']==1) {echo " checked='yes'";}

  echo "></TD></TR>\n";

  echo "     <TR><TD>Allow Non-GM's To Login:</TD><TD align='left'><INPUT type=\"checkbox\" name=\"showAllUsers\" value=1";

  if ($settings['ALL']['admin'][-1]['showAllUsers']==1) {echo " checked='yes'";}

  echo "></TD></TR>\n";

  echo "     <TR><TD>Previous SQL Load (YYYY-MM-DD):</TD><TD align='right'><INPUT type=\"text\" size=20 maxchar=3 disabled='disabled' name='LastDate' value=\"".$settings['ALL']['admin'][-1]['LastDate']."\"></TD></TR>\n";

  echo "     <TR><TD>Calculated Sim Length:</TD><TD align='right'>".$settings['ALL']['admin'][-1]['calcLength']." days</TD><input type='hidden' name='calcLength' value=\"".$settings['ALL']['admin'][-1]['calcLength']."\" /></TR>\n";

  echo "     <TR><TD>Sim Length Adjustment (Days):</TD><TD align='left'><INPUT type=\"text\" size=40 name=\"simLenAdj\" value=\"".($settings['ALL']['admin'][-1]['simLenAdj']==""?10:$settings['ALL']['admin'][-1]['simLenAdj'])."\"></TD></TR>\n";



  # Export Tracker

  echo "     <TR class='headline'><TD colspan=2>Export Tracker Settings</TD></TR>\n";

  echo "     <TR><TD>Enable Export Tracker:</TD><TD align='left'><INPUT type=\"checkbox\" name=\"expEnable\" value=1";

  if ($settings['ALL']['admin'][-1]['expEnable']==1) {echo " checked='yes'";}

  echo "></TD></TR>\n";

  echo "     <TR><TD>League File Name:</TD><TD align='left'><INPUT type=\"text\" size=40 name=\"expfilenm\" value=\"".$settings['ALL']['admin'][-1]['expfilenm']."\"></TD></TR>\n";

  echo "     <TR><TD>League File Path:</TD><TD align='left'><INPUT type=\"text\" size=40 name=\"lgfile\" value=\"".($settings['ALL']['admin'][-1]['lgfile']==""?"http://www.league-site.com/league_file":$settings['ALL']['admin'][-1]['lgfile'])."\"></TD></TR>\n";

  echo "     <TR><TD>Export File Path:</TD><TD align='left'><INPUT type=\"text\" size=40 name=\"expfile\" value=\"".($settings['ALL']['admin'][-1]['expfile']==""?"http://www.league-site.com/exports":$settings['ALL']['admin'][-1]['expfile'])."\"></TD></TR>\n";

  echo "     <TR><TD>Files Are Renamed On Import:</TD><TD align='left'><INPUT type=\"checkbox\" name=\"renameFiles\" value=1";

  if ($settings['ALL']['admin'][-1]['renameFiles']==1) {echo " checked='yes'";}

  echo "></TD></TR>\n";



  # OOTP Settings

  echo "     <TR class='headline'><TD colspan=2>OOTP Settings</TD></TR>\n";

  echo "     <TR><TD>Primary League:</TD><TD>";

  echo "<SELECT name='priLgID'>";

  $query="SELECT league_id,name,abbr,IF(parent_league_id=0,league_id,parent_league_id) as parent_league_id,league_level FROM leagues WHERE 1 ORDER BY parent_league_id,league_level";

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

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

  if (mysqli_num_rows($result))

  {

		  while ($row=mysqli_fetch_array($result))

		  {

		  	$lgID=$row['league_id'];

		  	echo " <OPTION value='$lgID'";

		  	if ($lgID==$settings['ALL']['admin'][-1]['priLgID']) {echo " selected";}

		  	echo ">".$row['name']."</OPTION>";

		  	

		  }

  }

  else {echo "<OPTION value=0>ERROR: Load leagues table</OPTION>";}

  echo "</SELECT>";

  //echo "<INPUT type=\"text\" size=20 maxchar=3 name=\"priLgID\" value=\"".$settings['ALL']['admin'][-1]['priLgID']."\">";

  echo "</TD></TR>\n";

  $scale=array('Hidden','1-5','2-8','1-10','1-20','20-80','1-100');

  echo "     <TR><TD>Financials On:</TD><TD align='left'><INPUT type=\"checkbox\" name=\"finEnable\" value=1";

  if ($settings['ALL']['admin'][-1]['finEnable']==1) {echo " checked='yes'";}

  echo "></TD></TR>\n";

  echo "     <TR><TD>Ratings Pages:</TD><TD align='left'><INPUT type=\"checkbox\" name=\"ratEnable\" value=1";

  if ($settings['ALL']['admin'][-1]['ratEnable']==1) {echo " checked='yes'";}

  echo "></TD></TR>\n";

  echo "     <TR><TD>Actual Ratings Scale:</TD><TD>";

  echo "<SELECT name='Ratings'>";

  for ($i=0;$i<count($scale);$i++)

  {

	  echo "<OPTION value='".$scale[$i]."'";

	  if ($scale[$i]==$settings['ALL']['admin'][-1]['Ratings']) {echo " selected";}

	  echo ">".$scale[$i]."</OPTION>";

  }

  echo "</SELECT>";

  echo "</TD></TR>\n";

  echo "     <TR><TD>Potential Ratings Scale:</TD><TD>";

  echo "<SELECT name='Talents'>";

  for ($i=0;$i<count($scale);$i++)

  {

	  echo "<OPTION value='".$scale[$i]."'";

      	  if ($scale[$i]==$settings['ALL']['admin'][-1]['Talents']) {echo " selected";}

	  echo ">".$scale[$i]."</OPTION>";

  }

  echo "</SELECT>";

  echo "</TD></TR>\n";

  echo "     <TR><TD>Other Ratings Scale:</TD><TD>";

  echo "<SELECT name='Others'>";

  for ($i=0;$i<count($scale);$i++)

  {

	  echo "<OPTION value='".$scale[$i]."'";

       	  if ($scale[$i]==$settings['ALL']['admin'][-1]['Others']) {echo " selected";}

	  echo ">".$scale[$i]."</OPTION>";

  }

  echo "</SELECT>";

  echo "</TD></TR>\n";



  # Global StatsLab Settings

  echo "     <TR class='headline'><TD colspan=2>Global StatsLab Settings</TD></TR>\n";

  echo "     <TR><TD>Use StatsLab Scout for Ratings:</TD><TD align='left'><INPUT type=\"checkbox\" name=\"scoutsOn\" value=1";

  if ($settings['ALL']['admin'][-1]['scoutsOn']==1) {echo " checked='yes'";}

  echo "></TD></TR>\n";

  echo "     <TR><TD>Development Tracker:</TD><TD align='left'><INPUT type=\"checkbox\" name=\"devEnable\" value=1";

  if ($settings['ALL']['admin'][-1]['devEnable']==1) {echo " checked='yes'";}

  echo "></TD></TR>\n";

  echo "     <TR><TD title='For development tracker'>Track Lefty/Righty Split Ratings:</TD><TD align='left'><INPUT type=\"checkbox\" name=\"trackSplits\" value=1";

  if ($settings['ALL']['admin'][-1]['trackSplits']==1) {echo " checked='yes'";}

  echo "></TD></TR>\n";

  if ($settings['ALL']['admin'][-1]['scoutsOn']==1)

  {

	  echo "     <TR><TD>Last Scouted On (YYYY-MM-DD):</TD><TD align='right'><INPUT type=\"text\" size=20 maxchar=3 disabled='disabled' value=\"".$settings['ALL']['admin'][-1]['sctrun']."\"></TD></TR>\n";

  }

  echo "     <TR><TD>Only Allow Players To Be Added To Trade Block In Game:</TD><TD align='left'><INPUT type=\"checkbox\" name=\"addDisable\" value=1";

  if ($settings['ALL']['admin'][-1]['addDisable']==1) {echo " checked='yes'";}

  echo "></TD></TR>\n";



  # Email Settings

  echo "     <TR class='headline'><TD colspan=2>Email Configuration</TD></TR>\n";

  echo "     <TR><TD title='Turns on/off sending emails using the Send Update button'>Send Update Emails:</TD><TD align='left'><INPUT type=\"checkbox\" name=\"sendUpdateEmails\" value=1";

  if ($settings['ALL']['admin'][-1]['sendUpdateEmails']==1) {echo " checked='yes'";}

  echo "></TD></TR>\n";

  echo "     <TR><TD>Email From Address:</TD><TD align='left'><INPUT type=\"text\" size=40 name=\"emailFrom\" value=\"".$settings['ALL']['admin'][-1]['emailFrom']."\"></TD></TR>\n";

  echo "     <TR><TD>Email Reply-To Address(es):</TD><TD align='left'><INPUT type=\"text\" size=40 name=\"emailReplyTo\" value=\"".$settings['ALL']['admin'][-1]['emailReplyTo']."\"></TD></TR>\n";

  echo "     <TR><TD colspan=2 class='italic'>NOTE: The default reply-to address (if left blank) will be the OOTP commissioner's address, but the email from address (top setting) needs to contain the website's domain.  They can be the same, and if the from field is left blank, the commissioner's address will be used.<br/><br/>If you have more than one commish account, enter the appropriate from address, even if it matches one of the commish emails.</TD></TR>\n";



  # Slack Settings

  echo "     <TR class='headline'><TD colspan=2>Slack Configuration</TD></TR>\n";

  echo "     <TR><TD title='Turn Slack Integration on/off'>Enable Slack Integrations:</TD><TD align='left'><INPUT type=\"checkbox\" name=\"slackEnable\" value=1";

  if ($settings['ALL']['admin'][-1]['slackEnable']==1) {echo " checked='yes'";}

  echo "></TD></TR>\n";

  echo "     <TR><TD title='Turns on/off sending updates to Slack using the Send Update button'>Send Update Slack:</TD><TD align='left'><INPUT type=\"checkbox\" name=\"sendUpdateSlack\" value=1";

  if ($settings['ALL']['admin'][-1]['sendUpdateSlack']==1) {echo " checked='yes'";}

  echo "></TD></TR>\n";

  echo "     <TR><TD>Slack Service URL:</TD><TD align='left'><INPUT type=\"text\" size=40 name=\"slackServiceURL\" value=\"".$settings['ALL']['admin'][-1]['slackServiceURL']."\"></TD></TR>\n";

  echo "     <TR><TD>Slack Username:</TD><TD align='left'><INPUT type=\"text\" size=40 name=\"slackUser\" value=\"".$settings['ALL']['admin'][-1]['slackUser']."\"></TD></TR>\n";

  echo "     <TR><TD>Slack Icon:</TD><TD align='left'><INPUT type=\"text\" size=40 name=\"slackIcon\" value=\"".$settings['ALL']['admin'][-1]['slackIcon']."\"></TD></TR>\n";

  echo "     <TR><TD>Default Slack Channel:</TD><TD align='left'><INPUT type=\"text\" size=40 name=\"slackDefChannel\" value=\"".$settings['ALL']['admin'][-1]['slackDefChannel']."\"></TD></TR>\n";

  echo "     <TR><TD>Trade Block Slack Channel:</TD><TD align='left'><INPUT type=\"text\" size=40 name=\"slackTradeChannel\" value=\"".$settings['ALL']['admin'][-1]['slackTradeChannel']."\"></TD></TR>\n";



  # Close Admin Settings

  echo "     <tr><td></td><td><input type=\"submit\" value=\"Save\"></td></tr>\n";

  echo "    </table>";

  echo "   </form>\n";

  echo "   </div>\n";



  ##### User Functions #####



  # Get Leagues

  $leagues[9999]="Unaffiliated";

  $query="SELECT league_id,name FROM leagues";

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

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

  while ($row=mysqli_fetch_array($result))

  {

	  $league_id=$row['league_id'];

	  $leagues[$league_id]=$row['name'];

  }



  # Get Users

  $query="SELECT hm.*,t.abbr,t.name,t.nickname FROM teams as t RIGHT JOIN (SELECT human_manager_id,is_commish,first_name,last_name,team_id,if(league_id=0,9999,league_id) as league_id FROM human_managers";

  //if ($settings['ALL']['admin'][-1]['showAllUsers']!=1) {$query.=" WHERE is_commish=1 OR team_id>0 OR organization_id>0";}

  $query.=") as hm ON t.team_id=hm.team_id ORDER BY league_id,last_name,first_name";

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

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

  if (mysqli_num_rows($result)>0)

  {

	  while ($row=mysqli_fetch_array($result))

	  {

		  if ($row['team_id']>0) {$tname=$row['abbr'];}

		  elseif ($row['is_commish']==1) {$tname="CMSH";}

		  else {$tname="N/A";}



		  $hmid=$row['human_manager_id'];

		  $users[$hmid]['name']=$row['first_name']." ".$row['last_name'];

		  $users[$hmid]['tid']=$row['team_id'];

		  $users[$hmid]['tabbr']=$row['abbr'];

		  $users[$hmid]['tname']=$tname;

		  $users[$hmid]['is_commish']=$row['is_commish'];

		  $users[$hmid]['lgid']=$row['league_id'];

	  }



	

	  # Display

	  echo "   <div class='textbox' style='float:right;clear:right;width:420px;'>\n";

	  echo "    <table cellpadding=2 cellspacing=0 style='width:100%'>";

	  echo "     <TR class='title'><TD colspan=2>User Functions</TD></TR>\n";

	  // Login as

	  echo "     <tr class='s2_l'><td colspan=2>Login As:</td>\n";

	  echo "     <tr class='s2'>\n";

	  echo "      <td>\n";

	  echo "       <form method='post' onsubmit=\"return checkSelect(document.getElementById('loginAsUser'),document.getElementById('loginPass'));\" action='login.php'>\n";

	  echo "        <input type='hidden' name='login' value='loginAsUser'>\n";

	  echo "        <input type='hidden' name='actAs' value='1'>\n";

	  echo "        <select name='username' id='loginAsUser'>\n";

	  echo "         <option value=0>Please Select User</option>\n";

	  $lastLgID=-1;

	  foreach ($users as $hmid => $val)

	  {

  		  $league_id=$users[$hmid]['lgid'];

		  if ($lastLgID!=$league_id) {echo "      <optgroup label='".$leagues[$league_id]."'>\n";}

		

		  echo "         <option value='$hmid'>";

		  echo $users[$hmid]['name']." (".$users[$hmid]['tname'].")";

		  echo "</option>\n";



		  $lastLgID=$league_id;

	  }

	  echo "        </select>\n";

	  echo "       </td>\n";

	  echo "       <td>\n";

	  echo "        <input type='submit' value='Go'>\n";

	  echo "       </form>\n";

	  echo "      </td></tr>\n";

	  // Reset Password

	  if (isset($_SESSION['passReset']))

	  {

		  $hmid=$_SESSION['passReset'];

		  echo "     <tr class='s1_l'><td colspan=2><span style='color:#990000;'>-- Password Reset for ".$users[$hmid]['name']." --</span></td>\n";

		  unset($_SESSION['passReset']);

	  }

	  echo "     <tr class='s1_l'><td colspan=2>Reset Password For:</td>\n";

	  echo "     <tr class='s1'>\n";

	  echo "      <td>\n";

	  echo "       <form method='post' onsubmit=\"return checkSelect(document.getElementById('chgPassUser'),document.getElementById('oldpass'));\" action='admin_login_functions.php'>\n";

	  echo "        <input type='hidden' name='formName' value='passReset'>\n";

	  echo "        <select name='user_id' id='chgPassUser'>\n";

	  echo "         <option value=0>Please Select User</option>\n";

	  $lastLgID=-1;

	  foreach ($users as $hmid => $val)

	  {

  		  $league_id=$users[$hmid]['lgid'];

		  if ($lastLgID!=$league_id) {echo "      <optgroup label='".$leagues[$league_id]."'>\n";}

		

		  echo "         <option value='$hmid'>";

		  echo $users[$hmid]['name']." (".$users[$hmid]['tname'].")";

		  echo "</option>\n";



		  $lastLgID=$league_id;

	  }

	  echo "        </select>\n";

	  echo "       </td>\n";

	  echo "       <td>\n";

	  echo "        <input type='submit' value='Go'>\n";

	  echo "       </form>\n";

	  echo "      </td></tr>\n";

	  // Grant commish access

	  $slCmshQuery="SELECT identifier FROM ootp_sql_admin WHERE module='users' AND setting='commish' AND value=1";

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

	  $slCmshResult=mysqli_query($db,$slCmshQuery);

	  if (mysqli_num_rows($slCmshResult))

	  {

		  while ($slCmshRow=mysqli_fetch_array($slCmshResult))

		  {

			  $hmid=$slCmshRow['identifier'];

			  $users[$hmid]['sl_commish']=1;

			  $fndSLCommish=1;

		  }

	  }

	  if (isset($_SESSION['accessGranted']))

	  {

		  $hmid=$_SESSION['accessGranted'];

		  echo "     <tr class='s2_l'><td colspan=2><span style='color:#990000;'>-- Commish Access Granted to ".$users[$hmid]['name']." --</span></td>\n";

		  unset($_SESSION['accessGranted']);

	  }

	  echo "     <tr class='s2_l'><td colspan=2>Grant StatsLab Commish Access To:</td></tr>\n";

	  echo "     <tr class='s2'>\n";

	  echo "      <td>\n";

	  echo "       <form method='post' action='admin_login_functions.php'>\n";

	  echo "        <input type='hidden' name='formName' value='grantCommish'>\n";

	  echo "        <select name='user_id' id='commishUser'>\n";

	  echo "         <option value=0>Please Select User</option>\n";

	  $lastLgID=-1;

	  foreach ($users as $hmid => $val)

	  {

		  if (($users[$hmid]['is_commish']==1)||($users[$hmid]['sl_commish']==1)) {continue;}  //Can't grant to OOTP Commish

	

		  $league_id=$users[$hmid]['lgid'];

		  if ($lastLgID!=$league_id) {echo "      <optgroup label='".$leagues[$league_id]."'>\n";}

		

		  echo "         <option value='$hmid'>";

		  echo $users[$hmid]['name']." (".$users[$hmid]['tname'].")";

		  echo "</option>\n";



		  $lastLgID=$league_id;

	  }

	  echo "        </select>\n";

	  echo "       </td>\n";

	  echo "       <td>\n";

	  echo "        <input type='submit' value='Go'>\n";

	  echo "       </form>\n";

	  echo "      </td></tr>\n";

	  if (isset($_SESSION['accessRemoved']))

	  {

		  $hmid=$_SESSION['accessRemoved'];

		  echo "     <tr class='s1_l'><td colspan=2><span style='color:#990000;'>-- Commish Access Removed from ".$users[$hmid]['name']." --</span></td>\n";

		  unset($_SESSION['accessRemoved']);

	  }

	  // Remove commish access

	  if ($fndSLCommish==1)

	  {

		  echo "     <tr class='s1_l'><td colspan=2>Remove StatsLab Commish Access For:</td></tr>\n";

		  echo "     <tr class='s1'>\n";

		  echo "      <td>\n";

		  echo "       <form method='post' action='admin_login_functions.php'>\n";

		  echo "        <input type='hidden' name='formName' value='denyCommish'>\n";

		  echo "        <select name='user_id' id='commishUser'>\n";

		  echo "         <option value=0>Please Select User</option>\n";

		  $lastLgID=-1;

		  foreach ($users as $hmid => $val)

		  {

			  if ($users[$hmid]['sl_commish']!=1) {continue;}



			  $league_id=$users[$hmid]['lgid'];

			  if ($lastLgID!=$league_id) {echo "      <optgroup label='".$leagues[$league_id]."'>\n";}



				  echo "         <option value='$hmid'>";

			  echo $users[$hmid]['name']." (".$users[$hmid]['tname'].")";

			  echo "</option>\n";



			  $lastLgID=$league_id;

		  }

		  echo "        </select>\n";

		  echo "       </td>\n";

		  echo "       <td>\n";

		  echo "        <input type='submit' value='Go'>\n";

		  echo "       </form>\n";

		  echo "      </td></tr>\n";

	  }

	  if (isset($_SESSION['adminerror']))

	  {

		  echo "      <tr><td>&nbsp;</td><td colspan=2>";

		  echo $_SESSION['adminerror'];

		  echo "</td></tr>\n";

		  unset($_SESSION['adminerror']);

	  }



	  echo "    </table>\n";

	  echo "   </div>\n";

	

	  ##### Last Login Table #####

	  $query="SELECT identifier,value FROM ootp_sql_admin WHERE setting='Last Login';";

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

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

	  if (mysqli_num_rows($result)>0)

	  {

		  while ($row=mysqli_fetch_array($result))

		  {

			  $hmid=$row['identifier'];

			  $users[$hmid]['logintime']=$row['value'];

		  }

	  }



	  echo "   <div class='textbox' style='float:right;clear:right;width:420px;'>\n";

	  echo "    <table cellpadding=2 cellspacing=0 border=0 style='width:100%'>\n";

	  echo "     <tr class='title'><td colspan=3>GM Login History</td></tr>\n";

	  echo "     <tr class='headline'><td class='hsc2_l'>GM</td><td class='hsc2_l'>Team</td><td class='hsc2'>Last Accessed</td></tr>\n";

	  $cnt=0;

	  $lastLgID=-1;

	  foreach ($users as $hmid => $val)

	  {

		  $league_id=$users[$hmid]['lgid'];

		  $tid=$users[$hmid]['tid'];



		  if ($lastLgID!=$league_id) {echo "     <tr class='headline'><td colspan=3 style='font-weight:bold;font-style:italic;'>".$leagues[$league_id]."</td></tr>\n";}



		  $cls='s'.($cnt%2+1);

	    	  echo "     <tr class='$cls'>";

		  echo "<td class='".$cls."_l' sorttable_customkey='".$users[$hmid]['sortname']."'>".$users[$hmid]['name']."</td>";

	    	  if ($tid==0)

		  {

		 	  if ($row['is_commish']==1) {$tname='Commissioner';} else {$tname='No team';}

		  }

	   	  else {$tname="<a href='$lgpath/teams/team_$tid.html' title='".$users[$hmid]['tname']."'>".$users[$hmid]['tabbr']."</a>";}

		  echo "<td class='".$cls."_l'>$tname</td>";

		  echo "<td";

		  if (isset($users[$hmid]['logintime'])) 

	   	  {

			  $loginTime=$users[$hmid]['logintime'];

		 	  echo " sorttable_customkey='$loginTime'>".date("D M j, Y H:i",$loginTime);

		  }

	   	  else {echo " sorttable_customkey='0'>Never";}

		  echo "</td></tr>\n";



		  $lastLgID=$league_id;

		  $cnt++;

	  }

	  echo "     <tr><td colspan=3 style='text-align:right;'><a href='./ip_report.php'>IP Address Report</a></td></tr>\n";

       	  echo "    </table>\n";

	  echo "   </div>\n";

  }



  mysqli_close($db);



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

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

  page_foot($_SESSION['lgpath']);



?>

