<?php
session_start();
require_once('mysqli_connect.php');

// must be logged in
if (!isset($_SESSION['user_id'])) {
  header("Location: login.php");
  exit();
}

// must be coach/admin/player
$role = $_SESSION['role'] ?? '';
if ($role !== 'admin' && $role !== 'player' && $role !== 'super_admin') {
  die("Access denied.");
}
$user_id = (int)$_SESSION['user_id'];
$team_id = isset($_GET['team_id']) ? (int)$_GET['team_id'] : 0;

$coach_id = (int)$_SESSION['user_id'];
$errors = [];
$success = "";

function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }


// Search + Filter values
$search = trim($_GET['search'] ?? '');
$team_filter = isset($_GET['team_id']) ? (int)$_GET['team_id'] : 0;

// Handle photo upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'upload_photo') {
  $player_id = (int)($_POST['player_id'] ?? 0);

  if ($player_id <= 0) {
    $errors[] = "Invalid player selected.";
  } else {
    // make sure this player belongs to one of this coach's teams
    $check_q = "SELECT u.user_id
                FROM users u
                JOIN team_members tm ON tm.player_id = u.user_id
                JOIN teams t ON t.team_id = tm.team_id
                WHERE u.user_id = $player_id
                  AND t.coach_id = $coach_id
                LIMIT 1";
    $check_r = mysqli_query($dbc, $check_q);

    if (!$check_r || mysqli_num_rows($check_r) !== 1) {
      $errors[] = "You do not have permission to update this player photo.";
    } else {
      if (!isset($_FILES['photo']) || $_FILES['photo']['error'] !== UPLOAD_ERR_OK) {
        $errors[] = "Please choose a photo to upload.";
      } else {
        $file = $_FILES['photo'];

        $allowed_types = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
        $mime = mime_content_type($file['tmp_name']);

        if (!isset($allowed_types[$mime])) {
          $errors[] = "Only JPG, PNG, or WEBP images are allowed.";
        } else {
          if (!is_dir('uploads')) {
            mkdir('uploads', 0777, true);
          }

          $ext = $allowed_types[$mime];
          $filename = 'player_' . $player_id . '_' . time() . '.' . $ext;
          $destination = 'uploads/' . $filename;

          if (move_uploaded_file($file['tmp_name'], $destination)) {
            $photoEsc = mysqli_real_escape_string($dbc, $destination);

            $update_q = "UPDATE users
                         SET photo = '$photoEsc'
                         WHERE user_id = $player_id
                         LIMIT 1";
            $update_r = mysqli_query($dbc, $update_q);

            if ($update_r) {
              $success = "Player photo updated.";
            } else {
              $errors[] = "Photo uploaded, but database could not be updated.";
            }
          } else {
            $errors[] = "Could not save uploaded file.";
          }
        }
      }
    }
  }
}

// Team filter dropdown data
$teams = [];
$q = "SELECT team_id, team_name
      FROM teams
      WHERE coach_id = $coach_id
      ORDER BY team_name ASC";
$r = mysqli_query($dbc, $q);

if ($r) {
  while ($row = mysqli_fetch_assoc($r)) {
    $teams[] = $row;
  }
}


// Player cards query
$players = [];
$teamName = '';

if ($team_id <= 0) {
  $errors[] = "No team selected.";
} else {

  // admin can open their own team
  if ($role === 'admin') {
    $check_q = "SELECT team_name
                FROM teams
                WHERE team_id = $team_id
                  AND coach_id = $user_id
                LIMIT 1";
  }

  // super admin can open any team
  elseif ($role === 'super_admin') {
    $check_q = "SELECT team_name
                FROM teams
                WHERE team_id = $team_id
                LIMIT 1";
  }

  // player can only open a team they belong to
  else {
    $check_q = "SELECT t.team_name
                FROM teams t
                JOIN team_members tm ON tm.team_id = t.team_id
                WHERE t.team_id = $team_id
                  AND tm.player_id = $user_id
                LIMIT 1";
  }

  $check_r = mysqli_query($dbc, $check_q);

  if (!$check_r || mysqli_num_rows($check_r) !== 1) {
    $errors[] = "Team not found or you do not have access.";
  } else {
    $teamRow = mysqli_fetch_assoc($check_r);
    $teamName = $teamRow['team_name'];

    $q = "SELECT
            u.user_id,
            u.first_name,
            u.last_name,
            u.photo,
            tm.jersey_num,
            tm.position,
            t.team_name,
            t.team_id
          FROM team_members tm
          JOIN users u ON u.user_id = tm.player_id
          JOIN teams t ON t.team_id = tm.team_id
          WHERE t.team_id = $team_id
          ORDER BY tm.jersey_num ASC, u.last_name ASC, u.first_name ASC";

    $r = mysqli_query($dbc, $q);

    if ($r) {
      while ($row = mysqli_fetch_assoc($r)) {
        $players[] = $row;
      }
    }
  }
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Player Cards • Sideline</title>
<link rel="icon" type="image/x-icon" href="images/sideline_logo.ico">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
:root{
  --bg:#f6f7fb;
  --card:#fff;
  --line:#e5e7eb;
  --dark:#111827;
  --muted:#64748b;
  --text:#0f172a;
}
*{box-sizing:border-box}
body{
  margin:0;
  font-family:system-ui,Segoe UI,Arial,sans-serif;
  background:var(--bg);
  color:var(--text);
}
.topbar{
  display:flex;
  justify-content:space-between;
  align-items:center;
  padding:14px 18px;
  background:linear-gradient(to right, #251F47, #111827, #2B784A);
  color:white;
}
.nav a{
  color:white;
  text-decoration:none;
  border:1px solid rgba(255,255,255,.18);
  padding:8px 10px;
  border-radius:12px;
  margin-left:8px;
}
.container{
  max-width:1200px;
  margin:22px auto;
  padding:0 16px;
}
.grid{
  display:grid;
  grid-template-columns:repeat(3,1fr);
  gap:16px;
}
.card{
  background:var(--card);
  border:1px solid var(--line);
  border-radius:16px;
  padding:16px;
  box-shadow:0 8px 24px rgba(0,0,0,.05);
}
.toolbar{
  background:#fff;
  border:1px solid var(--line);
  border-radius:16px;
  padding:16px;
  margin-bottom:16px;
}
.toolbar form{
  display:flex;
  gap:10px;
  flex-wrap:wrap;
  align-items:end;
}
label{
  display:block;
  font-size:.9rem;
  color:var(--muted);
  margin-bottom:6px;
}
input, select{
  width:100%;
  padding:10px 12px;
  border:1px solid var(--line);
  border-radius:12px;
  background:#fff;
}
.field{
  min-width:220px;
}
.playerPhoto{
  width:90px;
  height:90px;
  border-radius:50%;
  object-fit:cover;
  display:block;
  margin:0 auto 12px auto;
  border:2px solid var(--line);
  background:#f1f5f9;
}
.muted{
  color:var(--muted);
}
.btn{
  display:inline-block;
  padding:8px 10px;
  border-radius:12px;
  border:1px solid var(--line);
  text-decoration:none;
  margin-top:10px;
  background:#fff;
  color:var(--text);
  cursor:pointer;
}
.btn.dark{
  background:var(--dark);
  color:#fff;
  border-color:var(--dark);
}
.error{
  background:#fef2f2;
  border:1px solid #fecaca;
  color:#991b1b;
  padding:10px 12px;
  border-radius:12px;
  margin-bottom:16px;
}
.success{
  background:#ecfdf5;
  border:1px solid #bbf7d0;
  color:#166534;
  padding:10px 12px;
  border-radius:12px;
  margin-bottom:16px;
}
.uploadBox{
  margin-top:12px;
  padding-top:12px;
  border-top:1px solid var(--line);
}
.uploadBox form{
  display:flex;
  flex-direction:column;
  gap:8px;
}
@media (max-width:900px){
  .grid{grid-template-columns:1fr;}
  .field{min-width:100%;}
}
</style>
</head>
<body>

<header class="topbar">
  <div><strong>Sideline</strong> Player Cards</div>
<div class="nav">
  <?php if ($role === 'admin' || $role === 'super_admin'): ?>
    <a href="coach_dashboard.php">Dashboard</a>
  <?php else: ?>
    <a href="player_home.php">Home</a>
  <?php endif; ?>
  <a href="logout.php">Logout</a>
</a>
</div>
</header>

<main class="container">

  <h2>Player Cards</h2>
  <p class="muted">Search players, filter by team, and upload headshots.</p>

  <?php if (!empty($errors)): ?>
    <div class="error">
      <strong>Please fix:</strong>
      <ul>
        <?php foreach ($errors as $e): ?>
          <li><?= h($e) ?></li>
        <?php endforeach; ?>
      </ul>
    </div>
  <?php endif; ?>

  <?php if ($success): ?>
    <div class="success">✅ <?= h($success) ?></div>
  <?php endif; ?>

  <div class="toolbar">
    <form method="get" action="player_cards.php">
      <div class="field">
        <label>Search Player</label>
        <input type="text" name="search" value="<?= h($search) ?>" placeholder="Search by first or last name">
      </div>

      <div class="field">
        <label>Filter by Team</label>
        <select name="team_id">
          <option value="0">All Teams</option>
          <?php foreach ($teams as $team): ?>
            <option value="<?= (int)$team['team_id'] ?>" <?= $team_filter === (int)$team['team_id'] ? 'selected' : '' ?>>
              <?= h($team['team_name']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <div>
        <button class="btn dark" type="submit">Apply</button>
      </div>

      <div>
        <a class="btn" href="player_cards.php">Clear</a>
      </div>
    </form>
  </div>

  <?php if (empty($players)): ?>
    <div class="card">
      No players found for this search/filter.
    </div>
  <?php else: ?>

    <div class="grid">
      <?php foreach ($players as $p): ?>
        <?php
          $photo = !empty($p['photo']) ? h($p['photo']) : 'images/default-player.png';
        ?>
        <div class="card">

          <img src="<?= $photo ?>" class="playerPhoto" alt="Player photo">

          <h3><?= h($p['first_name'] . ' ' . $p['last_name']) ?></h3>

          <p><strong>#<?= h($p['jersey_num'] ?? '—') ?></strong></p>

          <p class="muted"><?= h($p['position'] ?? 'No position') ?></p>

          <p class="muted">Team: <?= h($p['team_name']) ?></p>

          <a class="btn" href="team.php?team_id=<?= (int)$p['team_id'] ?>">Open Team</a>

          <?php if ($role === 'admin' || $role === 'super_admin'): ?>
  <div class="uploadBox">
    <form method="post" action="player_cards.php?team_id=<?= (int)$team_id ?>" enctype="multipart/form-data">
      <input type="hidden" name="action" value="upload_photo">
      <input type="hidden" name="player_id" value="<?= (int)$p['user_id'] ?>">

      <label>Upload / Change Photo</label>
      <input type="file" name="photo" accept=".jpg,.jpeg,.png,.webp" required>

      <button class="btn dark" type="submit">Upload Photo</button>
    </form>
  </div>
<?php endif; ?>

        </div>
      <?php endforeach; ?>
    </div>

  <?php endif; ?>

</main>
</body>
</html>