<?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'] ?? '') !== 'super_admin') {
  die("Access denied. Super admins only.");
}

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

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

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

// ---- Handle actions ----
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = $_POST['action'] ?? '';
  $target_user_id = (int)($_POST['user_id'] ?? 0);

  if ($target_user_id <= 0) {
    $errors[] = "Invalid user selected.";
  }

  // ---- Delete player account ----
  if ($action === 'delete_player' && empty($errors)) {
    if ($target_user_id === $current_admin_id) {
      $errors[] = "You cannot delete your own account.";
    } else {

      // 1. Delete related rostered players first (foreign key fix)
      $del = $dbc->prepare("DELETE FROM rostered_players WHERE user_id = ?");
      $del->bind_param("i", $target_user_id);
      $del->execute();

      // 2. Delete the user
      $q = "DELETE FROM users
            WHERE user_id = $target_user_id
              AND role = 'player'
            LIMIT 1";
      $r = mysqli_query($dbc, $q);

      if ($r && mysqli_affected_rows($dbc) > 0) {
        $success = "Player deleted.";
      } else {
        $errors[] = "Could not delete player. Only player accounts can be deleted here.";
      }
    }
  }
}

// ---- Pull all users ----
$users = [];
$q = "SELECT user_id, first_name, last_name, email, role
      FROM users
      ORDER BY role DESC, last_name ASC, first_name ASC";
$r = mysqli_query($dbc, $q);

if ($r) {
  while ($row = mysqli_fetch_assoc($r)) {
    $users[] = $row;
  }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Manage Users • 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; --danger:#991b1b;
    }
    *{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:flex-start;
      gap:30px;
      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 {
      color:#fff;
      text-decoration:none;
      padding:8px 12px;
      border-radius:8px;
      background:#2B784A;
    }

    .container{max-width:1100px; margin:22px auto; padding:0 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)
    }
    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}
    .btn{
      background:var(--dark); color:#fff; border:none; border-radius:12px;
      padding:8px 10px; cursor:pointer;
    }
    .btn.danger{background:var(--danger)}
    .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}
    .notice{
      padding:10px 12px; border-radius:12px; border:1px dashed var(--line);
      background:#fafafa; color:#334155; margin-top:10px
    }
    .error{
      background:#fef2f2;border:1px solid #fecaca;color:#991b1b;
      padding:10px 12px;border-radius:12px;margin:10px 0
    }
    .success{
      background:#ecfdf5;border:1px solid #bbf7d0;color:#166534;
      padding:10px 12px;border-radius:12px;margin:10px 0
    }
    .actionForms{
      display:flex;
      gap:8px;
      flex-wrap:wrap;
    }
  </style>
</head>
<body>

<header class="topbar">
  <div class="brand">
    <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>

<main class="container">
  <div class="card">
    <h2>Manage Users</h2>
    <p>Admin-only page to delete player accounts.</p>

    <?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 ($success): ?>
      <div class="success">✅ <?= h($success) ?></div>
    <?php endif; ?>

    <?php if (empty($users)): ?>
      <p class="notice">No users found.</p>
    <?php else: ?>
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Role</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($users as $u): ?>
            <tr>
              <td><?= h($u['first_name'] . ' ' . $u['last_name']) ?></td>
              <td><?= h($u['email']) ?></td>
              <td>
                <?php if ($u['role'] === 'admin'): ?>
                  <span class="badge ok">Coach</span>
                <?php else: ?>
                  <span class="badge">Player</span>
                <?php endif; ?>
              </td>
              <td>
                <div class="actionForms">

                  <?php if ($u['role'] === 'player'): ?>
                    <form method="post" action="manage_users.php"
                          onsubmit="return confirm('Delete this player account?');">
                      <input type="hidden" name="action" value="delete_player">
                      <input type="hidden" name="user_id" value="<?= (int)$u['user_id'] ?>">
                      <button class="btn danger" type="submit">Delete Player</button>
                    </form>
                  <?php else: ?>
                    <?php if ((int)$u['user_id'] === $current_admin_id): ?>
                      <span class="notice">This is you</span>
                    <?php else: ?>
                      <span class="notice">Coach account</span>
                    <?php endif; ?>
                  <?php endif; ?>

                </div>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    <?php endif; ?>
  </div>
</main>

</body>
</html>
