<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../config/db.php';
include __DIR__ . '/../includes/header.php';

$error = null; $success = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $name = trim($_POST['name'] ?? '');
  $email = trim($_POST['email'] ?? '');
  $pass = $_POST['password'] ?? '';
  $pass2 = $_POST['password_confirm'] ?? '';

  if (!$name || !$email || !$pass || !$pass2) {
    $error = 'All fields are required';
  } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $error = 'Invalid email';
  } elseif ($pass !== $pass2) {
    $error = 'Passwords do not match';
  } else {
    $stmt = db()->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res->fetch_assoc()) {
      $error = 'Email already registered';
    } else {
      $hash = password_hash($pass, PASSWORD_DEFAULT);
      $stmt = db()->prepare("INSERT INTO users (name, email, password_hash) VALUES (?,?,?)");
      $stmt->bind_param("sss", $name, $email, $hash);
      $success = $stmt->execute();
      if ($success) {
        $_SESSION['user_id'] = (int)$stmt->insert_id;
        $_SESSION['user_name'] = $name ?: $email;
        header('Location: /WATCHING/index.php'); exit;
      } else {
        $error = 'Failed to register';
      }
    }
  }
}
?>
<div class="container glass-card" style="padding:16px;margin-top:24px;max-width:520px;">
  <h2>Register</h2>
  <?php if ($error): ?><div class="alert error"><?php echo htmlspecialchars($error); ?></div><?php endif; ?>
  <form method="post">
    <label>Name</label><input class="input" name="name" required>
    <label>Email</label><input class="input" type="email" name="email" required>
    <label>Password</label><input class="input" type="password" name="password" required>
    <label>Confirm Password</label><input class="input" type="password" name="password_confirm" required>
    <button class="btn" type="submit" style="margin-top:10px;">Create Account</button>
  </form>
  <div style="margin-top:10px;">
    Already have an account? <a href="/WATCHING/pages/login.php">Login</a>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>