<?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' && ($_SESSION['role'] ?? '') !== 'super_admin') {
  die("Access denied. Coaches/admins only.");
}

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

$errors = [];
$team = null;
$roster = [];
$team_id = isset($_GET['team_id']) ? (int)$_GET['team_id'] : 0;

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

// ---- Get team info ----
// super_admin can open any team
if ($team_id <= 0) {
  $errors[] = "No team selected.";
} else {
  if ($role === 'super_admin') {
    $q = "SELECT team_id, team_name, sport, season, notes, is_active
          FROM teams
          WHERE team_id = $team_id
          LIMIT 1";
  } /*else {
    $q = "SELECT team_id, team_name, sport, season, notes, is_active
          FROM teams
          WHERE team_id = $team_id AND coach_id = $coach_id
          LIMIT 1";
  }*/
  
  // else Anthony
    else {
        $q = "SELECT team_id, team_name, sport, season, notes, is_active
          FROM teams
          WHERE team_id = $team_id
          LIMIT 1";
    }

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

  if ($r && mysqli_num_rows($r) === 1) {
    $team = mysqli_fetch_assoc($r);
  } else {
    $errors[] = "Team not found or you do not have access.";
  }
}

/*// ---- Pull roster ----
if ($team) {
  $q = "SELECT
          u.user_id,
          u.first_name,
          u.last_name,
          tm.jersey_num,
          tm.position
        FROM team_members tm
        JOIN users u ON u.user_id = tm.player_id
        WHERE tm.team_id = $team_id
        ORDER BY tm.jersey_num IS NULL, tm.jersey_num, u.last_name, u.first_name";
  $r = mysqli_query($dbc, $q);

  if ($r) {
    while ($row = mysqli_fetch_assoc($r)) {
      $roster[] = $row;
    }
  }
}
*/


// ---- Pull roster ---- Anthony
if ($team) {
  $q = "SELECT
          u.user_id,
          u.first_name,
          u.last_name,
          u.photo,
          rp.jersey_num,
          rp.position
        FROM rostered_players rp
        JOIN users u ON u.user_id = rp.user_id
        WHERE rp.team_id = $team_id
        ORDER BY rp.jersey_num IS NULL, rp.jersey_num, u.last_name, u.first_name";
  $r = mysqli_query($dbc, $q);

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


?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Lineup Builder • 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);color:var(--text)}
    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:1300px; margin:22px auto; padding:0 16px}
    .grid{display:grid; grid-template-columns:320px 1fr; gap:16px}
    .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}
    p{margin:8px 0; color:var(--muted)}
    .notice{
      padding:10px 12px; border-radius:12px; border:1px dashed var(--line);
      background:#fafafa; color:#334155;
    }
    .error{
      background:#fef2f2;border:1px solid #fecaca;color:#991b1b;
      padding:10px 12px;border-radius:12px;margin:10px 0
    }
    .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;
      margin-right:6px;
    }

    /* roster sidebar */
    .playerList{
      display:flex;
      flex-direction:column;
      gap:10px;
      margin-top:12px;
    }
    .playerChip{
      padding:10px 12px;
      border:1px solid var(--line);
      background:#fff;
      border-radius:12px;
      cursor:grab;
      box-shadow:0 4px 12px rgba(2,6,23,.05);
      user-select:none;
    }
    .playerChip strong{
      display:block;
      color:var(--text);
    }
    .playerChip span{
      color:var(--muted);
      font-size:.9rem;
    }
    
    .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);
}

    /* field area */
    .fieldWrap{
      background:var(--card);
      border:1px solid var(--line);
      border-radius:16px;
      padding:16px;
      box-shadow:0 10px 30px rgba(2,6,23,.05)
    }
    .field{
      position:relative;
      width:100%;
      min-height:720px;
      border-radius:20px;
      overflow:hidden;
      border:2px solid #dbe2ea;
      background-size:cover;
      background-position:center;
      background-repeat:no-repeat;
    }

    /* sport backgrounds made with gradients/shapes so you don't need external images */
    .field.baseball{
      /*background:
        radial-gradient(circle at 50% 78%, #c68642 0 10%, transparent 10.5%),
        radial-gradient(circle at 50% 78%, #3b7d3a 0 28%, transparent 28.5%),
        linear-gradient(#5da85d, #4b944b);
        */
        
        background-image:url("images/baseball_field_ui.png");
    }
    .field.football{
      /*background:
        repeating-linear-gradient(
          to right,
          rgba(255,255,255,.18) 0px,
          rgba(255,255,255,.18) 2px,
          transparent 2px,
          transparent 80px
        ),
        linear-gradient(#3f9142, #2f7a33);
        
        */
        background-image:url("images/football_field_ui.png");
    }
    .field.soccer{
      /*background:
        radial-gradient(circle at center, transparent 0 59px, rgba(255,255,255,.85) 60px, rgba(255,255,255,.85) 62px, transparent 63px),
        linear-gradient(to right, transparent 49.5%, rgba(255,255,255,.9) 49.5%, rgba(255,255,255,.9) 50.5%, transparent 50.5%),
        linear-gradient(#4ea84e, #3e9440);*/
        
        background-image:url("images/soccer_field_ui.png");
    }
    .field.basketball{
      /*background:
        radial-gradient(circle at 50% 50%, transparent 0 59px, rgba(255,255,255,.8) 60px, rgba(255,255,255,.8) 62px, transparent 63px),
        linear-gradient(to right, transparent 49.5%, rgba(255,255,255,.8) 49.5%, rgba(255,255,255,.8) 50.5%, transparent 50.5%),
        linear-gradient(#d8904d, #c97a35);
        */
        
        background-image:url("images/basketball_court_ui.png");
        
    }

    .fieldLabel{
      position:absolute;
      top:14px;
      left:14px;
      background:rgba(17,24,39,.75);
      color:#fff;
      padding:8px 10px;
      border-radius:12px;
      font-size:.95rem;
      z-index:2;
    }

    .dropZone{
      position:absolute;
      min-width:90px;
      min-height:48px;
      padding:8px;
      border:2px dashed rgba(255,255,255,.7);
      border-radius:14px;
      background:rgba(255,255,255,.7);
      color:#000000;
      font-weight:700;
      display:flex;
      align-items:center;
      justify-content:center;
      text-align:center;
      backdrop-filter: blur(2px);
    }

    .placedPlayer{
      background:#111827;
      color:#fff;
      border-radius:12px;
      padding:8px 10px;
      font-size:.9rem;
      width:100%;
      text-align:center;
      cursor:grab;
    }
    .placedPlayerImg {
      width: 45px;
      height: 45px;
      object-fit: cover;
      border-radius: 50%;
     display: block;
     margin: 0 auto;
    }

    .controls{
      display:flex;
      gap:10px;
      flex-wrap:wrap;
      margin-top:14px;
    }
    
    .flR{
        float:right;
    }

    @media (max-width: 980px){
      .grid{grid-template-columns:1fr}
      .field{min-height:560px}
    }
  </style>
</head>
<body>

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

<main class="container">

  <?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 ($team): ?>
    <div class="grid">
      <!-- Left side -->
      <div class="card">
        <h2><?= h($team['team_name']) ?></h2>
        <p>
          <span class="badge"><?= h($team['sport']) ?></span>
          <span class="badge"><?= h($team['season']) ?></span>
        </p>

        <div class="notice">
          Drag players from this list onto the field/court to build a lineup.
        </div>

        <div class="playerList" id="playerList">
          <?php if (empty($roster)): ?>
            <p class="notice">No players on this team yet.</p>
          <?php else: ?>
            <?php foreach ($roster as $m): ?>
              <div
                class="playerChip"
                draggable="true"
                data-player-id="<?= (int)$m['user_id'] ?>"
                data-player-name="<?= h($m['first_name']. ' ' . $m['last_name']) ?>"
                data-player-photo="images/<?= h($m['photo']) ?>"
              >
                <img src = "images/<?= h($m['photo'])?>", width = 80px, height= 100px>
                <div class = "flR"><strong><?= h($m['first_name'] . ' ' . $m['last_name']) ?></strong>
                <span>
                  #<?= h($m['jersey_num'] ?? '—') ?> • <?= h($m['position'] ?? 'No position') ?>
                </span>
                </div>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>
        

        <div class="controls">
          <button class="btn secondary" type="button" onclick="resetLineup()">Reset Layout</button>
          <a class="btn secondary" href="coach_dashboard.php?team_id=<?= (int)$team_id ?>">Back</a>

        </div>
      </div>

      <!-- Right side -->
      <div class="fieldWrap">
        <h3>Lineup Area</h3>
        <p>Sport-based layout for <strong><?= h($team['sport']) ?></strong>.</p>
        
        <div class="field <?= strtolower(h($team['sport'])) ?>" id="field">
          <div class="fieldLabel"><?= h($team['sport']) ?> Layout</div>

          <?php
          $sport = strtolower($team['sport']);

          if ($sport === 'basketball') {
            $zones = [
              ['PG', '45%', '70%'],
              ['SG', '25%', '55%'],
              ['SF', '75%', '55%'],
              ['PF', '35%', '30%'],
              ['C',  '65%', '30%'],
            ];
          } elseif ($sport === 'soccer') {
            $zones = [
              ['GK',  '10%', '50%'],
              ['LB', '30%', '25%'],
              ['CB', '22%', '62%'],
              ['CB', '22%', '38%'],
              ['RB', '30%', '75%'],
              ['LM', '49%', '15%'],
              ['CM', '50%', '50%'],
              ['RM', '49%', '85%'],
              ['LW', '70%', '25%'],
              ['RW', '70%', '75%'],
              ['S', '80%', '50%'],
            ];
          } elseif ($sport === 'football') {
            $zones = [
              ['WR', '14%', '57%'],
              ['LT', '30%', '61%'],
              ['LG', '40%', '58%'],
              ['C',  '50%', '55%'],
              ['RG', '60%', '58%'],
              ['RT', '70%', '61%'],
              ['TE', '77%', '68%'],
              ['WR', '89%', '57%'],
              ['QB', '50%', '65%'],
              ['FB', '50%', '75%'],
              ['RB', '50%', '85%'],
              
              
              ['S', '30%', '15%'],
              ['CB', '14%', '42%'],
              ['DE', '30%', '45%'],
              ['DT', '40%', '45%'],
              ['NT', '50%', '45%'],
              ['DT', '60%', '45%'],
              ['DE', '70%', '45%'],
              ['MLB', '40%', '34%'],
              ['OLB', '60%', '30%'],
              ['CB', '89%', '42%'],
              ['S', '70%', '15%'],
              
              ['K', '10%', '90%'],
              ['P', '22%', '90%'],
              ['LS', '34%', '90%'],
  ];
          } else { // baseball default
            $zones = [
              ['P',  '50%', '55%'],
              ['C',  '50%', '82%'],
              ['1B', '75%', '62%'],
              ['2B', '62%', '40%'],
              ['SS', '38%', '40%'],
              ['3B', '25%', '62%'],
              ['LF', '18%', '18%'],
              ['CF', '50%', '10%'],
              ['RF', '82%', '18%'],
            ];
          }

          foreach ($zones as $i => $z):
          ?>
            <div
              class="dropZone"
              data-zone="<?= h($z[0]) ?>"
              style="left:calc(<?= h($z[1]) ?> - 60px); top:calc(<?= h($z[2]) ?> - 26px);"
            >
              <?= h($z[0]) ?>
            </div>
          <?php endforeach; ?>
        </div>
        
        <br>
        
        <!--coach option buttons-->
        <!--view/Edit team roster-->
        <button class="btn secondary" type="button"
        onclick="document.location='team_roster.php?team_id=<?= (int)$team_id ?>'">View/Edit Team Roster</button>
        <!--view/edit team events-->
        <button class="btn secondary" type="button" onclick = "document.location='add_event.php'">Add/Edit Team Events</button>
        
        
      </div>

    </div>
  <?php endif; ?>
  
</main>

<script>
  let draggedPlayer = null;

  function wireDragSources() {
    document.querySelectorAll('.playerChip, .placedPlayer').forEach(el => {
      el.addEventListener('dragstart', function () {
        draggedPlayer = this;
      });
    });
  }

  document.querySelectorAll('.dropZone').forEach(zone => {
    zone.addEventListener('dragover', function (e) {
      e.preventDefault();
    });

    zone.addEventListener('drop', function (e) {
      e.preventDefault();
      if (!draggedPlayer) return;

      // if dragging from sidebar, clone it into field
      if (draggedPlayer.classList.contains('playerChip')) {
        const placed = document.createElement('div');
        placed.className = 'placedPlayer';
        placed.draggable = true;
        const img = document.createElement('img');
        img.src = draggedPlayer.dataset.playerPhoto;
        img.alt = draggedPlayer.dataset.playerName;
        img.title = draggedPlayer.dataset.playerName;
        img.className = 'placedPlayerImg';
        
placed.appendChild(img);
        this.innerHTML = '';
        this.appendChild(placed);
      } else {
        // moving an already placed player
        const oldParent = draggedPlayer.parentElement;
        if (oldParent && oldParent.classList.contains('dropZone')) {
          oldParent.textContent = oldParent.dataset.zone;
        }
        this.innerHTML = '';
        this.appendChild(draggedPlayer);
      }

      wireDragSources();
      draggedPlayer = null;
    });
  });

  function resetLineup() {
    document.querySelectorAll('.dropZone').forEach(zone => {
      zone.textContent = zone.dataset.zone;
      
    });
    draggedPlayer = null;
  }

  wireDragSources();
  
</script>

</body>
</html>