<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'No session']);
    exit;
}

if (isset($_FILES['avatar'])) {
    $dir = 'assets/avatars/';
    if (!file_exists($dir)) {
        mkdir($dir, 0777, true);
    }

    $filename = $_SESSION['user_id'] . '.jpg';
    $path = $dir . $filename;

    if (move_uploaded_file($_FILES['avatar']['tmp_name'], $path)) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error al guardar archivo']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'No file received']);
}