<?php
// ─── POST /api/users/update.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();

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

$id        = (int)   ($_POST['record_id']  ?? 0);
$username  = trim($_POST['username']        ?? '');
$user_type = trim($_POST['user_type']       ?? '');
$team_id   = trim($_POST['team_id']         ?? '');
$password  = trim($_POST['password']        ?? ''); // blank = don't change

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

$db->run(
    "UPDATE users SET username = ?, user_type = ?, team_id = ?
     WHERE  record_id = ?",
    [$username, $user_type, $team_id, $id]
);

// Only update password if provided
if ($password !== '') {
    $hashed = hash('sha256', $password);
    $db->run("UPDATE users SET user_password = ? WHERE record_id = ?", [$hashed, $id]);
}

Response::ok(null, 'User updated.');