<?php
session_start();
include('html_functions.php');
check_cookie();
include($_SESSION['adminpath']."/dbopen.php");

if ($_GET['clear_votes']==1)
 {
   $lgid=$_GET['lgid'];
   $year=$_GET['year'];
   $hmid=$_GET['human_manager_id'];
   if ($year=="") {$query="DELETE FROM awards_vote WHERE league_id=$lgid AND award_id=100;";}
    elseif ($hmid=="")
    {
      $query="DELETE FROM awards_vote WHERE league_id=$lgid AND year=$year AND award_id=100 AND human_manager_id!=-1;";
    }
    else
    {
      $query="DELETE FROM awards_vote WHERE league_id=$lgid AND year=$year AND human_manager_id=$hmid AND award_id=100;";
    }
   mysqli_query($db,$query);
   header("Location: ./hofAdmin.php");
   exit;
 }

$lgid=$_POST['league_id'];
$ballot=$_POST['ballot'];
$year=$_POST['year'];
$hmid=$_SESSION['user_id'];

  # Check if awards vote table exists
  $query="SHOW TABLES LIKE 'awards_vote';";
  $result=mysqli_query($db,$query);
  if (!mysqli_num_rows($result))
  {
	  ##### Initialize Table #####
	  $query="CREATE TABLE IF NOT EXISTS awards_vote (player_id INT, league_id INT, sub_league_id INT, year SMALLINT, human_manager_id INT, award_id SMALLINT, position SMALLINT, vote INT DEFAULT 0, PRIMARY KEY (player_id, league_id, sub_league_id, year, human_manager_id, award_id));";
	  $result=mysqli_query($db,$query);
  }

  # Check Admin Table
  $module='HOF';
  $query="SHOW TABLES LIKE 'ootp_sql_admin';";
  $result=mysqli_query($db,$query);
  if (mysqli_num_rows($result)) 
  {
	  # Get Settings
	  $query="SELECT setting,value FROM ootp_sql_admin WHERE scope IN ('ALL',$lgid) AND module='$module' AND setting='numVotes'";
	  if ($_GET['showq']==1) {echo "$query<br/>\n";}
	  $result=mysqli_query($db,$query);
	  if (mysqli_num_rows($result))
	  {
		  while ($row=mysqli_fetch_array($result))
		  {
			  $field=$row['setting'];
		 	  $val=$row['value'];
			  $val=stripslashes($val);
		 	  switch ($field)
			  {
			  case 'numVotes'  : $numVotes=$val;   break;
			  }
		  }
      	  }
  }
  if ($numVotes=="") {$numVotes=10;}
  if ($numVotes<1) {$numVotes=10;}

##### Create Update Statements #####
$hmid=$_SESSION['user_id'];
$pids=explode(",",$ballot);
$tot=min($numVotes,count($pids));
for ($i=0;$i<$tot;$i++)
 {
   $pid=$pids[$i];
   $insQuery="INSERT INTO awards_vote (player_id,league_id,sub_league_id,human_manager_id,year,award_id,vote) VALUES ($pid,$lgid,0,$hmid,$year,100,1);";
   $updText.=$insQuery."\n";
 }

##### Write Votes to File #####
if ($updText!="")
 {
   $updText=trim($updText,",");
   $updText=trim($updText);
   $e=explode("\n",$updText);
   foreach ($e as $key => $query)
    {
      mysqli_query($db,$query);
      $err=mysqli_error($db);
      if ($err!="") {echo $err."<br />\n";}
    }
 }
 
header("Location: ./hall_of_fame_vote.php?page=results");

?>
