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

// ---- Safety: must be logged in + admin ----
if (!isset($_SESSION['user_id'])) {
  header("Location: login.php");
  exit();
}
if (($_SESSION['role'] ?? '') !== 'admin' && ($_SESSION['role'] ?? '') !== 'super_admin') {
  die("Access denied.");
}

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

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

// HTML escape stuff
function h($s){
    return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
    
// Get user's last name for welcome message
$user_id = (int)$_SESSION['user_id'];
$q = "SELECT last_name FROM users WHERE user_id = $user_id LIMIT 1";
$r = mysqli_query($dbc, $q);
if ($r && $row = mysqli_fetch_assoc($r)) {
    $_SESSION['last_name'] = $row['last_name'];
}

//Get the pfp for coach 
$pfp = 'images/default_pfp.png';

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

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

// ---- 2) List this coach's teams ---- Anthony
$teams = [];
$q = "SELECT team_id
      FROM rostered_coaches
      WHERE user_id = $coach_id";
$r = mysqli_query($dbc, $q);

if ($r){
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
            
    $team_id = (int)$row['team_id'];

    $q2 = "SELECT team_id, team_name, sport, season, is_active
        FROM teams
        WHERE team_id = $team_id
        ORDER BY is_active DESC, team_name ASC";
    $r2 = mysqli_query($dbc, $q2);
    
    if ($r2) {
     while ($row2 = mysqli_fetch_assoc($r2)) {
         $teams[] = $row2;
     }
    }
  }
}


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

if ($r) {
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
            
    $team_id = (int)$row['team_id'];   

    $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 = $team_id
        AND event_date = CURDATE()
        ORDER BY event_date $order";
    $r2 = mysqli_query($dbc, $q2);
    
    if ($r2) {
     while ($row2 = mysqli_fetch_assoc($r2)) {
         $events[] = $row2;
     }
    }
  }
}

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

if ($r) {
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
                
    $team_id = (int)$row['team_id'];    

    $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 = $team_id
        AND event_date >= CURDATE()
        ORDER BY event_date $order";
    $r2 = mysqli_query($dbc, $q2);
    
    if ($r2) {
     while ($row2 = mysqli_fetch_assoc($r2)) {
         $allEvents[] = $row2;
     }
    }
  }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Coach 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;
}

.nav a.active { border-color: #fff; opacity: 1; }

.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;
}

.stack { display: flex; flex-direction: column; gap: 10px; }

.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);
}

.split { display: flex; gap: 10px; flex-wrap: wrap; }

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;
}

.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;
}
  </style>
</head>

<body>
<header class="topbar">
  <div class="brand"><a href="coach_dashboard.php">Sideline <span style="opacity:.8;font-weight:600">Coach</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;">
  <a href = "profile.php?user_id=<?= (int)$user_id?>"><img src="<?= h($pfp) ?>" style="width:55px;height:55px;border-radius:50%;object-fit:cover;"></a>
  <h2>Welcome to Sideline, Coach <?= h($_SESSION['last_name'] ?? '') ?>!</h2>
</div>

  <?php if ($msg === 'team_created'): ?>
    <div class="success">Team created successfully!</div>
  <?php endif; ?>
</div>

<div class="bottomLayout">

<div class="card">
  <div class="titleRow">
    <h3>My Teams</h3>
    <a class="btn secondary" href="create_team.php">Create New Team</a>
  </div>

  <?php if (empty($teams)): ?>
    <p class="notice">No teams yet.</p>
  <?php else: ?>
    <table>
      <thead>
        <tr>
          <th>Team</th>
          <th>Sport</th>
          <th>Season</th>
          <th>Open</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($teams as $t): ?>
        <tr>
          <td><?= h($t['team_name']) ?></td>
          <td><?= h($t['sport']) ?></td>
          <td><?= h($t['season']) ?></td>
          <td>
            <a class="btn secondary" href="lineup_builder.php?team_id=<?= (int)$t['team_id'] ?>">Open</a>
          </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 scheduled for 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><?= !empty($event['notes']) ? h($event['notes']) : '—' ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  <?php endif; ?>
</div>

</section>
</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>