<?php
// POST /api/auth/create_user.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$currentUser = requireRole([1]);
$db          = getDB();

$username  = trim(post('username', ''));
$email     = trim(post('email', ''));
$password  = post('password', '');
$fullName  = trim(post('full_name', ''));
$roleId    = (int)post('role_id', 2);

if (!$username || !$email || !$password) apiError('Username, email and password required.', 422);
if (strlen($password) < 8) apiError('Password must be at least 8 characters.', 422);

// Check unique
$check = $db->prepare("SELECT COUNT(*) FROM users WHERE username = ? OR email = ?");
$check->execute([$username, $email]);
if ((int)$check->fetchColumn() > 0) apiError('Username or email already exists.', 422);

$hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
$db->prepare("INSERT INTO users (username, email, password_hash, full_name, role_id, is_active) VALUES (?, ?, ?, ?, ?, 1)")
   ->execute([$username, $email, $hash, $fullName, $roleId]);

apiSuccess(['id' => (int)$db->lastInsertId()], 'User created.', 201);
