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

$errors = [];

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $email = trim($_POST['email'] ?? '');
  $password = (string)($_POST['password'] ?? '');

  if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Enter a valid email.";
  if ($password === '') $errors[] = "Password is required.";

  if (empty($errors)) {
    $emailEsc = mysqli_real_escape_string($dbc, $email);

    $q = "SELECT user_id, role, first_name, last_name, password_hash
          FROM users
          WHERE email='$emailEsc'
          LIMIT 1";

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

    if ($r && mysqli_num_rows($r) === 1) {
      $row = mysqli_fetch_assoc($r);

      if (password_verify($password, $row['password_hash'])) {
        $_SESSION['user_id'] = (int)$row['user_id'];
        $_SESSION['role'] = $row['role'];
        $_SESSION['name'] = $row['first_name'] . ' ' . $row['last_name'];

        if (password_verify($password, $row['password_hash'])) {
    $_SESSION['user_id'] = (int)$row['user_id'];
    $_SESSION['role'] = $row['role'];
    $_SESSION['name'] = $row['first_name'] . ' ' . $row['last_name'];

    if ($row['role'] === 'super_admin') {
        header("Location: superadmin_dashboard.php");
    } elseif ($row['role'] === 'admin') {
        header("Location: coach_dashboard.php");
    } else {
        header("Location: player_home.php");
    }
    exit();
}
      }
    }

    $errors[] = "Invalid email or password.";
  }
}

$msg = $_GET['msg'] ?? '';
?>

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Login</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/login_gb.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);
    }
    .loginLayout {
      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{width:75%;padding:10px 5px;border:1px solid #e5e7eb;border-radius:12px}
    .btn{background:#251F47;color:#FFFFFF;border:none;border-radius:12px;padding:10px 12px;cursor:pointer}
    .btn.secondary{background:#fff;color:#000000;border:1px solid #e5e7eb}
    .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}
    .success{background:#ecfdf5;border:1px solid #bbf7d0;color:#166534;padding:10px 12px;border-radius:12px;margin:10px 0}
    .link{
      color:#FFFFFF;
      text-decoration:none;
      font-size:.9rem;
    }
    .link:hover{
      text-decoration:underline;
    }
    
    p{
        color:#FFFFFF;
      text-decoration:none;
      font-size:.9rem;
    }
    
    @media (max-width: 768px) {
    .loginLayout {
    grid-template-columns: 1fr;
  }
}
  </style>
</head>
<body>
<div class="bgLayer"></div>
<div class="wrap loginLayout">
<!-- Left: Log in card -->
  <div class="card">
    <h2 style="color:#FFFFFF; text-align:center;">Login</h2>

    <?php if ($msg === 'account_created'): ?>
      <div class="success">Account created! You can log in now.</div>
    <?php endif; ?>

    <?php if (!empty($errors)): ?>
      <div class="error">
        <?php foreach ($errors as $e): ?>
          <p><?= h($e) ?></p>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
    
    <form method="post" action="index.php" novalidate>
      <label>Email</label>
      <input type="email" name="email" value="<?= h($_POST['email'] ?? '') ?>" required>

      <label>Password</label>
      <input type="password" name="password" required>
      <br>
      <a class="link" href="forgot_password.php">Forgot your password?</a>
      <br><br>

      <div class="split">
        <button class="btn" type="submit">Login</button>
        <a class="btn secondary" href="signup.php" style="display:inline-block;text-decoration:none">Sign up</a>
      </div>
    </form>
  </div>
    <!-- RIGHT: Welcome card -->
<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 back to 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 consolodate scheduling, player & event management, team creation, and updates into one streamlined application. 
  </p>
</div>
</div>
</body>
</html>