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

// ---- Only allow super admins ----
if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'super_admin') {
    die("Access denied. Super admins only.");
}

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

$errors = [];
$success = "";

// ---- Handle deletion ----
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $team_id = (int)($_POST['team_id'] ?? 0);

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

        // 1. Get team name BEFORE deleting
        $stmt = $dbc->prepare("SELECT team_name FROM teams WHERE team_id = ?");
        $stmt->bind_param("i", $team_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $team = $result->fetch_assoc();
        $team_name = $team['team_name'] ?? "Unknown Team";

        // 1.5 Delete related rostered coaches first (foreign key fix)
        $del = $dbc->prepare("DELETE FROM rostered_coaches WHERE team_id = ?");
        $del->bind_param("i", $team_id);
        $del->execute();

        // 2. Delete the team
        $stmt = $dbc->prepare("DELETE FROM teams WHERE team_id = ? LIMIT 1");
        $stmt->bind_param("i", $team_id);
        $stmt->execute();

        // 3. Confirmation message
        if ($stmt->affected_rows > 0) {
            $success = "Team \"" . h($team_name) . "\" deleted successfully.";
        } else {
            $errors[] = "Could not delete team.";
        }
    }
}

// ---- Fetch teams ----
$teams = [];
$q = "SELECT team_id, team_name, sport, season, is_active 
      FROM teams 
      ORDER BY team_name ASC";
$r = mysqli_query($dbc, $q);

if ($r) {
    while ($row = mysqli_fetch_assoc($r)) {
        $teams[] = $row;
    }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Manage Teams • Sideline</title>
  <style>
    body {
      margin:0;
      font-family:system-ui,Segoe UI,Arial,sans-serif;
      background:#F6F7FB;
      color:#0f172a;
    }

    /* ---- Updated Header Layout ---- */
    .topbar {
      width:100%;
      display:flex;
      align-items:center;
      justify-content:flex-start;
      gap:30px;
      padding:14px 18px;
      background: linear-gradient(to right, #251F47, #111827, #2B784A);
      color:#fff;
    }

    .nav {
      display:flex;
      gap:10px;
    }

    .nav a {
      color:#fff;
      text-decoration:none;
      padding:8px 12px;
      border-radius:8px;
      background:#2B784A;
    }

    .container {
      max-width:1000px;
      margin:40px auto;
      background:#fff;
      padding:20px;
      border-radius:16px;
      box-shadow:0 10px 30px rgba(0,0,0,.05);
    }
    table {
      width:100%;
      border-collapse:collapse;
      margin-top:20px;
    }
    th, td {
      padding:12px;
      border-bottom:1px solid #e5e7eb;
      text-align:left;
    }
    th { color:#334155; font-weight:700; }
    .btn-danger {
      background:#991b1b;
      color:#fff;
      border:none;
      padding:8px 12px;
      border-radius:8px;
      cursor:pointer;
    }
    .success {
      background:#ecfdf5;
      border:1px solid #bbf7d0;
      color:#166534;
      padding:10px;
      border-radius:8px;
      margin-bottom:10px;
    }
    .error {
      background:#fef2f2;
      border:1px solid #fecaca;
      color:#991b1b;
      padding:10px;
      border-radius:8px;
      margin-bottom:10px;
    }
    .badge {
      display:inline-block;
      padding:4px 8px;
      border-radius:6px;
      font-size:.85rem;
      color:#fff;
    }
    .badge.active { background:#16a34a; }
    .badge.inactive { background:#991b1b; }
  </style>
</head>
<body>

<header class="topbar">
  <div class="brand" style="margin-left:6px;">
    <a href="superadmin_dashboard.php" style="color:#fff; font-weight:800; text-decoration:none;">
      Sideline
    </a>
  </div>
  <div class="nav">
    <a href="logout.php" style="color:#fff; text-decoration:none; padding:8px 12px; border-radius:8px; background:#2B784A;">
      Logout
    </a>
  </div>
</header>

<div class="container">
  <h2>Manage Teams</h2>
  <p>View and delete teams.</p>

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

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

  <?php if (empty($teams)): ?>
    <p>No teams found.</p>
  <?php else: ?>
    <table>
      <thead>
        <tr>
          <th>Team Name</th>
          <th>Sport</th>
          <th>Season</th>
          <th>Status</th>
          <th>Action</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>
              <?php if ($t['is_active']): ?>
                <span class="badge active">Active</span>
              <?php else: ?>
                <span class="badge inactive">Inactive</span>
              <?php endif; ?>
            </td>
            <td>
              <form method="post" onsubmit="return confirm('Delete this team?');">
                <input type="hidden" name="team_id" value="<?= (int)$t['team_id'] ?>">
                <button class="btn-danger" type="submit">Delete</button>
              </form>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  <?php endif; ?>
</div>

</body>
</html>
