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

if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    $payload = require_auth();
    $uid     = $payload['uid'];
    $b       = body();

    $fields = [];
    $params = [];
    foreach (['display_name', 'bio', 'photo_url', 'position'] 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);
}

$payload = require_auth();
$stmt    = db()->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$payload['uid']]);
$row = $stmt->fetch();
if (!$row) json_err('User not found', 404);

$role = resolve_role($row['email'], $row['role']);

json_ok([
    'id'           => $row['id'],
    'email'        => $row['email'],
    'display_name' => $row['display_name'],
    'role'         => $role,
    'bio'          => $row['bio'],
    'photo_url'    => $row['photo_url'],
    'position'     => $row['position'],
    'team_id'      => $row['team_id'],
    'created_at'   => $row['created_at'],
]);
