<?php
declare(strict_types=1);
require_once __DIR__ . '/config.php';

if (!empty($_SESSION['user_id'])) {
    header('Location: dashboard.php');
    exit;
}

$error = '';

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

    if ($username === '' || $password === '') {
        $error = 'Please enter your username and password.';
    } else {
        $stmt = $pdo->prepare('SELECT id, username, password, role FROM users WHERE username = ? LIMIT 1');
        $stmt->execute([$username]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password'])) {
            session_regenerate_id(true);
            $_SESSION['user_id'] = (int)$user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];
            header('Location: dashboard.php');
            exit;
        } else {
            $error = 'Invalid login details.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Gotalist Login</title>
  <link rel="stylesheet" href="assets/css/styles.css" />
</head>
<body>
  <div class="container">
    <div class="form-card">
      <div class="brand" style="margin-bottom:1rem;">
        <span class="brand-mark">G</span>
        <span>Gotalist Members</span>
      </div>
      <h1 style="font-size:2rem;">Login</h1>
      <p class="muted">Access your training library, modules, media, and downloads.</p>

      <?php if ($error): ?>
        <div class="error"><?php echo h($error); ?></div>
      <?php endif; ?>

      <form method="post" action="">
        <label for="username">Username</label>
        <input id="username" name="username" type="text" maxlength="60" required>

        <label for="password">Password</label>
        <input id="password" name="password" type="password" maxlength="100" required>

        <div class="btn-row">
          <button class="btn btn-primary" type="submit">Login</button>
          <a class="btn btn-secondary" href="register.php">Create Account</a>
        </div>
      </form>
    </div>
  </div>
</body>
</html>
