<?php
rate_limit('register', 10);
$d = input();
$errors = v_required($d, ['name','email','password']);
if ($errors) json_error('Validation failed', 422, $errors);
$email = strtolower(trim((string)$d['email']));
if (!v_email($email)) json_error('Invalid email', 422);
if (strlen((string)$d['password']) < 8) json_error('Password must be at least 8 characters', 422);

$exists = db()->prepare('SELECT id FROM users WHERE email=?');
$exists->execute([$email]);
if ($exists->fetch()) json_error('Email already registered', 409);

$hash = password_hash((string)$d['password'], PASSWORD_BCRYPT);
$stmt = db()->prepare('INSERT INTO users (name,email,phone,password,role_id,status) VALUES (?,?,?,?,?,?)');
$stmt->execute([
    v_str($d, 'name', 150),
    $email,
    v_str($d, 'phone', 40) ?: null,
    $hash,
    4, // staff by default
    'pending',
]);
$id = (int)db()->lastInsertId();
audit('user.register', 'user', $id, $email);
json_ok(['id' => $id], 'Registration submitted. An admin will activate your account.');
