<?php
require_once __DIR__ . '/../config/helpers.php';
cors();

$uid    = $_GET['uid'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];
$db     = db();

if ($uid === '') json_err('Missing uid');

if ($method === 'GET') {
    $stmt = $db->prepare('SELECT * FROM users WHERE id = ?');
    $stmt->execute([$uid]);
    $row = $stmt->fetch();
    if (!$row) json_err('Not found', 404);
    unset($row['password_hash']);
    $row['role'] = resolve_role($row['email'], $row['role']);
    json_ok($row);
}

if ($method === 'PUT') {
    $payload = require_auth();
    // Users can only update themselves; admins can update anyone.
    if ($payload['role'] !== 'admin' && $payload['uid'] !== $uid) json_err('Forbidden', 403);

    $b = body();
    $fields = []; $params = [];
    foreach (['display_name','bio','photo_url','position','team_id','role'] as $f) {
        if (array_key_exists($f, $b)) { $fields[] = "$f = ?"; $params[] = $b[$f]; }
    }
    if (empty($fields)) json_err('Nothing to update');
    $params[] = $uid;
    $db->prepare('UPDATE users SET ' . implode(', ', $fields) . ' WHERE id = ?')->execute($params);

    $stmt = $db->prepare('SELECT * FROM users WHERE id = ?');
    $stmt->execute([$uid]);
    $row = $stmt->fetch();
    unset($row['password_hash']);
    $row['role'] = resolve_role($row['email'], $row['role']);
    json_ok($row);
}

json_err('Method not allowed', 405);
