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

$errors = [];
$values = [
  'role' => 'player',
  'first_name' => '',
  'last_name' => '',
  'email' => ''
];

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

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

  $values['role'] = trim($_POST['role'] ?? 'player');
  $values['first_name'] = trim($_POST['first_name'] ?? '');
  $values['last_name'] = trim($_POST['last_name'] ?? '');
  $values['email'] = trim($_POST['email'] ?? '');
  $password = (string)($_POST['password'] ?? '');

  if (!in_array($values['role'], ['admin','player'], true)) {
    $errors[] = "Please choose a valid account type.";
  }

  if ($values['first_name'] === '') $errors[] = "First name is required.";
  if ($values['last_name'] === '') $errors[] = "Last name is required.";

  if ($values['email'] === '' || !filter_var($values['email'], FILTER_VALIDATE_EMAIL)) {
    $errors[] = "A valid email is required.";
  }

  if (strlen($password) < 6) {
    $errors[] = "Password must be at least 6 characters.";
  }

  if (empty($errors)) {
    $emailEsc = mysqli_real_escape_string($dbc, $values['email']);
    $q = "SELECT user_id FROM users WHERE email='$emailEsc' LIMIT 1";
    $r = mysqli_query($dbc, $q);

    if ($r && mysqli_num_rows($r) > 0) {
      $errors[] = "That email is already registered.";
    }
  }

  if (empty($errors)) {
    $roleEsc = mysqli_real_escape_string($dbc, $values['role']);
    $firstEsc = mysqli_real_escape_string($dbc, $values['first_name']);
    $lastEsc = mysqli_real_escape_string($dbc, $values['last_name']);
    $emailEsc = mysqli_real_escape_string($dbc, $values['email']);
    $hash = password_hash($password, PASSWORD_DEFAULT);
    $hashEsc = mysqli_real_escape_string($dbc, $hash);

    $q = "
      INSERT INTO users (role, first_name, last_name, email, password_hash)
      VALUES ('$roleEsc', '$firstEsc', '$lastEsc', '$emailEsc', '$hashEsc')
    ";
    $r = mysqli_query($dbc, $q);

    if ($r) {
      header("Location: index.php?msg=account_created");
      exit();
    } else {
      $errors[] = "Database error: " . mysqli_error($dbc);
    }
  }
}
?>

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Signup • Sideline</title>
  <link rel="icon" type="image/x-icon" href="images/sideline_logo.ico">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body{
      font-family: system-ui, Arial;
      background: transparent;
      margin: 0;
      min-height: 100vh;
    }
    .bgLayer {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: -1;
      background:
        linear-gradient(to top, rgba(43,120,74,0.7), rgba(17,24,39,1), rgba(37,31,71,0.9)),
        url('images/sideline_tick.png'),
        url('images/sign-up_bg.png');
      background-size: cover, 5000px auto, cover;
      background-position: center, top, center;
      background-repeat: no-repeat, no-repeat, no-repeat;
    }
    .wrap{
       max-width:900px;
       margin:30px auto;
       padding:0 16px
    }
    .card{
       background: rgba(255, 255, 255, 0.45);
       border: 1px solid rgba(255, 25, 255, 0.3);
       border-radius: 16px;
       padding: 16px;
       box-shadow: 0 10px 30px rgba(2,6,23,.15);
       height: 100%;
       display: flex;
       flex-direction: column;
    }
    .signupLayout {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 20px;
      align-items: stretch;
    }

    .welcomeCard {
      background: rgba(255, 255, 255, 0.45);
      border: 1px solid rgba(255, 25, 255, 0.3);
      border-radius: 16px;
      padding: 16px;
      box-shadow: 0 10px 30px rgba(2,6,23,.15);

    }
    label{
       display:block;
       margin:10px 0 6px;
       color:#FFFFFF;
       font-size:.9rem
    }
    input, select {
       width: 100%;
       padding: 10px 12px;
       border: 1px solid #e5e7eb;
       border-radius: 12px;
       box-sizing: border-box;
    }
    .btn{
       background:#251F47;
       color:#fff;border:none;
       border-radius:12px;
       padding:10px 12px;
       cursor:pointer
    }
    .btn.secondary{
       background:#fff;
       color:#111827;
       border:1px solid #e5e7eb
    }
    .row {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 10px;
    }
    .split{
       display:flex;
       gap:10px;
       flex-wrap:
       wrap;
       margin-top:14px
    }
    .error{
       background:#fef2f2;
       border:1px solid #fecaca;
       color:#991b1b;
       padding:10px 12px;
       border-radius:12px;
       margin:10px 0
    }
      p{
        color:#FFFFFF;
      text-decoration:none;
      font-size:.9rem;
    }
    
  </style>
</head>
<body>
<div class="bgLayer"></div>
<div class="wrap signupLayout">
  <div class="card">
    <h1 style="color:#FFFFFF; text-align:center;">Signup</h1>
    <p style="color:#FFFFFF; text-align:center;">Create an account (Coach or Player).</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; ?>

    <form method="post" action="signup.php" novalidate>
      <label>Account Type</label>
      <select name="role" required>
        <option value="admin" <?= $values['role']==='admin' ? 'selected' : '' ?>>Coach</option>
        <option value="player" <?= $values['role']==='player' ? 'selected' : '' ?>>Player</option>
      </select>
      
      <div class="row">
          <div>
              <label>First Name</label>
              <input name="first_name" value="<?= h($values['first_name']) ?>" required>
          </div>
      <div>
          <label>Last Name</label>
          <input name="last_name" value="<?= h($values['last_name']) ?>" required>
      </div>
      </div>

      <label>Email</label>
      <input type="email" name="email" placeholder="coach@gmail.com" value="<?= h($values['email']) ?>" required>

      <label>Password</label>
      <input type="password" name="password" placeholder="Minimum 6 characters" required>

      <div class="split">
        <button class="btn" type="submit">Create Account</button>
        <a class="btn secondary" href="index.php" style="display:inline-block;text-decoration:none">Back to Login</a>
      </div>
    </form>
  </div>
  <div class="card welcomeCard" style="text-align:center;">
     <img src = "images/sideline_logo.png" alt = "sideline logo" style = "height: 200px; width: 200px; margin:auto;">
  <h2 style="color:#FFFFFF;">Welcome to the Sideline!</h2>
  <p>We are a sports management app built to simplify how coaches and players of youth and recreational
  sports organize their season. We consolidate scheduling, player & event management, team creation, and updates all in one streamlined application. 
  </p>
</div>
</div>
</body>
</html>