<?php
declare(strict_types=1);
require_once __DIR__ . '/../helpers.php';
require_post();
$adminUserId = as_int(get_post('admin_user_id'));
require_admin($adminUserId);
$userId = as_int(get_post('user_id'));
$fullName = get_post('full_name');
$username = get_post('username');
$password = get_post('password');
$role = get_post('role', 'cashier');
if (!validate_role($role)) respond(['success' => false, 'message' => 'Invalid role'], 400);

$conn = db();
if ($password !== '') {
    $hash = password_hash($password, PASSWORD_DEFAULT);
    $stmt = $conn->prepare('UPDATE users SET full_name = ?, username = ?, password_hash = ?, role = ?, updated_at = NOW() WHERE id = ?');
    $stmt->bind_param('ssssi', $fullName, $username, $hash, $role, $userId);
} else {
    $stmt = $conn->prepare('UPDATE users SET full_name = ?, username = ?, role = ?, updated_at = NOW() WHERE id = ?');
    $stmt->bind_param('sssi', $fullName, $username, $role, $userId);
}
if (!$stmt->execute()) respond(['success' => false, 'message' => 'Unable to update user: ' . $stmt->error], 400);
log_activity($adminUserId, 'UPDATE_USER', "Updated user {$fullName} ({$username}) role {$role}");
respond(['success' => true, 'message' => 'User updated']);
