<?php
error_reporting(E_ALL);
ini_set('display_errors','On');
//
// Copyright (c) 2021 RealTime Fantasy Sports, Inc.
//
require_once("autoload.php");
require_once("../conf/basketball.cfg");
require_once("basketball-functions.php");

const GamesPlayed = -4;

$POS = ScrubInteger('POS');
$TEAM = ScrubInteger('TEAM');
$CSV = ScrubBoolean('CSV');

list($rtuser, $theme, $league) = BasketballPresentation::Initialize();
$theme->AddJS("jquery/jquery.tablesorter-2.31.3.min.js"); // https://github.com/Mottie/tablesorter
$theme->ResponsiveHeader($rtuser);
$presentation = new BasketballPresentation($league);
$team = $globals->team;

$prefs = $globals->cache_basketball->GetPrefs($rtuser,"player-eligibility");
if (!array_key_exists('TEAM', $_REQUEST)) $TEAM = (array_key_exists("team",$prefs) ? (int)$prefs["team"] : 0);
if ($TEAM > 0 && !$league->IsTeam($TEAM)) $TEAM = 0;

$globals->cache_basketball->SetPrefs($rtuser,"player-eligibility", "team", $TEAM);

?>
<style>
.table-eligible tbody tr td { text-align: center; }
.table-eligible tbody tr td:nth-child(1) { text-align: left; }
.table-eligible tbody tr td:nth-child(5) { text-align: left; }
.pos-select.h2 { margin:20px 0px; }
.pos-select.h2 > ul { padding-left: 0px; margin-bottom: 0px; }
.pos-select.h2 > ul > li { float:left; list-style: none; padding: 1px 6px; }
.pos-select.h2 .selected { text-decoration: underline; }
.btn-filters select { width: auto; }
</style>
<script>
$(document).ready(function (){
   $('select[name="TEAM"]').change(function(){ $('#FILTER').submit();});
   $('.table-eligible table').tablesorter({ sortInitialOrder: "asc", sortList: [[5,1]]});
   $('[data-toggle="tooltip"]').tooltip();
});
</script>
<?

$league->CheckEligibility();

if (!$POS) {
   if (is_array($league->position_groups) && count($league->position_groups)) 
      $POS = current($league->position_groups)->group_id;
   else
      $theme->ModalMessage(Theme::HdrInfo, "Your league does not have any position eligibility groups defined.");
}

$sql = "select * from Eligible_Players as EP,Basketball_Player_View as BPV where EP.Player_Id = BPV.Player_Id and BPV.deleted = 0 ";
if ($league->use_game_eligible_players)
	$sql .= "and EP.Game_Id = " . (int)$league->game_id;
else
	$sql .= "and EP.League_Id = " . (int)$league->league_id;

//
//  Get Eligibility Groups
//
$players = array();
$result = $globals->db->Query($sql. " order by BPV.Last_Name,BPV.First_Name,BPV.Player_Id");
while ($row = $globals->db->FetchRowObject($result)) {
	if (array_key_exists($row->Player_Id, $players)) continue;
   $groups = $league->GetEligiblePositionGroups($row->Player_Id, ScrubBoolean('CLEAR')); // ,(strlen($CLEAR_CACHE)>0?true:false));
   if (!in_array($POS, $groups)) continue;
//maybe if (-3 == $TEAM && count($groups) < 3) continue; // primary plus "U" is not multiple
   $players[$row->Player_Id] = $groups;
}
$globals->db->Free($result);

$league->GetTeams();
list($status, $owned, $owners) = $league->GetPlayerStatus($players);

if ($league->UsingPFAs())
	$league->GetProtectedFreeAgents( League::PFANextWaiverWire == $league->protected_free_agents ? League::PFALockUntilDate : NULL );

if (!$league->is_commissioner && !$league->is_guest)
   $watchlist = $team->GetWatchList();
else
   $watchlist = array();

$season = NBA::Season;
if ($league->fantasy_week <= League::FirstFantasyWeek) $season--;

$percent = BasketballPlayer::GetOwned($league->player_pool);

//
//  Season and Filter Options
//
echo '<div class="row">';
echo '<div class="col-sm-4 hidden-xs hidden-tn"><h1>' . NBA::Season . ' Eligibility</h1></div>';

echo '<div class="col-sm-8 col-tn-12 text-right">';
echo '<form id="FILTER" class="form-inline" role="form" action="' . BasketballPresentation::URL('report-eligibility.php') . '" method="GET">';
$presentation->HiddenIDs();
echo '<input type="hidden" name="POS" value="' . $POS . '">';

echo '<div class="btn-group btn-fitlers">';
echo '<select class="form-control control-inline" name="TEAM">';
//maybe echo '<option value="-3"' . (0 == $TEAM ? " selected":"") . '>Multiple Positions</option>';
echo '<option value="0"' . (0 == $TEAM ? " selected":"") . '>All Players</option>';
echo '<option value="-1"' . (-1 == $TEAM ? " selected":"") . '>Free Agents</option>';
echo '<option value="-3"' . (-3 == $TEAM ? " selected":"") . '>Active Only</option>';
if (!$league->is_commissioner && !$league->is_guest) echo '<option value="-2"' . (-2 == $TEAM ? " selected":"") . '>My Watch List</option>';
echo '<option disabled="disabled">----------</option>';
foreach ($league->teams as $tid => $filter)
	echo '<option value="' . $tid . '"' . ($tid == $TEAM?" selected":"") . '>' . $filter->Name(40) . '</option>';
echo "</select>";

echo '</div>'; //btn-group
echo '</form>';
echo '</div></div>';
$ACTIVE = (-3 == $TEAM); // active only filter


//
//  Position Selection
//
echo '<div class="pos-select h2"><ul class="pull-left">';
foreach ($league->position_groups as $group_id => $group) {
   if ($group->IsFlex()) continue;
   echo '<li id=POS' . $group_id . ($group_id == $POS ? ' class="selected"':'') . '>';
   echo '<a href="' . BasketballPresentation::URL('report-eligibility.php?POS=' . $group_id). '">' . $group->abbreviation . '</a></li>';
}
echo '</ul>';

echo '<div style="clear:both;"></div></div>';


echo '<div class="table-responsive table-fixed-column table-eligible">';
echo '<table class="table table-hover table-tight">';
echo '<thead><tr>';
echo '<th class="column-fixed">Player</th>';
echo '<th>Team</th>';
echo '<th>Act</th>';
echo '<th>Inj</th>';
echo '<th>Fantasy</th>';
echo '<th>Own%</th>';
foreach ($league->position_groups as $group_id => $group ) echo '<th>' . $group->abbreviation . '</th>';
echo '</tr></thead><tbody>';

foreach($players as $id => $groups) {
   if (-2 == $TEAM && !array_key_exists($id, $watchlist)) continue; // not on watch list
   if (-1 == $TEAM && League::PlayerStatusFreeAgent != $status[$id]) continue; // not free agent, filter on free agents (!=)
   if ($TEAM > 0) {
      if (League::PlayerStatusFreeAgent == $status[$id]) continue; // free agent, fitler on team
      if ($TEAM != $status[$id]) continue; // other team, fitler on team
   }
   $player = BasketballPlayer::GetPlayer($id);
   if (!$player || $player->player_id != $id) continue;
	if ($ACTIVE && !$player->active) continue;

   echo '<tr player-id="' . $player->player_id . '">';
   echo '<td class="column-fixed">' . BasketballPresentation::PlayerPopup($player->player_id, true, "lastfirst") . '</td>';
   echo '<td>' . $player->nba_team . '</td>';
   echo '<td>' . ($player->active ? "A":""). '</td>';
   echo '<td>' . BasketballPlayer::InjuryIndicator($player->injury_status) . '</td>';

   echo '<td nowrap>';
   if (League::PlayerStatusFreeAgent == $status[$id]) { 
      if ($league->is_commissioner || $league->is_guest) {
         echo '<span class="hidden-lg hidden-md hidden-sm">FA</span><span class="hidden-xs hidden-tn">Free Agent</span>';
      } else {
         
         echo '<a href="javascript:WatchList('. $id . ');"><span id="player' . $id . '" data-toggle="tooltip" data-placement="top" title="Add to your Watch List" class="glyphicon ' . (array_key_exists($id,$watchlist) ? "glyphicon-star rtfs-gold":"glyphicon-star-empty") . '"></span></a> ';
         echo '<a href="' . BasketballPresentation::URL_FreeAgent($id) . '"><span class="hidden-lg hidden-md hidden-sm">FA</span><span class="hidden-xs hidden-tn">';
         echo ($league->UsingPFAs() && array_key_exists($id,$league->protected_players) ? 'Protected':'Free Agent') . '</span></a>';
      }
   } else {
      if (count($owners[$id]) > 0 ) { // && $league->ShowRosters()) {
         foreach($owners[$id] as $owner) {
            echo '<span class="hidden-lg hidden-md hidden-sm">' . $league->teams[$owner]->abbreviation . '</span>';
            echo '<span class="hidden-xs hidden-tn">' . $league->teams[$owner]->name . '</span>';
            echo "<br>";
         }
      } else {
         echo $owned[$id];
      }
   }
   echo '</td>';

   if (array_key_exists($id, $percent))
      echo '<td>' . $percent[$id] . '</td>';
   else
      echo '<td>0.0</td>';

   foreach ($league->position_groups as $group_id => $group) {
//      if ($group->IsOpenGroup())
//         $pos = 0;
//      else
         $pos = current($group->group_members);
      
      if (in_array($group_id, $groups))
         echo '<td>' . $group->abbreviation . '</td>';
      else
         echo '<td>&nbsp;</td>';
   }
	echo '</tr>';
}
echo '</tbody></table>';
echo '</div>';

?>
<script>
function WatchList(pid) {
   if ($("#player" + pid).hasClass("rtfs-gold")) {
      $("#player" + pid).removeClass("rtfs-gold").removeClass("glyphicon-star").addClass("glyphicon-star-empty");
      $.ajax({
        type: "GET",
        url: '/basketball/watch-list.php',
        data: { LID: _basketball.league_id, UID: _basketball.uid, DEL: pid }
      });
   } else {
      $("#player" + pid).addClass("rtfs-gold").addClass("glyphicon-star").removeClass("glyphicon-star-empty");
      $.ajax({
        type: "GET",
        url: '/basketball/watch-list.php',
        data: { LID: _basketball.league_id, UID: _basketball.uid, ADD: pid }
      });
   }
}
</script>

<?

$theme->ResponsiveFooter();
?>