<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/helpers.php';

$id = (int) ($_POST['id'] ?? 0);
if ($id <= 0 || empty($_FILES['foto'])) {
    json_fail('Usuario ou foto nao informado.');
}

$uploadDir = public_upload_path('fotos');
$name = 'usuario_' . $id . '_' . time() . '_' . basename($_FILES['foto']['name']);
$target = $uploadDir . '/' . $name;

if (!move_uploaded_file($_FILES['foto']['tmp_name'], $target)) {
    json_fail('Falha ao salvar foto.', 500);
}

$relative = 'uploads/fotos/' . $name;
$stmt = db()->prepare('UPDATE usuarios SET foto_url = ? WHERE id = ?');
$stmt->execute([$relative, $id]);

json_ok(['foto_url' => $relative]);

