<?php
require_once __DIR__ . '/../config/user_functions.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../config/users_local.php';

header('Content-Type: application/json');

// only admin can inline-edit
if (!isset($_SESSION['user']) || (($_SESSION['user']['role'] ?? '') !== 'admin')) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Forbidden']);
    exit;
}

$username = trim($_POST['username'] ?? '');
$field    = trim($_POST['field'] ?? '');
$value    = $_POST['value'] ?? '';

if ($username === '' || $field === '') {
    echo json_encode(['success' => false, 'error' => 'Missing parameters']);
    exit;
}

$users = get_users();
$map = [];
foreach ($users as $u) {
    if (!empty($u['username'])) {
        $map[$u['username']] = $u;
    }
}

if (!isset($map[$username])) {
    echo json_encode(['success' => false, 'error' => 'User not found']);
    exit;
}

$allowed_fields = ['name','role','active'];
if (!in_array($field, $allowed_fields, true)) {
    echo json_encode(['success' => false, 'error' => 'Field not allowed']);
    exit;
}

$user = $map[$username];

if ($field === 'name') {
    $user['name'] = $value;
}
elseif ($field === 'role') {
    $allowed_roles = ['admin','supervisor','warehouse','viewer'];
    if (!in_array($value, $allowed_roles, true)) {
        echo json_encode(['success' => false, 'error' => 'Role not allowed']);
        exit;
    }
    $user['role'] = $value;
}
elseif ($field === 'active') {
    $user['active'] = ($value === '1');
}

$map[$username] = $user;
save_users($map);

echo json_encode(['success' => true]);
