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

session_start();
require 'conexion.php';

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

$user_id = $_SESSION['user_id'];
$avatar = $_POST['avatar'] ?? '';

if (empty($avatar)) {
    echo json_encode(['success' => false, 'error' => 'Avatar no válido.']);
    exit;
}

// Validar que el formato tenga al menos 3 partes (seed, color, shape)
$avatar_parts = explode('|', $avatar);
if (count($avatar_parts) !== 3) {
    echo json_encode(['success' => false, 'error' => 'Formato de avatar inválido.']);
    exit;
}

$sql = "UPDATE accounts SET Avatar = ? WHERE ID = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('si', $avatar, $user_id);

if ($stmt->execute()) {
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'error' => 'Error al actualizar.']);
}

$stmt->close();
$conn->close();
?>