<?php
declare(strict_types=1);
require __DIR__ . '/bootstrap.php';

require_method('POST');
$data = read_json();

$fullName = trim((string) ($data['full_name'] ?? ''));
$email = strtolower(trim((string) ($data['email'] ?? '')));
$password = (string) ($data['password'] ?? '');
$learningGoal = trim((string) ($data['learning_goal'] ?? 'Student'));

if ($fullName === '' || !filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($password) < 8) {
    json_response([
        'error' => 'Provide a full name, valid email and password of at least 8 characters.',
    ], 422);
}

$pdo = db();
$existingStmt = $pdo->prepare('SELECT id FROM users WHERE email = :email LIMIT 1');
$existingStmt->execute(['email' => $email]);
if ($existingStmt->fetch()) {
    json_response(['error' => 'An account already exists for that email.'], 409);
}

$role = 'student';
if ($email === 'ronald@kingsoftonline.com') {
    $adminCount = (int) $pdo->query(
        "SELECT COUNT(*) FROM users WHERE role IN ('trainer', 'admin')"
    )->fetchColumn();
    if ($adminCount === 0) {
        $role = 'admin';
    }
}

$stmt = $pdo->prepare(
    'INSERT INTO users (full_name, email, password_hash, learning_goal, role)
     VALUES (:full_name, :email, :password_hash, :learning_goal, :role)'
);
$stmt->execute([
    'full_name' => $fullName,
    'email' => $email,
    'password_hash' => password_hash($password, PASSWORD_DEFAULT),
    'learning_goal' => $learningGoal,
    'role' => $role,
]);

$userId = (int) $pdo->lastInsertId();
$course = active_course();
ensure_enrollment($userId, (int) $course['id']);
$_SESSION['user_id'] = $userId;

json_response([
    'user' => current_user(),
    'course' => $course,
], 201);
