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

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

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

$errors = [];
$success = false;

//Stickyy: Keep form values after submit
$team_name = '';
$sport = '';
$season = '';
$notes = '';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

  $team_name = trim($_POST['team_name'] ?? '');
  $sport     = trim($_POST['sport'] ?? '');
  $season    = trim($_POST['season'] ?? '');
  $notes     = trim($_POST['notes'] ?? '');

  // ---- Validation :D ----
  if ($team_name === '') $errors[] = "Team name is required.";
  if ($sport === '') $errors[] = "Sport is required.";
  if (!in_array($sport, ['Baseball', 'Football', 'Soccer', 'Basketball'], true)) {
    $errors[] = "Please choose a valid sport.";
  }
  if ($season === '') $errors[] = "Season is required (ex: Spring 2026).";

/*  // prevent duplicate team_name per coach+season so it doesnt get crazy
  if (empty($errors)) {
    $teamEsc = mysqli_real_escape_string($dbc, $team_name);
    $sportEsc = mysqli_real_escape_string($dbc, $sport);
    $seasonEsc = mysqli_real_escape_string($dbc, $season);

    $q = "SELECT team_id
          FROM teams
          WHERE coach_id = $coach_id
            AND team_name = '$teamEsc'
            AND sport = '$sportEsc'
            AND season = '$seasonEsc'
          LIMIT 1";
    $r = mysqli_query($dbc, $q);
    if ($r && mysqli_num_rows($r) > 0) {
      $errors[] = "You already have a team with that name, sport, and season.";
    }
  }
*/


/*original insert
  // ---- Insert ----
  if (empty($errors)) {
    $teamEsc = mysqli_real_escape_string($dbc, $team_name);
    $sportEsc = mysqli_real_escape_string($dbc, $sport);
    $seasonEsc = mysqli_real_escape_string($dbc, $season);
    $notesEsc = mysqli_real_escape_string($dbc, $notes);





   $q = "INSERT INTO teams (coach_id, team_name, sport, season, notes, is_active)
          VALUES ($coach_id, '$teamEsc', '$sportEsc', '$seasonEsc', '$notesEsc', 1)";
    $r = mysqli_query($dbc, $q);

    if ($r) {
      $success = true;

      // Stay on this page and show success message
      // ooorrrrr redirect back to dashboard with a message:
      header("Location: admin_dashboard.php?msg=team_created");
      exit();
    } else {
      $errors[] = "Database error: " . mysqli_error($dbc);
    }
  }
  
 */
  
  /*revisit validation to prevent duplicates*/
 /*insert statement for rostered_coach*/
 // ---- Insert ----
    if (empty($errors)) {
    $teamEsc = mysqli_real_escape_string($dbc, $team_name);
    $sportEsc = mysqli_real_escape_string($dbc, $sport);
    $seasonEsc = mysqli_real_escape_string($dbc, $season);
    $notesEsc = mysqli_real_escape_string($dbc, $notes);


    $q = "INSERT INTO teams (team_name, sport, season, notes, is_active)
          VALUES ('$teamEsc', '$sportEsc', '$seasonEsc', '$notesEsc', 1)";
    $r = mysqli_query($dbc, $q);
    
    $q2 = "SELECT * FROM teams";
    $r2 = mysqli_query($dbc, $q2);
    $row2 = mysqli_fetch_array($r2, MYSQLI_ASSOC);
    
    
    $q3 = "SELECT team_id FROM teams 
           WHERE team_name = '$team_name'";
           
    $r3 = mysqli_query($dbc, $q3);
    $row3 = mysqli_fetch_array($r3, MYSQLI_ASSOC);
    
    
    $q4 = "INSERT INTO rostered_coaches (user_id, team_id, position)
          VALUES ('$coach_id', '$row3[team_id]', 'Head Coach')";
    $r4 = mysqli_query($dbc, $q4);
          
          
    if ($r) {
      $success = true;

      // Stay on this page and show success message
      // ooorrrrr redirect back to dashboard with a message:
      header("Location: coach_dashboard.php?msg=team_created");
      exit();
    } else {
      $errors[] = "Database error: " . mysqli_error($dbc);
    }
  }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Create Team • Sideline</title>
  <link rel="icon" type="image/x-icon" href="images/sideline_logo.ico">
  <style>
   /* ===== Root Variables ===== */
:root {
  --bg: #f6f7fb; 
  --card: #fff; 
  --text: #0f172a; 
  --muted: #64748b;
  --line: #e5e7eb; 
  --dark: #111827; 
  --accent: #2563eb;
  --ok: #16a34a; 
  --warn: #f59e0b;
}

/* ===== Global Styles ===== */
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui,Segoe UI,Arial,sans-serif; background: var(--bg); color: var(--text); }
a { color: inherit; text-decoration: none; }

/* ===== Topbar ===== */
.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 ===== */
.container { max-width: 1100px; margin: 22px auto; padding: 0 16px; }


/* ===== Centered Single Card ===== */
 .grid.single-card {
  display: flex;
  flex-direction: column;  
  align-items: center;      
  margin-top: 20px;
  gap: 20px;                
}

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

/* ===== Title Card Above ===== */
.card.title-card {
  max-width: 500px;   
  max-height: 100px;
  width: 100%;
  padding: 16px 12px;       
  margin: 0 auto;           
  background: linear-gradient(to right, #f6f7fb, #C5E8B7, #2B784A);
  color: #251F47;
  text-align: center;
  border-radius: 16px;
  font-size: 1.05rem;
  font-weight: 700;
}

/* ===== Typography ===== */
h1,h2,h3 { margin: 0 0 10px; }
p { margin: 8px 0; color: var(--muted); }
label { display: block; font-size: .9rem; color: var(--muted); margin: 10px 0 6px; }

/* ===== Form Elements ===== */
input, select, textarea {
  width: 100%; padding: 10px 12px; border: 1px solid var(--line);
  border-radius: 12px; background: #fff;
}
textarea { min-height: 90px; resize: vertical; }

/* ===== Buttons ===== */
.btn {
  background: #251F47; color: #ffffff; border: none; border-radius: 12px;
  padding: 10px 12px; cursor: pointer; display: inline-block;
}
.btn.secondary { background: #fff; color: var(--dark); border: 1px solid var(--line); }
.split { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 14px; }

/* ===== Notifications ===== */
.error {
  background: #fef2f2; border: 1px solid #fecaca; color: #991b1b;
  padding: 10px 12px; border-radius: 12px; margin: 10px 0;
}
.notice {
  padding: 10px 12px; border-radius: 12px; border: 1px dashed var(--line);
  background: #fafafa; color: #334155;
}

/* ===== Responsive ===== */
@media (max-width: 900px){
  .card { max-width: 100%; }
}
  </style>
</head>

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

<main class="container">
  

    <!-- Title Card -->
    <div class="card title-card">
      <h1 style="text-align:center; margin:0;">Create Your Team !</h1>
    </div>
    
<section class="grid single-card">
    <!-- Form Card -->
    <div class="card">
      <?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; ?>

      <form method="post" action="create_team.php" novalidate>
        <label>Team name <span style="color:#991b1b">*</span></label>
        <input name="team_name" value="<?= h($team_name) ?>" placeholder="Milwaukee Falcons" required>

        <label>Sport <span style="color:#991b1b">*</span></label>
        <select name="sport" required>
          <option value="">-- Select a sport --</option>
          <option value="Baseball" <?= $sport === 'Baseball' ? 'selected' : '' ?>>Baseball</option>
          <option value="Football" <?= $sport === 'Football' ? 'selected' : '' ?>>Football</option>
          <option value="Soccer" <?= $sport === 'Soccer' ? 'selected' : '' ?>>Soccer</option>
          <option value="Basketball" <?= $sport === 'Basketball' ? 'selected' : '' ?>>Basketball</option>
        </select>

        <label>Season <span style="color:#991b1b">*</span></label>
        <input name="season" value="<?= h($season) ?>" placeholder="Spring 2026" required>

        <label>Notes</label>
        <textarea name="notes" placeholder="Focus: conditioning + defensive communication."><?= h($notes) ?></textarea>

        <div class="split">
          <button class="btn" type="submit">Save Team</button>
          <a class="btn secondary" href="coach_dashboard.php">Cancel</a>
        </div>
      </form>
    </div>

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