<?php
// ─── POST /api/users/create.php ──────────────────────────────────────────
define('ROOT', dirname(__DIR__, 2));
require_once ROOT . '/core/DB.php';
require_once ROOT . '/core/Response.php';
require_once ROOT . '/core/Auth.php';

$user = Auth::require();
$db   = DB::get();

// Only admin/dev can create users
$role = Auth::role($user);
if (!in_array($role, ['admin','dev','test'])) Response::error('Permission denied.', 403);

$username  = trim($_POST['username']  ?? '');
$password  = trim($_POST['password']  ?? '');
$user_type = trim($_POST['user_type'] ?? '');
$team_id   = trim($_POST['team_id']   ?? '');

if (!$username)  Response::error('Username is required.');
if (!$password)  Response::error('Password is required.');
if (!$user_type) Response::error('Role is required.');

// Check username unique
$exists = $db->scalar("SELECT COUNT(*) FROM users WHERE username = ?", [$username]);
if ($exists) Response::error("Username '$username' already exists.");

// SHA-256 hash — matches existing system
$hashed = hash('sha256', $password);

$db->run(
    "INSERT INTO users (username, user_password, user_type, team_id)
     VALUES (?, ?, ?, ?)",
    [$username, $hashed, $user_type, $team_id]
);

$record_id = (int) $db->lastId();

Response::ok(['record_id' => $record_id], 'User created.');