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

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

if (($_SESSION['role'] ?? '') !== 'player') {
  header("Location: coach_dashboard.php");
  exit();
}

$player_id = (int)$_SESSION['user_id'];
$msg = $_GET['msg'] ?? '';

$sort = $_GET['sort'] ?? 'asc';
$order = ($sort === 'desc') ? 'DESC' : 'ASC';

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

// Get player's last name for welcome message
$q = "SELECT first_name, last_name, email
      FROM users
      WHERE user_id = $player_id
      LIMIT 1";
$r = mysqli_query($dbc, $q);

$player_first = '';
$player_last = '';
$player_email = '';

if ($r && $row = mysqli_fetch_assoc($r)) {
  $player_first = $row['first_name'] ?? '';
  $player_last  = $row['last_name'] ?? '';
  $player_email = $row['email'] ?? '';
  $_SESSION['last_name'] = $player_last;
}

$pfp = 'images/default_pfp.png';

$q = "SELECT photo FROM users WHERE user_id = $player_id LIMIT 1";
$r = mysqli_query($dbc, $q);

if ($r && $row = mysqli_fetch_assoc($r)) {
  if (!empty($row['photo'])) {
    $pfp = 'images/' . $row['photo'];
  }
}

//---- Player teams ---- Anthony
$teams = [];
$q = "SELECT
        t.team_id,
        t.team_name,
        t.sport,
        t.season,
        t.is_active,
        rp.jersey_num,
        rp.position,
        u.first_name AS coach_first,
        u.last_name AS coach_last
      FROM rostered_players rp
      JOIN teams t ON t.team_id = rp.team_id
      JOIN users u ON u.user_id = rp.user_id
      WHERE rp.user_id = $player_id
      ORDER BY t.is_active DESC, t.team_name ASC";
$r = mysqli_query($dbc, $q);

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

// ---- 3) Today's events for this player ---- Anthony
$events = [];
$q = "SELECT team_id
      FROM rostered_players
      WHERE user_id = $player_id";
$r = mysqli_query($dbc, $q);

while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
    $q2 = "SELECT events.title, events.event_type, events.event_date, events.notes, teams.team_name
        FROM events
        INNER JOIN teams 
        ON events.team_id = teams.team_id
        WHERE events.team_id = '$row[team_id]'
        AND event_date = CURDATE()
        ORDER BY event_date $order";
    $r2 = mysqli_query($dbc, $q2);
    
    while($row2 = mysqli_fetch_array($r2, MYSQLI_ASSOC)){
        $events[]= $row2;
    }
}

// ---- 4) ALL upcoming events for this coach's teams ---- Anthony
$allEvents = [];
$q = "SELECT team_id
      FROM rostered_players
      WHERE user_id = $player_id";
$r = mysqli_query($dbc, $q);

while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
    $q2 = "SELECT events.title, events.event_type, events.event_date, events.notes, teams.team_name
        FROM events
        INNER JOIN teams 
        ON events.team_id = teams.team_id
        WHERE events.team_id = '$row[team_id]'
        AND event_date >= CURDATE()
        ORDER BY event_date $order";
    $r2 = mysqli_query($dbc, $q2);

    while($row2 = mysqli_fetch_array($r2, MYSQLI_ASSOC)){
        $allEvents[]= $row2;
    }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Player Dashboard • Sideline</title>
  <link rel="icon" type="image/x-icon" href="images/sideline_logo.ico">
  <style>
:root {
  --bg: #f6f7fb;
  --card: #fff;
  --text: #0f172a;
  --muted: #64748b;
  --line: #e5e7eb;
  --dark: #111827;
  --accent: #2563eb;
  --ok: #16a34a;
  --warn: #f59e0b;
}

* { box-sizing: border-box; }

body {
  margin: 0;
  font-family: system-ui, Segoe UI, Arial, sans-serif;
  background: var(--bg);
  min-height: 100vh;
}

a { color: inherit; text-decoration: none; }

.topbar {
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 18px;
  background: linear-gradient(to right, #251F47, #111827, #2B784A);
  color: #fff;
  border-bottom: 1px solid rgba(255,255,255,.08);
}

.brand { font-weight: 800; letter-spacing: .3px; }

.nav {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
}

.nav a {
  background: #FFFFFF;
  color: #251F47;
  border: 1px solid rgba(255,255,255,.18);
  padding: 8px 10px;
  border-radius: 12px;
  cursor: pointer;
  opacity: .95;
}

.container {
  max-width: 1100px;
  margin: 22px auto;
  padding: 0 16px;
}

.grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  gap: 14px;
}

.col-12 { grid-column: span 12; }

.card {
  background: var(--card);
  border: 1px solid var(--line);
  border-radius: 16px;
  padding: 16px;
  box-shadow: 0 10px 30px rgba(2,6,23,.05);
}

h1, h2, h3 { margin: 0 0 10px; color: var(--text); }
p { margin: 8px 0; color: var(--muted); }

.titleRow {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  flex-wrap: wrap;
}

.badge {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 10px;
  border-radius: 999px;
  background: #eef2ff;
  color: #3730a3;
  font-size: .85rem;
  border: 1px solid #e0e7ff;
}

.badge.ok {
  background: #ecfdf5;
  border-color: #bbf7d0;
  color: #166534;
}

.badge.warn {
  background: #fffbeb;
  border-color: #fde68a;
  color: #92400e;
}

.btn {
  background: var(--dark);
  color: #fff;
  border: none;
  border-radius: 12px;
  padding: 10px 12px;
  cursor: pointer;
  display: inline-block;
}

.btn.secondary {
  background: #251F47;
  color: #fff;
  border: 1px solid var(--line);
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

th, td {
  padding: 10px;
  border-bottom: 1px solid var(--line);
  text-align: left;
  font-size: .95rem;
  vertical-align: top;
}

th { color: #334155; font-weight: 700; }

.notice {
  padding: 10px 12px;
  border-radius: 12px;
  border: 1px dashed var(--line);
  background: #fafafa;
  color: #334155;
}

.success {
  padding: 10px 12px;
  border-radius: 12px;
  border: 1px solid #bbf7d0;
  background: #ecfdf5;
  color: #166534;
  margin-top: 12px;
}

.bottomLayout {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 14px;
  grid-column: span 12;
  align-items: start;
}

.rightColumn {
  display: flex;
  flex-direction: column;
  gap: 14px;
}

.welcomeBox {
  background: linear-gradient(to right, #FFFFFF, #C5E8B7, #2B784A);
  color: #111827;
  padding: 18px 20px;
  border-radius: 14px;
  margin-bottom: 10px;
}

.welcomeBox h2 { margin: 0; color: #111827; }

.weatherWrap {
  background: #fff;
  border: 1px solid var(--line);
  border-radius: 16px;
  padding: 10px;
  box-shadow: 0 10px 30px rgba(2,6,23,.05);
  overflow: hidden;
}

@media (max-width: 900px) {
  .bottomLayout {
    grid-template-columns: 1fr;
  }
}
  </style>
</head>

<body>
  <header class="topbar">
    <div class="brand">
      <a href="player_home.php">Sideline <span style="opacity:.8;font-weight:600">Player</span></a>
    </div>
    <div class="nav">
      <a href="logout.php">Logout</a>
    </div>
  </header>

  <main class="container">
    <section class="grid">

      <div class="col-12">
        <div class="welcomeBox" style="display:flex; align-items:center; gap:15px;">
          
          <!--make pfp a link to profile-->
          <a href = "profile.php?user_id=<?= (int)$player_id?>"><img src="<?= h($pfp) ?>" style="width:55px;height:55px;border-radius:50%;object-fit:cover;"></a>
          
          
          <h2>Welcome to Sideline, <?= h($player_first ?: ($_SESSION['name'] ?? 'Player')) ?>!</h2>
        </div>

        <?php if ($msg === 'profile_updated'): ?>
          <div class="success">✅ Profile updated successfully!</div>
        <?php endif; ?>
      </div>

      <div class="bottomLayout">

        <div class="card">
          <div class="titleRow">
            <h3>My Teams</h3>
          </div>

          <?php if (empty($teams)): ?>
            <p class="notice">You are not on any teams yet.</p>
          <?php else: ?>
            <table>
              <thead>
                <tr>
                  <th>Team</th>
                  <th>Sport</th>
                  <th>Season</th>
                  <th>Details</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($teams as $t): ?>
                  <tr>
                    <td>
                      <strong><?= h($t['team_name']) ?></strong><br>
                    </td>
                    <td><?= h($t['sport']) ?></td>
                    <td><?= h($t['season']) ?></td>
                    <td>
                      <small>
                        Jersey #<?= h($t['jersey_num']) ?><br>
                        <?= h($t['position']) ?>
                      </small>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          <?php endif; ?>
        </div>

        <div class="rightColumn">

          <div class="weatherWrap">
            <a class="weatherwidget-io"
               href="https://forecast7.com/en/43d04n87d91/milwaukee/?unit=us"
               data-label_1="MILWAUKEE" 
               data-label_2="WEATHER" 
               data-font="Arial" 
               data-icons="Climacons Animated" 
               data-theme="pure">
              MILWAUKEE WEATHER
            </a>
          </div>

          <div class="card">
            <div class="titleRow">
              <h3>Today's Events</h3>
              <div class="split">
              </div>
            </div>

            <?php if (empty($events)): ?>
              <p class="notice">No events today.</p>
            <?php else: ?>
              <table>
                <thead>
                  <tr>
                    <th>Date</th>
                    <th>Event</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($events as $event): ?>
                    <tr>
                      <td><?= h($event['event_date']) ?></td>
                      <td>
                        <?= h($event['title']) ?><br>
                        <small><?= h($event['team_name']) ?> • <?= h($event['event_type']) ?></small>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            <?php endif; ?>
          </div>

        </div>
      </div>

      <div class="card col-12">
        <div class="titleRow">
          <h3>All Upcoming Events</h3>
          <div class="split">
            <a class="btn secondary" href="?sort=asc">Oldest First</a>
            <a class="btn secondary" href="?sort=desc">Newest First</a>
          </div>
        </div>

        <?php if (empty($allEvents)): ?>
          <p class="notice">No upcoming events scheduled.</p>
        <?php else: ?>
          <table>
            <thead>
              <tr>
                <th>Date</th>
                <th>Team</th>
                <th>Event</th>
                <th>Type</th>
                <th>Notes</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($allEvents as $event): ?>
                <tr>
                  <td><?= h($event['event_date']) ?></td>
                  <td><?= h($event['team_name']) ?></td>
                  <td><?= h($event['title']) ?></td>
                  <td><?= h($event['event_type']) ?></td>
                  <td>
                    <?php if (!empty($event['notes'])): ?>
                      <?= h($event['notes']) ?>
                    <?php else: ?>
                      <span style="color:#94a3b8;">—</span>
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        <?php endif; ?>
      </div>

    </section>

    <p style="text-align:center;color:#64748b;margin:18px 0;">
      Sideline • Player Dashboard
    </p>
  </main>

  <script>
    !function(d,s,id){
      var js,fjs=d.getElementsByTagName(s)[0];
      if(!d.getElementById(id)){
        js=d.createElement(s);
        js.id=id;
        js.src='https://weatherwidget.io/js/widget.min.js';
        fjs.parentNode.insertBefore(js,fjs);
      }
    }(document,'script','weatherwidget-io-js');
  </script>
</body>
</html>