<?php
session_start();
require_once(__DIR__ . '/config/settings.php');
header('Content-Type: application/json');

$data = json_decode(file_get_contents('php://input'), true);
$user = $_SESSION['user_id'];
$char = $data['name'];
$totalToAdd = $data['str'] + $data['agi'] + $data['vit'] + $data['ene'];

try {
    $dsn = "dblib:host={$db_settings['host']}:1433;dbname={$db_settings['name']}";
    $pdo = new PDO($dsn, $db_settings['user'], $db_settings['pass']);
    
    // Validar puntos disponibles
    $stmt = $pdo->prepare("SELECT LevelUpPoint FROM Character WHERE Name = ? AND AccountID = ?");
    $stmt->execute([$char, $user]);
    $currentPoints = $stmt->fetchColumn();

    if ($totalToAdd > $currentPoints) {
        echo json_encode(['error' => 'No tienes suficientes puntos']);
        exit;
    }

    // Actualizar Stats
    $sql = "UPDATE Character SET 
            Strength += ?, Agility += ?, Vitality += ?, Energy += ?, 
            LevelUpPoint -= ? 
            WHERE Name = ? AND AccountID = ?";
    $pdo->prepare($sql)->execute([$data['str'], $data['agi'], $data['vit'], $data['ene'], $totalToAdd, $char, $user]);

    echo json_encode(['success' => true]);
} catch (Exception $e) {
    echo json_encode(['error' => 'Error de servidor']);
}